Skip to content

Commit

Permalink
Trim multiple selector string, that is a string of selectors separate…
Browse files Browse the repository at this point in the history
…d by a comma, passed to the style engine.

This is so we can correctly align prettified content,
and remove spaces between multiple selectors with the same styles.
  • Loading branch information
ramonjd committed Nov 18, 2022
1 parent 8e83fff commit 77c4092
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
6 changes: 4 additions & 2 deletions packages/style-engine/class-wp-style-engine-css-rule.php
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,10 @@ public function get_css( $should_prettify = false, $indent_count = 0 ) {
$declarations_indent = $should_prettify ? $indent_count + 1 : 0;
$suffix = $should_prettify ? "\n" : '';
$spacer = $should_prettify ? ' ' : '';
$selector = $should_prettify ? str_replace( ',', ",\n", $this->get_selector() ) : $this->get_selector();
$css_declarations = $this->declarations->get_declarations_string( $should_prettify, $declarations_indent );
// Trims any multiple selectors strings.
$selector_trimmed = implode( ',', array_map( 'trim', explode( ',', $this->get_selector() ) ) );
$selector = $should_prettify ? str_replace( array( ',' ), ",\n", $selector_trimmed ) : $selector_trimmed;
$css_declarations = $this->declarations->get_declarations_string( $should_prettify, $declarations_indent );

if ( empty( $css_declarations ) ) {
return '';
Expand Down
27 changes: 27 additions & 0 deletions phpunit/style-engine/class-wp-style-engine-css-rule-test.php
Original file line number Diff line number Diff line change
Expand Up @@ -141,4 +141,31 @@ public function test_should_prettify_css_rule_output() {

$this->assertSame( $expected, $css_rule->get_css( true ) );
}

/**
* Tests that a string of multiple selectors is trimmed.
*
* @covers ::get_css
*/
public function test_should_trim_multiple_selectors() {
$selector = '.poirot, .poirot:active, #miss-marple > .st-mary-mead ';
$input_declarations = array(
'margin-left' => '0',
'font-family' => 'Detective Sans',
);
$css_declarations = new WP_Style_Engine_CSS_Declarations_Gutenberg( $input_declarations );
$css_rule = new WP_Style_Engine_CSS_Rule_Gutenberg( $selector, $css_declarations );
$expected = '.poirot,.poirot:active,#miss-marple > .st-mary-mead{margin-left:0;font-family:Detective Sans;}';

$this->assertSame( $expected, $css_rule->get_css(), 'Return value should be not prettified.' );

$expected_prettified = '.poirot,
.poirot:active,
#miss-marple > .st-mary-mead {
margin-left: 0;
font-family: Detective Sans;
}';

$this->assertSame( $expected_prettified, $css_rule->get_css( true ), 'Return value should be prettified with new lines and indents.' );
}
}

0 comments on commit 77c4092

Please sign in to comment.