Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Style engine: migrate functions, classes and tests #3199

Closed
Closed
Show file tree
Hide file tree
Changes from 15 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
154 changes: 154 additions & 0 deletions src/wp-includes/style-engine.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
<?php
/**
* Style engine: Public functions
*
* This file contains a variety of public functions developers can use to interact with
* the Style Engine API.
*
* @package WordPress
* @subpackage StyleEngine
* @since 6.1.0
*/


/**
* Global public interface method to generate styles from a single style object, e.g.,
* the value of a block's attributes.style object or the top level styles in theme.json.
* See: https://developer.wordpress.org/block-editor/reference-guides/theme-json-reference/theme-json-living/#styles and
* https://developer.wordpress.org/block-editor/reference-guides/block-api/block-supports/
*
* Example usage:
*
* $styles = wp_style_engine_get_styles( array( 'color' => array( 'text' => '#cccccc' ) ) );
* // Returns `array( 'css' => 'color: #cccccc', 'declarations' => array( 'color' => '#cccccc' ), 'classnames' => 'has-color' )`.
*
* @access public
* @since 6.1.0
*
* @param array $block_styles The style object.
* @param array $options {
* Optional. An array of options. Default empty array.
*
* @type string|null $context An identifier describing the origin of the style object, e.g., 'block-supports' or 'global-styles'. Default is `null`.
* When set, the style engine will attempt to store the CSS rules, where a selector is also passed.
* @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`.
* @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 }`,
* otherwise, the value will be a concatenated string of CSS declarations.
* }
*
* @return array {
* @type string $css A CSS ruleset or declarations block formatted to be placed in an HTML `style` attribute or tag.
* @type string[] $declarations An associative array of CSS definitions, e.g., array( "$property" => "$value", "$property" => "$value" ).
* @type string $classnames Classnames separated by a space.
* }
*/
function wp_style_engine_get_styles( $block_styles, $options = array() ) {
$options = wp_parse_args(
$options,
array(
'selector' => null,
'context' => null,
'convert_vars_to_classnames' => false,
)
);

$parsed_styles = WP_Style_Engine::parse_block_styles( $block_styles, $options );

// Output.
$styles_output = array();

if ( ! empty( $parsed_styles['declarations'] ) ) {
$styles_output['css'] = WP_Style_Engine::compile_css( $parsed_styles['declarations'], $options['selector'] );
$styles_output['declarations'] = $parsed_styles['declarations'];
if ( ! empty( $options['context'] ) ) {
WP_Style_Engine::store_css_rule( $options['context'], $options['selector'], $parsed_styles['declarations'] );
}
}

if ( ! empty( $parsed_styles['classnames'] ) ) {
$styles_output['classnames'] = implode( ' ', array_unique( $parsed_styles['classnames'] ) );
}

return array_filter( $styles_output );
}

/**
* Returns compiled CSS from a collection of selectors and declarations.
* Useful for returning a compiled stylesheet from any collection of CSS selector + declarations.
*
* Example usage:
* $css_rules = array( array( 'selector' => '.elephant-are-cool', 'declarations' => array( 'color' => 'gray', 'width' => '3em' ) ) );
* $css = wp_style_engine_get_stylesheet_from_css_rules( $css_rules );
* // Returns `.elephant-are-cool{color:gray;width:3em}`.
*
* @since 6.1.0
*
* @param array $css_rules {
* Required. A collection of CSS rules.
*
* @type array ...$0 {
* @type string $selector A CSS selector.
* @type string[] $declarations An associative array of CSS definitions, e.g., array( "$property" => "$value", "$property" => "$value" ).
* }
* }
* @param array $options {
* Optional. An array of options. Default empty array.
*
* @type string|null $context An identifier describing the origin of the style object, e.g., 'block-supports' or 'global-styles'. Default is 'block-supports'.
* When set, the style engine will attempt to store the CSS rules.
* @type bool $optimize Whether to optimize the CSS output, e.g., combine rules. Default is `false`.
* @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.
* }
*
* @return string A string of compiled CSS declarations, or empty string.
*/
function wp_style_engine_get_stylesheet_from_css_rules( $css_rules, $options = array() ) {
if ( empty( $css_rules ) ) {
return '';
}

$options = wp_parse_args(
$options,
array(
'context' => null,
)
);

$css_rule_objects = array();
foreach ( $css_rules as $css_rule ) {
if ( empty( $css_rule['selector'] ) || empty( $css_rule['declarations'] ) || ! is_array( $css_rule['declarations'] ) ) {
continue;
}

if ( ! empty( $options['context'] ) ) {
WP_Style_Engine::store_css_rule( $options['context'], $css_rule['selector'], $css_rule['declarations'] );
}

$css_rule_objects[] = new WP_Style_Engine_CSS_Rule( $css_rule['selector'], $css_rule['declarations'] );
}

if ( empty( $css_rule_objects ) ) {
return '';
}

return WP_Style_Engine::compile_stylesheet_from_css_rules( $css_rule_objects, $options );
}

