@wordpress/global-styles-ui
Version:
Global Styles UI components for WordPress.
1 lines • 12.9 kB
Source Map (JSON)
{"version":3,"file":"hooks.cjs","names":["useContext","GlobalStylesContext","useMemo","getStyle","useCallback","setStyle","getSetting","setSetting","__","useSelect","coreStore","removePropertiesFromObject","isVariationWithProperties","mergeGlobalStyles","getResolvedValue"],"sources":["../src/hooks.ts"],"sourcesContent":["import { useCallback, useContext, useMemo } from '@wordpress/element';\nimport { useSelect } from '@wordpress/data';\nimport { store as coreStore } from '@wordpress/core-data';\nimport { __ } from '@wordpress/i18n';\nimport {\n\tgetResolvedValue,\n\tgetStyle,\n\tsetStyle,\n\tgetSetting,\n\tsetSetting,\n\tmergeGlobalStyles,\n} from '@wordpress/global-styles-engine';\nimport type {\n\tGlobalStylesConfig,\n\tStyleVariation,\n} from '@wordpress/global-styles-engine';\nimport { GlobalStylesContext } from './context';\nimport { removePropertiesFromObject, isVariationWithProperties } from './utils';\n\n/**\n * Hook to get and set style values with memoization.\n *\n * @param path The path to the style value.\n * @param blockName The name of the block, if applicable.\n * @param readFrom Which source to read from: \"base\" (theme), \"user\" (customizations), or \"merged\" (final result). Defaults to \"merged\".\n * @param shouldDecodeEncode Whether to decode and encode the style value.\n * @param state Optional style state path. Supports viewport states (e.g. `@mobile`),\n * pseudo-selector states (e.g. `:hover`) or both (e.g. `@mobile.:hover`).\n * Pseudo selectors are always read/written as nested keys.\n * @return An array containing the style value and a function to set the style\n * value.\n *\n * @example\n * const [ color, setColor ] = useStyle<string>( 'color.text', 'core/button', 'merged' );\n * const [ hoverColor, setHoverColor ] = useStyle<string>( 'color.text', 'core/button', 'user', true, ':hover' );\n */\nexport function useStyle< T = any >(\n\tpath: string,\n\tblockName?: string,\n\treadFrom: 'base' | 'user' | 'merged' = 'merged',\n\tshouldDecodeEncode: boolean = true,\n\tstate?: string\n) {\n\tconst { user, base, merged, onChange } = useContext( GlobalStylesContext );\n\tconst statePathParts = state?.split( '.' ).filter( Boolean ) ?? [];\n\tconst pseudoSelectorState = statePathParts.find( ( value ) =>\n\t\tvalue.startsWith( ':' )\n\t);\n\tconst statePathWithoutPseudo = statePathParts\n\t\t.filter( ( value ) => ! value.startsWith( ':' ) )\n\t\t.join( '.' );\n\tconst stylePath = [ path, statePathWithoutPseudo ]\n\t\t.filter( Boolean )\n\t\t.join( '.' );\n\n\tlet sourceValue = merged;\n\tif ( readFrom === 'base' ) {\n\t\tsourceValue = base;\n\t} else if ( readFrom === 'user' ) {\n\t\tsourceValue = user;\n\t}\n\n\tconst styleValue = useMemo< T | undefined >( () => {\n\t\tconst rawValue = getStyle< T >(\n\t\t\tsourceValue,\n\t\t\tstylePath,\n\t\t\tblockName,\n\t\t\tshouldDecodeEncode\n\t\t);\n\t\tif ( pseudoSelectorState ) {\n\t\t\treturn (\n\t\t\t\t( rawValue as Record< string, T | undefined > )?.[\n\t\t\t\t\tpseudoSelectorState\n\t\t\t\t] ?? ( {} as T )\n\t\t\t);\n\t\t}\n\t\treturn rawValue;\n\t}, [\n\t\tsourceValue,\n\t\tstylePath,\n\t\tblockName,\n\t\tshouldDecodeEncode,\n\t\tpseudoSelectorState,\n\t] );\n\n\tconst setStyleValue = useCallback(\n\t\t( newValue: T | undefined ) => {\n\t\t\tlet valueToSet: any = newValue;\n\t\t\tif ( pseudoSelectorState ) {\n\t\t\t\tconst fullCurrentValue = getStyle(\n\t\t\t\t\tuser,\n\t\t\t\t\tstylePath,\n\t\t\t\t\tblockName,\n\t\t\t\t\tfalse\n\t\t\t\t);\n\t\t\t\tvalueToSet = {\n\t\t\t\t\t...( fullCurrentValue as object ),\n\t\t\t\t\t[ pseudoSelectorState ]: newValue,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst newGlobalStyles = setStyle< any >(\n\t\t\t\tuser,\n\t\t\t\tstylePath,\n\t\t\t\tvalueToSet,\n\t\t\t\tblockName\n\t\t\t);\n\t\t\tonChange( newGlobalStyles );\n\t\t},\n\t\t[ user, onChange, stylePath, blockName, pseudoSelectorState ]\n\t);\n\n\treturn [ styleValue, setStyleValue ] as const;\n}\n\n/**\n * Hook to get and set setting values with memoization.\n *\n * @param path The path to the setting value.\n * @param blockName The name of the block, if applicable.\n * @param readFrom Which source to read from: \"base\" (theme), \"user\" (customizations), or \"merged\" (final result). Defaults to \"merged\".\n * @return An array containing the setting value and a function to set the\n * setting value.\n *\n * @example\n * const [ fontSize, setFontSize ] = useSetting<string>( 'fontSize', 'core/button', 'merged' );\n */\nexport function useSetting< T = any >(\n\tpath: string,\n\tblockName?: string,\n\treadFrom: 'base' | 'user' | 'merged' = 'merged'\n) {\n\tconst { user, base, merged, onChange } = useContext( GlobalStylesContext );\n\n\tlet sourceValue = merged;\n\tif ( readFrom === 'base' ) {\n\t\tsourceValue = base;\n\t} else if ( readFrom === 'user' ) {\n\t\tsourceValue = user;\n\t}\n\tconst settingValue = useMemo(\n\t\t() => getSetting< T >( sourceValue, path, blockName ),\n\t\t[ sourceValue, path, blockName ]\n\t);\n\n\tconst setSettingValue = useCallback(\n\t\t( newValue: T | undefined ) => {\n\t\t\tconst newGlobalStyles = setSetting< T >(\n\t\t\t\tuser,\n\t\t\t\tpath,\n\t\t\t\tnewValue,\n\t\t\t\tblockName\n\t\t\t);\n\t\t\tonChange( newGlobalStyles );\n\t\t},\n\t\t[ user, onChange, path, blockName ]\n\t);\n\n\treturn [ settingValue, setSettingValue ] as const;\n}\n\nconst EMPTY_ARRAY: StyleVariation[] = [];\n\n/**\n * Checks whether a style variation is empty.\n * @param root0\n * @param root0.title\n * @param root0.settings\n * @param root0.styles\n */\nfunction hasThemeVariation( {\n\ttitle,\n\tsettings,\n\tstyles,\n}: StyleVariation ): boolean {\n\treturn (\n\t\ttitle === __( 'Default' ) ||\n\t\tObject.keys( settings || {} ).length > 0 ||\n\t\tObject.keys( styles || {} ).length > 0\n\t);\n}\n\n/**\n * Fetches the current theme style variations that contain only the specified properties\n * and merges them with the user config.\n * @param properties\n */\nexport function useCurrentMergeThemeStyleVariationsWithUserConfig(\n\tproperties: string[] = []\n): StyleVariation[] {\n\tconst { variationsFromTheme } = useSelect( ( select ) => {\n\t\tconst _variationsFromTheme =\n\t\t\tselect(\n\t\t\t\tcoreStore\n\t\t\t).__experimentalGetCurrentThemeGlobalStylesVariations?.();\n\n\t\treturn {\n\t\t\tvariationsFromTheme: _variationsFromTheme || EMPTY_ARRAY,\n\t\t};\n\t}, [] );\n\n\tconst { user: userVariation } = useContext( GlobalStylesContext );\n\n\treturn useMemo( () => {\n\t\t// Create default variation from base, not user - this fixes the \"Default adapts\" issue\n\t\tconst clonedUserVariation = structuredClone( userVariation );\n\t\t// Get user variation and remove the settings for the given property.\n\t\tconst userVariationWithoutProperties = removePropertiesFromObject(\n\t\t\tclonedUserVariation,\n\t\t\tproperties\n\t\t);\n\t\tuserVariationWithoutProperties.title = __( 'Default' );\n\n\t\tconst variationsWithPropertiesAndBase = (\n\t\t\tvariationsFromTheme as StyleVariation[]\n\t\t )\n\t\t\t.filter( ( variation: StyleVariation ) => {\n\t\t\t\treturn isVariationWithProperties( variation, properties );\n\t\t\t} )\n\t\t\t.map( ( variation: StyleVariation ) => {\n\t\t\t\treturn mergeGlobalStyles(\n\t\t\t\t\tuserVariationWithoutProperties,\n\t\t\t\t\tvariation\n\t\t\t\t);\n\t\t\t} );\n\n\t\tconst variationsByProperties = [\n\t\t\tuserVariationWithoutProperties,\n\t\t\t...variationsWithPropertiesAndBase,\n\t\t];\n\n\t\treturn variationsByProperties?.length\n\t\t\t? variationsByProperties.filter( hasThemeVariation )\n\t\t\t: [];\n\t}, [ properties, userVariation, variationsFromTheme ] );\n}\n\n/**\n * Resolves `ref` pointers and theme-relative (`file:./…`) URLs in a style\n * object's `background` sub-tree, for display. The Global Styles screens\n * render inside the package's own public `BlockEditorProvider`, which strips\n * the Symbol-keyed settings the background panel would otherwise resolve\n * these against, so the screens resolve them before passing styles down.\n *\n * @param style A style object whose `background` values may contain `ref`\n * pointers or theme-relative URLs.\n * @return The style object with its `background` values resolved.\n */\nexport function useStyleWithResolvedBackground(\n\tstyle: GlobalStylesConfig[ 'styles' ]\n) {\n\tconst { merged } = useContext( GlobalStylesContext );\n\treturn useMemo( () => {\n\t\tif ( ! style?.background ) {\n\t\t\treturn style;\n\t\t}\n\t\tconst tree = { styles: merged?.styles, _links: merged?._links };\n\t\tconst background: Record< string, any > = {};\n\t\tfor ( const [ key, value ] of Object.entries(\n\t\t\tstyle.background as Record< string, any >\n\t\t) ) {\n\t\t\t// getResolvedValue writes the resolved URL onto the object it is\n\t\t\t// given: pass a copy so the context config keeps its\n\t\t\t// theme-relative path.\n\t\t\tbackground[ key ] = getResolvedValue(\n\t\t\t\tvalue && typeof value === 'object' ? { ...value } : value,\n\t\t\t\ttree\n\t\t\t);\n\t\t}\n\t\treturn { ...style, background };\n\t}, [ style, merged ] );\n}\n\n/**\n * Whether the current user may edit custom CSS in Global Styles.\n *\n * The capability is reported as a link on the global styles record rather\n * than as a user capability.\n */\nexport function useCanEditCSS(): boolean {\n\treturn useSelect( ( select ) => {\n\t\tconst { getEntityRecord, __experimentalGetCurrentGlobalStylesId } =\n\t\t\tselect( coreStore );\n\n\t\tconst globalStylesId = __experimentalGetCurrentGlobalStylesId();\n\t\tconst globalStyles = globalStylesId\n\t\t\t? getEntityRecord( 'root', 'globalStyles', globalStylesId )\n\t\t\t: undefined;\n\n\t\treturn !! ( globalStyles as GlobalStylesConfig )?._links?.[\n\t\t\t'wp:action-edit-css'\n\t\t];\n\t}, [] );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,SAAgB,SACf,MACA,WACA,WAAuC,UACvC,qBAA8B,MAC9B,OACC;CACD,MAAM,EAAE,MAAM,MAAM,QAAQ,cAAA,GAAaA,mBAAAA,WAAAA,CAAYC,aAAAA,mBAAoB;CACzE,MAAM,iBAAiB,OAAO,MAAO,GAAI,CAAC,CAAC,OAAQ,OAAQ,KAAK,CAAC;CACjE,MAAM,sBAAsB,eAAe,MAAQ,UAClD,MAAM,WAAY,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