Editor: Add missing WP_Theme_JSON::process_blocks_custom_css() method.

Follow up to [55192].

Props aristath, mamaduka, mukesh27, hellofromtonya.
Fixes #57621.


git-svn-id: https://develop.svn.wordpress.org/trunk@55216 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Felix Arntz 2023-02-03 18:23:55 +00:00
parent 97aeca6f73
commit 8900fdfd76
2 changed files with 76 additions and 1 deletions

View File

@ -1006,12 +1006,34 @@ class WP_Theme_JSON {
return $stylesheet;
}
/**
* Processes the CSS, to apply nesting.
*
* @since 6.2.0
*
* @param string $css The CSS to process.
* @param string $selector The selector to nest.
* @return string The processed CSS.
*/
protected function process_blocks_custom_css( $css, $selector ) {
$processed_css = '';
// Split CSS nested rules.
$parts = explode( '&', $css );
foreach ( $parts as $part ) {
$processed_css .= ( ! str_contains( $part, '{' ) )
? trim( $selector ) . '{' . trim( $part ) . '}' // If the part doesn't contain braces, it applies to the root level.
: trim( $selector . $part ); // Prepend the selector, which effectively replaces the "&" character.
}
return $processed_css;
}
/**
* Returns the global styles custom css.
*
* @since 6.2.0
*
* @return string
* @return string The global styles custom CSS.
*/
public function get_custom_css() {
// Add the global styles root CSS.

View File

@ -4624,4 +4624,57 @@ class Tests_Theme_wpThemeJson extends WP_UnitTestCase {
),
);
}
/**
* @dataProvider data_process_blocks_custom_css
*
* @param array $input An array containing the selector and css to test.
* @param string $expected Expected results.
*/
public function test_process_blocks_custom_css( $input, $expected ) {
$theme_json = new WP_Theme_JSON(
array(
'version' => WP_Theme_JSON::LATEST_SCHEMA,
'styles' => array(),
)
);
$reflection = new ReflectionMethod( $theme_json, 'process_blocks_custom_css' );
$reflection->setAccessible( true );
$this->assertEquals( $expected, $reflection->invoke( $theme_json, $input['css'], $input['selector'] ) );
}
/**
* Data provider.
*
* @return array[]
*/
public function data_process_blocks_custom_css() {
return array(
// Simple CSS without any child selectors.
'no child selectors' => array(
'input' => array(
'selector' => '.foo',
'css' => 'color: red; margin: auto;',
),
'expected' => '.foo{color: red; margin: auto;}',
),
// CSS with child selectors.
'with children' => array(
'input' => array(
'selector' => '.foo',
'css' => 'color: red; margin: auto; & .bar{color: blue;}',
),
'expected' => '.foo{color: red; margin: auto;}.foo .bar{color: blue;}',
),
// CSS with child selectors and pseudo elements.
'with children and pseudo elements' => array(
'input' => array(
'selector' => '.foo',
'css' => 'color: red; margin: auto; & .bar{color: blue;} &::before{color: green;}',
),
'expected' => '.foo{color: red; margin: auto;}.foo .bar{color: blue;}.foo::before{color: green;}',
),
);
}
}