class-wp-style-engine.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  1. <?php
  2. /**
  3. * StyleEngine: WP_Style_Engine class
  4. *
  5. * This is the main class integrating all other WP_Style_Engine_* classes.
  6. *
  7. * @package WordPress
  8. * @subpackage StyleEngine
  9. * @since 6.1.0
  10. */
  11. /**
  12. * Class WP_Style_Engine.
  13. *
  14. * The Style Engine aims to provide a consistent API for rendering styling for blocks across both client-side and server-side applications.
  15. *
  16. * This class is final and should not be extended.
  17. * This class is for internal Core usage and is not supposed to be used by extenders (plugins and/or themes).
  18. * This is a low-level API that may need to do breaking changes. Please, use wp_style_engine_get_styles instead.
  19. *
  20. * @access private
  21. * @since 6.1.0
  22. */
  23. #[AllowDynamicProperties]
  24. final class WP_Style_Engine {
  25. /**
  26. * Style definitions that contain the instructions to
  27. * parse/output valid Gutenberg styles from a block's attributes.
  28. * For every style definition, the follow properties are valid:
  29. * - classnames => (array) an array of classnames to be returned for block styles. The key is a classname or pattern.
  30. * A value of `true` means the classname should be applied always. Otherwise, a valid CSS property (string)
  31. * to match the incoming value, e.g., "color" to match var:preset|color|somePresetSlug.
  32. * - css_vars => (array) an array of key value pairs used to generate CSS var values. The key is a CSS var pattern, whose `$slug` fragment will be replaced with a preset slug.
  33. * The value should be a valid CSS property (string) to match the incoming value, e.g., "color" to match var:preset|color|somePresetSlug.
  34. * - property_keys => (array) array of keys whose values represent a valid CSS property, e.g., "margin" or "border".
  35. * - path => (array) a path that accesses the corresponding style value in the block style object.
  36. * - value_func => (string) the name of a function to generate a CSS definition array for a particular style object. The output of this function should be `array( "$property" => "$value", ... )`.
  37. *
  38. * @since 6.1.0
  39. * @var array
  40. */
  41. const BLOCK_STYLE_DEFINITIONS_METADATA = array(
  42. 'color' => array(
  43. 'text' => array(
  44. 'property_keys' => array(
  45. 'default' => 'color',
  46. ),
  47. 'path' => array( 'color', 'text' ),
  48. 'css_vars' => array(
  49. 'color' => '--wp--preset--color--$slug',
  50. ),
  51. 'classnames' => array(
  52. 'has-text-color' => true,
  53. 'has-$slug-color' => 'color',
  54. ),
  55. ),
  56. 'background' => array(
  57. 'property_keys' => array(
  58. 'default' => 'background-color',
  59. ),
  60. 'path' => array( 'color', 'background' ),
  61. 'classnames' => array(
  62. 'has-background' => true,
  63. 'has-$slug-background-color' => 'color',
  64. ),
  65. ),
  66. 'gradient' => array(
  67. 'property_keys' => array(
  68. 'default' => 'background',
  69. ),
  70. 'path' => array( 'color', 'gradient' ),
  71. 'classnames' => array(
  72. 'has-background' => true,
  73. 'has-$slug-gradient-background' => 'gradient',
  74. ),
  75. ),
  76. ),
  77. 'border' => array(
  78. 'color' => array(
  79. 'property_keys' => array(
  80. 'default' => 'border-color',
  81. 'individual' => 'border-%s-color',
  82. ),
  83. 'path' => array( 'border', 'color' ),
  84. 'classnames' => array(
  85. 'has-border-color' => true,
  86. 'has-$slug-border-color' => 'color',
  87. ),
  88. ),
  89. 'radius' => array(
  90. 'property_keys' => array(
  91. 'default' => 'border-radius',
  92. 'individual' => 'border-%s-radius',
  93. ),
  94. 'path' => array( 'border', 'radius' ),
  95. ),
  96. 'style' => array(
  97. 'property_keys' => array(
  98. 'default' => 'border-style',
  99. 'individual' => 'border-%s-style',
  100. ),
  101. 'path' => array( 'border', 'style' ),
  102. ),
  103. 'width' => array(
  104. 'property_keys' => array(
  105. 'default' => 'border-width',
  106. 'individual' => 'border-%s-width',
  107. ),
  108. 'path' => array( 'border', 'width' ),
  109. ),
  110. 'top' => array(
  111. 'value_func' => array( self::class, 'get_individual_property_css_declarations' ),
  112. 'path' => array( 'border', 'top' ),
  113. 'css_vars' => array(
  114. 'color' => '--wp--preset--color--$slug',
  115. ),
  116. ),
  117. 'right' => array(
  118. 'value_func' => array( self::class, 'get_individual_property_css_declarations' ),
  119. 'path' => array( 'border', 'right' ),
  120. 'css_vars' => array(
  121. 'color' => '--wp--preset--color--$slug',
  122. ),
  123. ),
  124. 'bottom' => array(
  125. 'value_func' => array( self::class, 'get_individual_property_css_declarations' ),
  126. 'path' => array( 'border', 'bottom' ),
  127. 'css_vars' => array(
  128. 'color' => '--wp--preset--color--$slug',
  129. ),
  130. ),
  131. 'left' => array(
  132. 'value_func' => array( self::class, 'get_individual_property_css_declarations' ),
  133. 'path' => array( 'border', 'left' ),
  134. 'css_vars' => array(
  135. 'color' => '--wp--preset--color--$slug',
  136. ),
  137. ),
  138. ),
  139. 'spacing' => array(
  140. 'padding' => array(
  141. 'property_keys' => array(
  142. 'default' => 'padding',
  143. 'individual' => 'padding-%s',
  144. ),
  145. 'path' => array( 'spacing', 'padding' ),
  146. 'css_vars' => array(
  147. 'spacing' => '--wp--preset--spacing--$slug',
  148. ),
  149. ),
  150. 'margin' => array(
  151. 'property_keys' => array(
  152. 'default' => 'margin',
  153. 'individual' => 'margin-%s',
  154. ),
  155. 'path' => array( 'spacing', 'margin' ),
  156. 'css_vars' => array(
  157. 'spacing' => '--wp--preset--spacing--$slug',
  158. ),
  159. ),
  160. ),
  161. 'typography' => array(
  162. 'fontSize' => array(
  163. 'property_keys' => array(
  164. 'default' => 'font-size',
  165. ),
  166. 'path' => array( 'typography', 'fontSize' ),
  167. 'classnames' => array(
  168. 'has-$slug-font-size' => 'font-size',
  169. ),
  170. ),
  171. 'fontFamily' => array(
  172. 'property_keys' => array(
  173. 'default' => 'font-family',
  174. ),
  175. 'path' => array( 'typography', 'fontFamily' ),
  176. 'classnames' => array(
  177. 'has-$slug-font-family' => 'font-family',
  178. ),
  179. ),
  180. 'fontStyle' => array(
  181. 'property_keys' => array(
  182. 'default' => 'font-style',
  183. ),
  184. 'path' => array( 'typography', 'fontStyle' ),
  185. ),
  186. 'fontWeight' => array(
  187. 'property_keys' => array(
  188. 'default' => 'font-weight',
  189. ),
  190. 'path' => array( 'typography', 'fontWeight' ),
  191. ),
  192. 'lineHeight' => array(
  193. 'property_keys' => array(
  194. 'default' => 'line-height',
  195. ),
  196. 'path' => array( 'typography', 'lineHeight' ),
  197. ),
  198. 'textDecoration' => array(
  199. 'property_keys' => array(
  200. 'default' => 'text-decoration',
  201. ),
  202. 'path' => array( 'typography', 'textDecoration' ),
  203. ),
  204. 'textTransform' => array(
  205. 'property_keys' => array(
  206. 'default' => 'text-transform',
  207. ),
  208. 'path' => array( 'typography', 'textTransform' ),
  209. ),
  210. 'letterSpacing' => array(
  211. 'property_keys' => array(
  212. 'default' => 'letter-spacing',
  213. ),
  214. 'path' => array( 'typography', 'letterSpacing' ),
  215. ),
  216. ),
  217. );
  218. /**
  219. * Util: Extracts the slug in kebab case from a preset string, e.g., "heavenly-blue" from 'var:preset|color|heavenlyBlue'.
  220. *
  221. * @since 6.1.0
  222. *
  223. * @param string $style_value A single CSS preset value.
  224. * @param string $property_key The CSS property that is the second element of the preset string. Used for matching.
  225. *
  226. * @return string The slug, or empty string if not found.
  227. */
  228. protected static function get_slug_from_preset_value( $style_value, $property_key ) {
  229. if ( is_string( $style_value ) && is_string( $property_key ) && str_contains( $style_value, "var:preset|{$property_key}|" ) ) {
  230. $index_to_splice = strrpos( $style_value, '|' ) + 1;
  231. return _wp_to_kebab_case( substr( $style_value, $index_to_splice ) );
  232. }
  233. return '';
  234. }
  235. /**
  236. * Util: Generates a CSS var string, e.g., var(--wp--preset--color--background) from a preset string such as `var:preset|space|50`.
  237. *
  238. * @since 6.1.0
  239. *
  240. * @param string $style_value A single css preset value.
  241. * @param string[] $css_vars An associate array of css var patterns used to generate the var string.
  242. *
  243. * @return string The css var, or an empty string if no match for slug found.
  244. */
  245. protected static function get_css_var_value( $style_value, $css_vars ) {
  246. foreach ( $css_vars as $property_key => $css_var_pattern ) {
  247. $slug = static::get_slug_from_preset_value( $style_value, $property_key );
  248. if ( static::is_valid_style_value( $slug ) ) {
  249. $var = strtr(
  250. $css_var_pattern,
  251. array( '$slug' => $slug )
  252. );
  253. return "var($var)";
  254. }
  255. }
  256. return '';
  257. }
  258. /**
  259. * Util: Checks whether an incoming block style value is valid.
  260. *
  261. * @since 6.1.0
  262. *
  263. * @param string $style_value A single CSS preset value.
  264. *
  265. * @return bool
  266. */
  267. protected static function is_valid_style_value( $style_value ) {
  268. return '0' === $style_value || ! empty( $style_value );
  269. }
  270. /**
  271. * Stores a CSS rule using the provided CSS selector and CSS declarations.
  272. *
  273. * @since 6.1.0
  274. *
  275. * @param string $store_name A valid store key.
  276. * @param string $css_selector When a selector is passed, the function will return a full CSS rule `$selector { ...rules }`, otherwise a concatenated string of properties and values.
  277. * @param string[] $css_declarations An associative array of CSS definitions, e.g., array( "$property" => "$value", "$property" => "$value" ).
  278. *
  279. * @return void.
  280. */
  281. public static function store_css_rule( $store_name, $css_selector, $css_declarations ) {
  282. if ( empty( $store_name ) || empty( $css_selector ) || empty( $css_declarations ) ) {
  283. return;
  284. }
  285. static::get_store( $store_name )->add_rule( $css_selector )->add_declarations( $css_declarations );
  286. }
  287. /**
  288. * Returns a store by store key.
  289. *
  290. * @since 6.1.0
  291. *
  292. * @param string $store_name A store key.
  293. *
  294. * @return WP_Style_Engine_CSS_Rules_Store
  295. */
  296. public static function get_store( $store_name ) {
  297. return WP_Style_Engine_CSS_Rules_Store::get_store( $store_name );
  298. }
  299. /**
  300. * Returns classnames and CSS based on the values in a styles object.
  301. * Return values are parsed based on the instructions in BLOCK_STYLE_DEFINITIONS_METADATA.
  302. *
  303. * @since 6.1.0
  304. *
  305. * @param array $block_styles The style object.
  306. * @param array $options {
  307. * Optional. An array of options. Default empty array.
  308. *
  309. * @type bool $convert_vars_to_classnames Whether to skip converting incoming CSS var patterns, e.g., `var:preset|<PRESET_TYPE>|<PRESET_SLUG>`, to var( --wp--preset--* ) values. Default `false`.
  310. * @type string $selector Optional. When a selector is passed, the value of `$css` in the return value will comprise a full CSS rule `$selector { ...$css_declarations }`,
  311. * otherwise, the value will be a concatenated string of CSS declarations.
  312. * }
  313. *
  314. * @return array {
  315. * @type string $classnames Classnames separated by a space.
  316. * @type string[] $declarations An associative array of CSS definitions, e.g., array( "$property" => "$value", "$property" => "$value" ).
  317. * }
  318. */
  319. public static function parse_block_styles( $block_styles, $options ) {
  320. $parsed_styles = array(
  321. 'classnames' => array(),
  322. 'declarations' => array(),
  323. );
  324. if ( empty( $block_styles ) || ! is_array( $block_styles ) ) {
  325. return $parsed_styles;
  326. }
  327. // Collect CSS and classnames.
  328. foreach ( static::BLOCK_STYLE_DEFINITIONS_METADATA as $definition_group_key => $definition_group_style ) {
  329. if ( empty( $block_styles[ $definition_group_key ] ) ) {
  330. continue;
  331. }
  332. foreach ( $definition_group_style as $style_definition ) {
  333. $style_value = _wp_array_get( $block_styles, $style_definition['path'], null );
  334. if ( ! static::is_valid_style_value( $style_value ) ) {
  335. continue;
  336. }
  337. $parsed_styles['classnames'] = array_merge( $parsed_styles['classnames'], static::get_classnames( $style_value, $style_definition ) );
  338. $parsed_styles['declarations'] = array_merge( $parsed_styles['declarations'], static::get_css_declarations( $style_value, $style_definition, $options ) );
  339. }
  340. }
  341. return $parsed_styles;
  342. }
  343. /**
  344. * Returns classnames, and generates classname(s) from a CSS preset property pattern, e.g., '`var:preset|<PRESET_TYPE>|<PRESET_SLUG>`'.
  345. *
  346. * @since 6.1.0
  347. *
  348. * @param array $style_value A single raw style value or css preset property from the $block_styles array.
  349. * @param array $style_definition A single style definition from BLOCK_STYLE_DEFINITIONS_METADATA.
  350. *
  351. * @return array|string[] An array of CSS classnames, or empty array.
  352. */
  353. protected static function get_classnames( $style_value, $style_definition ) {
  354. if ( empty( $style_value ) ) {
  355. return array();
  356. }
  357. $classnames = array();
  358. if ( ! empty( $style_definition['classnames'] ) ) {
  359. foreach ( $style_definition['classnames'] as $classname => $property_key ) {
  360. if ( true === $property_key ) {
  361. $classnames[] = $classname;
  362. }
  363. $slug = static::get_slug_from_preset_value( $style_value, $property_key );
  364. if ( $slug ) {
  365. /*
  366. * Right now we expect a classname pattern to be stored in BLOCK_STYLE_DEFINITIONS_METADATA.
  367. * One day, if there are no stored schemata, we could allow custom patterns or
  368. * generate classnames based on other properties
  369. * such as a path or a value or a prefix passed in options.
  370. */
  371. $classnames[] = strtr( $classname, array( '$slug' => $slug ) );
  372. }
  373. }
  374. }
  375. return $classnames;
  376. }
  377. /**
  378. * Returns an array of CSS declarations based on valid block style values.
  379. *
  380. * @since 6.1.0
  381. *
  382. * @param array $style_value A single raw style value from $block_styles array.
  383. * @param array $style_definition A single style definition from BLOCK_STYLE_DEFINITIONS_METADATA.
  384. * @param array $options {
  385. * Optional. An array of options. Default empty array.
  386. *
  387. * @type bool $convert_vars_to_classnames Whether to skip converting incoming CSS var patterns, e.g., `var:preset|<PRESET_TYPE>|<PRESET_SLUG>`, to var( --wp--preset--* ) values. Default `false`.
  388. * }
  389. *
  390. * @return string[] An associative array of CSS definitions, e.g., array( "$property" => "$value", "$property" => "$value" ).
  391. */
  392. protected static function get_css_declarations( $style_value, $style_definition, $options = array() ) {
  393. if ( isset( $style_definition['value_func'] ) && is_callable( $style_definition['value_func'] ) ) {
  394. return call_user_func( $style_definition['value_func'], $style_value, $style_definition, $options );
  395. }
  396. $css_declarations = array();
  397. $style_property_keys = $style_definition['property_keys'];
  398. $should_skip_css_vars = isset( $options['convert_vars_to_classnames'] ) && true === $options['convert_vars_to_classnames'];
  399. /*
  400. * Build CSS var values from `var:preset|<PRESET_TYPE>|<PRESET_SLUG>` values, e.g, `var(--wp--css--rule-slug )`.
  401. * Check if the value is a CSS preset and there's a corresponding css_var pattern in the style definition.
  402. */
  403. if ( is_string( $style_value ) && str_contains( $style_value, 'var:' ) ) {
  404. if ( ! $should_skip_css_vars && ! empty( $style_definition['css_vars'] ) ) {
  405. $css_var = static::get_css_var_value( $style_value, $style_definition['css_vars'] );
  406. if ( static::is_valid_style_value( $css_var ) ) {
  407. $css_declarations[ $style_property_keys['default'] ] = $css_var;
  408. }
  409. }
  410. return $css_declarations;
  411. }
  412. /*
  413. * Default rule builder.
  414. * If the input contains an array, assume box model-like properties
  415. * for styles such as margins and padding.
  416. */
  417. if ( is_array( $style_value ) ) {
  418. // Bail out early if the `'individual'` property is not defined.
  419. if ( ! isset( $style_property_keys['individual'] ) ) {
  420. return $css_declarations;
  421. }
  422. foreach ( $style_value as $key => $value ) {
  423. if ( is_string( $value ) && str_contains( $value, 'var:' ) && ! $should_skip_css_vars && ! empty( $style_definition['css_vars'] ) ) {
  424. $value = static::get_css_var_value( $value, $style_definition['css_vars'] );
  425. }
  426. $individual_property = sprintf( $style_property_keys['individual'], _wp_to_kebab_case( $key ) );
  427. if ( $individual_property && static::is_valid_style_value( $value ) ) {
  428. $css_declarations[ $individual_property ] = $value;
  429. }
  430. }
  431. return $css_declarations;
  432. }
  433. $css_declarations[ $style_property_keys['default'] ] = $style_value;
  434. return $css_declarations;
  435. }
  436. /**
  437. * Style value parser that returns a CSS definition array comprising style properties
  438. * that have keys representing individual style properties, otherwise known as longhand CSS properties.
  439. * e.g., "$style_property-$individual_feature: $value;", which could represent the following:
  440. * "border-{top|right|bottom|left}-{color|width|style}: {value};" or,
  441. * "border-image-{outset|source|width|repeat|slice}: {value};"
  442. *
  443. * @since 6.1.0
  444. *
  445. * @param array $style_value A single raw style value from $block_styles array.
  446. * @param array $individual_property_definition A single style definition from BLOCK_STYLE_DEFINITIONS_METADATA representing an individual property of a CSS property, e.g., 'top' in 'border-top'.
  447. * @param array $options {
  448. * Optional. An array of options. Default empty array.
  449. *
  450. * @type bool $convert_vars_to_classnames Whether to skip converting incoming CSS var patterns, e.g., `var:preset|<PRESET_TYPE>|<PRESET_SLUG>`, to var( --wp--preset--* ) values. Default `false`.
  451. * }
  452. *
  453. * @return string[] An associative array of CSS definitions, e.g., array( "$property" => "$value", "$property" => "$value" ).
  454. */
  455. protected static function get_individual_property_css_declarations( $style_value, $individual_property_definition, $options = array() ) {
  456. if ( ! is_array( $style_value ) || empty( $style_value ) || empty( $individual_property_definition['path'] ) ) {
  457. return array();
  458. }
  459. /*
  460. * The first item in $individual_property_definition['path'] array tells us the style property, e.g., "border".
  461. * We use this to get a corresponding CSS style definition such as "color" or "width" from the same group.
  462. * The second item in $individual_property_definition['path'] array refers to the individual property marker, e.g., "top".
  463. */
  464. $definition_group_key = $individual_property_definition['path'][0];
  465. $individual_property_key = $individual_property_definition['path'][1];
  466. $should_skip_css_vars = isset( $options['convert_vars_to_classnames'] ) && true === $options['convert_vars_to_classnames'];
  467. $css_declarations = array();
  468. foreach ( $style_value as $css_property => $value ) {
  469. if ( empty( $value ) ) {
  470. continue;
  471. }
  472. // Build a path to the individual rules in definitions.
  473. $style_definition_path = array( $definition_group_key, $css_property );
  474. $style_definition = _wp_array_get( static::BLOCK_STYLE_DEFINITIONS_METADATA, $style_definition_path, null );
  475. if ( $style_definition && isset( $style_definition['property_keys']['individual'] ) ) {
  476. // Set a CSS var if there is a valid preset value.
  477. if ( is_string( $value ) && str_contains( $value, 'var:' ) && ! $should_skip_css_vars && ! empty( $individual_property_definition['css_vars'] ) ) {
  478. $value = static::get_css_var_value( $value, $individual_property_definition['css_vars'] );
  479. }
  480. $individual_css_property = sprintf( $style_definition['property_keys']['individual'], $individual_property_key );
  481. $css_declarations[ $individual_css_property ] = $value;
  482. }
  483. }
  484. return $css_declarations;
  485. }
  486. /**
  487. * Returns compiled CSS from css_declarations.
  488. *
  489. * @since 6.1.0
  490. *
  491. * @param string[] $css_declarations An associative array of CSS definitions, e.g., array( "$property" => "$value", "$property" => "$value" ).
  492. * @param string $css_selector When a selector is passed, the function will return a full CSS rule `$selector { ...rules }`, otherwise a concatenated string of properties and values.
  493. *
  494. * @return string A compiled CSS string.
  495. */
  496. public static function compile_css( $css_declarations, $css_selector ) {
  497. if ( empty( $css_declarations ) || ! is_array( $css_declarations ) ) {
  498. return '';
  499. }
  500. // Return an entire rule if there is a selector.
  501. if ( $css_selector ) {
  502. $css_rule = new WP_Style_Engine_CSS_Rule( $css_selector, $css_declarations );
  503. return $css_rule->get_css();
  504. }
  505. $css_declarations = new WP_Style_Engine_CSS_Declarations( $css_declarations );
  506. return $css_declarations->get_declarations_string();
  507. }
  508. /**
  509. * Returns a compiled stylesheet from stored CSS rules.
  510. *
  511. * @since 6.1.0
  512. *
  513. * @param WP_Style_Engine_CSS_Rule[] $css_rules An array of WP_Style_Engine_CSS_Rule objects from a store or otherwise.
  514. * @param array $options {
  515. * Optional. An array of options. Default empty array.
  516. *
  517. * @type bool $optimize Whether to optimize the CSS output, e.g., combine rules. Default is `false`.
  518. * @type bool $prettify Whether to add new lines and indents to output. Default is the test of whether the global constant `SCRIPT_DEBUG` is defined.
  519. * }
  520. *
  521. * @return string A compiled stylesheet from stored CSS rules.
  522. */
  523. public static function compile_stylesheet_from_css_rules( $css_rules, $options = array() ) {
  524. $processor = new WP_Style_Engine_Processor();
  525. $processor->add_rules( $css_rules );
  526. return $processor->get_css( $options );
  527. }
  528. }