/**
* Returns compiled CSS from a store, if found.
*
* @since 6.1.0
*
* @param string $context A valid context name, corresponding to an existing store key.
* @param array $options {
* Optional. An array of options. Default empty array.
*
* @type bool $optimize Whether to optimize the CSS output, e.g., combine rules. Default is `false`.
* @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.
* }
*
* @return string A compiled CSS string.
*/
function wp_style_engine_get_stylesheet_from_context( $context, $options = array() ) {
return WP_Style_Engine::compile_stylesheet_from_css_rules( WP_Style_Engine::get_store( $context )->get_all_rules(), $options );
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
<?php
/**
* WP_Style_Engine_CSS_Declarations
*
* Holds, sanitizes and prints CSS rules declarations
*
* @package WordPress
* @subpackage StyleEngine
* @since 6.1.0
*/

/**
* Class WP_Style_Engine_CSS_Declarations.
*
* Holds, sanitizes, processes and prints CSS declarations for the style engine.
*
* @access private
* @since 6.1.0
*/
class WP_Style_Engine_CSS_Declarations {
Copy link
Contributor

@costdev costdev Sep 9, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While this is intended to be private, it's open not just for instantiation, but extension.

Some thoughts:

  • Should this be considered private? Why?
  • If so, should this be a final class to at least block extension, or do we extend/plan to extend this class?
  • What else could be done? (I appreciate that something like an allowlist using an optimized debug_backtrace for the caller of the constructor is essentially the only way to "properly" lock it down though, so not suggesting that).

Same applies to all instances in the PR.

@peterwilsoncc do you have any thoughts here?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

or do we extend/plan to extend this class

I'm not sure of the strategy right now.

I expect that there is no plan to extend. Since this comes from a Gutenberg package, we expect to version it.

Backwards compat will foil that I guess. 🤷

Happy to take any advice onboard!

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@azaozz Do you have any thoughts on this?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@costdev thanks for the ping.

If this is intended to be private, "core use only", it will perhaps have to be locked in a closure like the current Webfonts code is. That will ensure it can be updated in the future without concerns about backwards compatibility.

If not locked, back-compat will have to be maintained, even if the class is final.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @azaozz! If it's not locked and back-compat has to be maintained, I don't think there would be any benefit in having @access private. Would you agree?

Copy link
Member Author

@ramonjd ramonjd Sep 9, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it will perhaps have to be locked in a closure like the current Webfonts code is.

Thanks for the advice here.

I think the class in question (WP_Style_Engine_CSS_Declarations), and the following, other, new classes:

  • WP_Style_Engine_CSS_Rule
  • WP_Style_Engine_CSS_Rules_Store
  • WP_Style_Engine_Processor

should be fairly stable. Maintaining backwards compatibility will be expected and, I hope, not overly tortuous.

I'll remove @access private from these.

WP_Style_Engine, on the other hand, is the primary integration point and provides the bulk of the functionality.

I expect it will have to be updated more frequently, especially given that this is a new API.

In that case, do folks think it's safer to refactor WP_Style_Engine to something similar to what's happening in webfonts? https://github.com/ramonjd/wordpress-develop/blob/bb0cbe3f557d16714ca109a28c2877d178adc94f/src/wp-includes/script-loader.php#L3059-L3058

cc @aristath and @andrewserong for thoughts

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WP_Style_Engine, on the other hand, is the primary integration point and provides the bulk of the functionality.

I think even this one is pretty stable, and good for us to commit to maintaining for backwards compatibility. The protected methods can be added to or rearranged safely in future versions, but the public methods appear to be ones that have been pretty stable in Gutenberg lately, and I think would be good to commit to in the long-term. I'd lean toward keeping this PR as-is.


/**
* An array of CSS declarations (property => value pairs).
*
* @since 6.1.0
*
* @var array
*/
protected $declarations = array();

/**
* Constructor for this object.
*
* If a `$declarations` array is passed, it will be used to populate
* the initial $declarations prop of the object by calling add_declarations().
*
* @since 6.1.0
*
* @param string[] $declarations An associative array of CSS definitions, e.g., array( "$property" => "$value", "$property" => "$value" ).
*/
public function __construct( $declarations = array() ) {
$this->add_declarations( $declarations );
}

/**
* Adds a single declaration.
*
* @since 6.1.0
*
* @param string $property The CSS property.
* @param string $value The CSS value.
*
* @return WP_Style_Engine_CSS_Declarations Returns the object to allow chaining methods.
*/
public function add_declaration( $property, $value ) {
// Sanitizes the property.
$property = $this->sanitize_property( $property );
// Bails early if the property is empty.
if ( empty( $property ) ) {
return $this;
}

// Trims the value. If empty, bail early.
$value = trim( $value );
if ( '' === $value ) {
return $this;
}

// Adds the declaration property/value pair.
$this->declarations[ $property ] = $value;

return $this;
}

/**
* Removes a single declaration.
*
* @since 6.1.0
*
* @param string $property The CSS property.
*
* @return WP_Style_Engine_CSS_Declarations Returns the object to allow chaining methods.
*/
public function remove_declaration( $property ) {
unset( $this->declarations[ $property ] );
return $this;
}

/**
* Adds multiple declarations.
*
* @since 6.1.0
*
* @param array $declarations An array of declarations.
*
* @return WP_Style_Engine_CSS_Declarations Returns the object to allow chaining methods.
*/
public function add_declarations( $declarations ) {
foreach ( $declarations as $property => $value ) {
$this->add_declaration( $property, $value );
}
return $this;
}

/**
* Removes multiple declarations.
*
* @since 6.1.0
*
* @param array $properties An array of properties.
*
* @return WP_Style_Engine_CSS_Declarations Returns the object to allow chaining methods.
*/
public function remove_declarations( $properties = array() ) {
foreach ( $properties as $property ) {
$this->remove_declaration( $property );
}
return $this;
}

/**
* Gets the declarations array.
*
* @since 6.1.0
*
* @return array
*/
public function get_declarations() {
return $this->declarations;
}

/**
* Filters a CSS property + value pair.
*
* @since 6.1.0
*
* @param string $property The CSS property.
* @param string $value The value to be filtered.
* @param string $spacer The spacer between the colon and the value. Defaults to an empty string.
*
* @return string The filtered declaration or an empty string.
*/
protected static function filter_declaration( $property, $value, $spacer = '' ) {
$filtered_value = wp_strip_all_tags( $value, true );
if ( '' !== $filtered_value ) {
return safecss_filter_attr( "{$property}:{$spacer}{$filtered_value}" );
}
return '';
}

/**
* Filters and compiles the CSS declarations.
*
* @since 6.1.0
*
* @param bool $should_prettify Whether to add spacing, new lines and indents.
* @param number $indent_count The number of tab indents to apply to the rule. Applies if `prettify` is `true`.
*
* @return string The CSS declarations.
*/
public function get_declarations_string( $should_prettify = false, $indent_count = 0 ) {
$declarations_array = $this->get_declarations();
$declarations_output = '';
$indent = $should_prettify ? str_repeat( "\t", $indent_count ) : '';
$suffix = $should_prettify ? ' ' : '';
$suffix = $should_prettify && $indent_count > 0 ? "\n" : $suffix;
$spacer = $should_prettify ? ' ' : '';

foreach ( $declarations_array as $property => $value ) {
$filtered_declaration = static::filter_declaration( $property, $value, $spacer );
if ( $filtered_declaration ) {
$declarations_output .= "{$indent}{$filtered_declaration};$suffix";
}
}
return rtrim( $declarations_output );
}

/**
* Sanitizes property names.
*
* @since 6.1.0
*
* @param string $property The CSS property.
*
* @return string The sanitized property name.
*/
protected function sanitize_property( $property ) {
return sanitize_key( $property );
}
}
Loading