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

Layout: Add layout aware margin styles output for blocks in global styles #47399

Closed
Show file tree
Hide file tree
Changes from 8 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
72 changes: 71 additions & 1 deletion lib/class-wp-theme-json-gutenberg.php
Original file line number Diff line number Diff line change
Expand Up @@ -1213,9 +1213,14 @@ protected function get_layout_styles( $block_metadata ) {
return $block_rules;
}

// Skip outputting layout styles if the block does not support layout or margin.
// For blocks that have margin but not layout support, only layout aware margin styles are output.
if ( isset( $block_metadata['name'] ) ) {
$block_type = WP_Block_Type_Registry::get_instance()->get_registered( $block_metadata['name'] );
if ( ! block_has_support( $block_type, array( '__experimentalLayout' ), false ) ) {
if (
! block_has_support( $block_type, array( '__experimentalLayout' ), false ) &&
! block_has_support( $block_type, array( 'spacing', 'margin' ), false )
Copy link
Contributor

Choose a reason for hiding this comment

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

Trying to wrap my head around what this condition is doing - if layout is not supported, when does it matter whether margin is supported or not?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Ah, I see the confusion here, I should add a comment to clarify.

This check is about what the current block supports rather than what the theme supports, so to support layout aware margins for blocks without layout support (e.g. heading, paragraph, image) we need to allow it to pass at this point. The check is primarily an early return so that for blocks that we know don't need any handling, we don't need to do any further lookups to theme settings, etc. Previously, that was just blocks that didn't support layout, but we now need the check to be layout + margin.

Further down in the function, we check $has_block_gap_support (that is, the theme has block gap support) before outputting the layout aware margin rules.

Copy link
Contributor

Choose a reason for hiding this comment

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

Got it, thanks for clarifying!

) {
return $block_rules;
}
}
Expand Down Expand Up @@ -1253,6 +1258,71 @@ protected function get_layout_styles( $block_metadata ) {
}
}

// If the theme has block gap support, and the block has margin values, add layout-aware margin styles.
$margin_value = static::get_property_value( $node, array( 'spacing', 'margin' ) );
if (
$has_block_gap_support &&
isset( $margin_value ) && '' !== $margin_value
) {
$margin_styles = gutenberg_style_engine_get_styles(
array( 'spacing' => array( 'margin' => $margin_value ) )
);

if ( ! empty( $margin_styles['css'] ) ) {
// Add layout aware margin rules for each supported layout type.
foreach ( $layout_definitions as $layout_definition_key => $layout_definition ) {
$class_name = sanitize_title( _wp_array_get( $layout_definition, array( 'className' ), '' ) );
$margin_rules = _wp_array_get( $layout_definition, array( 'marginStyles' ), array() );

if (
! empty( $class_name ) &&
! empty( $margin_rules )
) {
foreach ( $margin_rules as $margin_rule ) {
if (
isset( $margin_rule['selector'] ) &&
preg_match( $layout_selector_pattern, $margin_rule['selector'] ) &&
! empty( $margin_rule['rules'] )
) {
$declarations = array();
foreach ( $margin_rule['rules'] as $css_property => $css_value ) {
if ( is_string( $css_value ) ) {
if ( static::is_safe_css_declaration( $css_property, $css_value ) ) {
$declarations[] = array(
'name' => $css_property,
'value' => $css_value,
);
}
} elseif ( isset( $margin_styles['declarations'][ $css_property ] ) ) {
if ( static::is_safe_css_declaration( $css_property, $margin_styles['declarations'][ $css_property ] ) ) {
$declarations[] = array(
'name' => $css_property,
'value' => $margin_styles['declarations'][ $css_property ],
);
}
}
}
$layout_selector = sprintf(
'.%s%s%s',
$class_name,
$margin_rule['selector'],
$selector
);

$block_rules .= static::to_ruleset( $layout_selector, $declarations );
}
}
}
}
// Add layout aware margin rule for children of the root site blocks class.
$block_rules .= sprintf(
'.wp-site-blocks > * + %s {%s}',
$selector,
$margin_styles['css']
);
}
}

// If the block should have custom gap, add the gap styles.
if ( null !== $block_gap_value && false !== $block_gap_value && '' !== $block_gap_value ) {
foreach ( $layout_definitions as $layout_definition_key => $layout_definition ) {
Expand Down
46 changes: 46 additions & 0 deletions lib/theme.json
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,29 @@
"margin-block-end": "0"
}
}
],
"marginStyles": [
{
"selector": " > ",
"rules": {
"margin-block-start": "0",
"margin-bottom": null
}
},
{
"selector": " > * + ",
"rules": {
"margin-top": null,
"margin-bottom": null
}
},
{
"selector": " > *:last-child",
"rules": {
"margin-top": null,
"margin-block-end": "0"
}
}
]
},
"constrained": {
Expand Down Expand Up @@ -322,6 +345,29 @@
"margin-block-end": "0"
}
}
],
"marginStyles": [
{
"selector": " > ",
"rules": {
"margin-block-start": "0",
"margin-bottom": null
}
},
{
"selector": " > * + ",
"rules": {
"margin-top": null,
"margin-bottom": null
}
},
{
"selector": " > *:last-child",
"rules": {
"margin-top": null,
"margin-block-end": "0"
}
}
]
},
"flex": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -549,6 +549,29 @@ describe( 'global styles renderer', () => {
},
},
],
marginStyles: [
{
selector: ' > ',
rules: {
'margin-block-start': '0',
'margin-bottom': null,
},
},
{
selector: ' > * + ',
rules: {
'margin-top': null,
'margin-bottom': null,
},
},
{
selector: ' > *:last-child',
rules: {
'margin-top': null,
'margin-block-end': '0',
},
},
],
},
flex: {
name: 'flex',
Expand Down Expand Up @@ -664,6 +687,24 @@ describe( 'global styles renderer', () => {
':where(.wp-block-group.is-layout-flex) { gap: 2em; }'
);
} );

it( 'should return layout aware margin styles', () => {
const style = {
spacing: { margin: { top: '25px', bottom: '50px' } },
};

const layoutStyles = getLayoutStyles( {
tree: layoutDefinitionsTree,
style,
selector: '.wp-block-cover',
hasBlockGapSupport: true,
hasFallbackGapSupport: true,
} );

expect( layoutStyles ).toEqual(
'.is-layout-flow > .wp-block-cover { margin-block-start: 0; margin-bottom: 50px }.is-layout-flow > * + .wp-block-cover { margin-top: 25px; margin-bottom: 50px }.is-layout-flow > *:last-child.wp-block-cover { margin-top: 25px; margin-block-end: 0 }.wp-site-blocks > * + .wp-block-cover { margin-top: 25px; margin-bottom: 50px; }'
);
} );
} );

describe( 'getBlockSelectors', () => {
Expand Down Expand Up @@ -691,6 +732,7 @@ describe( 'global styles renderer', () => {
border: '.my-image img, .my-image .crop-area',
},
hasLayoutSupport: false,
hasMarginSupport: false,
},
} );
} );
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
} from '@wordpress/blocks';
import { useSelect } from '@wordpress/data';
import { useContext, useMemo } from '@wordpress/element';
import { getCSSRules } from '@wordpress/style-engine';
import { compileCSS, getCSSRules } from '@wordpress/style-engine';

/**
* Internal dependencies
Expand Down Expand Up @@ -356,6 +356,61 @@ export function getLayoutStyles( {
}
}

// If the theme has block support support, and the block has margin values, add layout-aware margin styles.
if (
hasBlockGapSupport &&
style?.spacing?.margin &&
tree?.settings?.layout?.definitions
) {
const marginString = compileCSS( {
spacing: { margin: style.spacing.margin },
} );

// Get margin rules keyed by CSS class name.
const marginRules = getCSSRules( {
spacing: { margin: style.spacing.margin },
} ).reduce(
( acc, rule ) => ( {
...acc,
[ kebabCase( rule.key ) ]: rule.value,
} ),
{}
);

if ( marginRules ) {
// Add layout aware margin rules for each supported layout type.
Object.values( tree.settings.layout.definitions ).forEach(
( { className, marginStyles } ) => {
if ( marginStyles?.length ) {
marginStyles.forEach( ( marginStyle ) => {
const declarations = [];

Object.entries( marginStyle.rules ).forEach(
( [ cssProperty, cssValue ] ) => {
if ( cssValue ) {
declarations.push(
`${ cssProperty }: ${ cssValue }`
);
} else if ( marginRules[ cssProperty ] ) {
declarations.push(
`${ cssProperty }: ${ marginRules[ cssProperty ] }`
);
}
}
);

ruleset += `.${ className }${
marginStyle?.selector
}${ selector } { ${ declarations.join( '; ' ) } }`;
} );
}
}
);
// Add layout aware margin rule for children of the root site blocks class.
ruleset += `.wp-site-blocks > * + ${ selector } { ${ marginString } }`;
}
}

if ( gapValue && tree?.settings?.layout?.definitions ) {
Object.values( tree.settings.layout.definitions ).forEach(
( { className, name, spacingStyles } ) => {
Expand Down Expand Up @@ -529,6 +584,8 @@ export const getNodesWithStyles = ( tree, blockSelectors ) => {
blockSelectors[ blockName ].fallbackGapValue,
hasLayoutSupport:
blockSelectors[ blockName ].hasLayoutSupport,
hasMarginSupport:
blockSelectors[ blockName ].hasMarginSupport,
selector: blockSelectors[ blockName ].selector,
styles: blockStyles,
featureSelectors:
Expand Down Expand Up @@ -682,6 +739,7 @@ export const toStyles = (
styles,
fallbackGapValue,
hasLayoutSupport,
hasMarginSupport,
featureSelectors,
styleVariationSelectors,
} ) => {
Expand Down Expand Up @@ -795,7 +853,9 @@ export const toStyles = (
// Process blockGap and layout styles.
if (
! disableLayoutStyles &&
( ROOT_BLOCK_SELECTOR === selector || hasLayoutSupport )
( ROOT_BLOCK_SELECTOR === selector ||
hasLayoutSupport ||
hasMarginSupport )
) {
ruleset += getLayoutStyles( {
tree,
Expand Down Expand Up @@ -912,6 +972,7 @@ export const getBlockSelectors = ( blockTypes, getBlockStyles ) => {
const duotoneSelector =
blockType?.supports?.color?.__experimentalDuotone ?? null;
const hasLayoutSupport = !! blockType?.supports?.__experimentalLayout;
const hasMarginSupport = !! blockType?.supports?.spacing?.margin;
const fallbackGapValue =
blockType?.supports?.spacing?.blockGap?.__experimentalDefault;

Expand Down Expand Up @@ -947,6 +1008,7 @@ export const getBlockSelectors = ( blockTypes, getBlockStyles ) => {
? featureSelectors
: undefined,
hasLayoutSupport,
hasMarginSupport,
name,
selector,
styleVariationSelectors: Object.keys( styleVariationSelectors )
Expand Down
35 changes: 34 additions & 1 deletion phpunit/class-wp-theme-json-test.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,16 @@ public function test_get_stylesheet_generates_layout_styles( $layout_definitions
),
),
'styles' => array(
'blocks' => array(
'core/group' => array(
'spacing' => array(
'margin' => array(
'top' => '25px',
'bottom' => '50px',
),
),
),
),
'spacing' => array(
'blockGap' => '1em',
),
Expand All @@ -65,7 +75,7 @@ public function test_get_stylesheet_generates_layout_styles( $layout_definitions

// Results also include root site blocks styles.
$this->assertEquals(
'body { margin: 0;}.wp-site-blocks > .alignleft { float: left; margin-right: 2em; }.wp-site-blocks > .alignright { float: right; margin-left: 2em; }.wp-site-blocks > .aligncenter { justify-content: center; margin-left: auto; margin-right: auto; }.wp-site-blocks > * { margin-block-start: 0; margin-block-end: 0; }.wp-site-blocks > * + * { margin-block-start: 1em; }body { --wp--style--block-gap: 1em; }body .is-layout-flow > *{margin-block-start: 0;margin-block-end: 0;}body .is-layout-flow > * + *{margin-block-start: 1em;margin-block-end: 0;}body .is-layout-flex{gap: 1em;}body .is-layout-flow > .alignleft{float: left;margin-inline-start: 0;margin-inline-end: 2em;}body .is-layout-flow > .alignright{float: right;margin-inline-start: 2em;margin-inline-end: 0;}body .is-layout-flow > .aligncenter{margin-left: auto !important;margin-right: auto !important;}body .is-layout-flex{display: flex;}body .is-layout-flex{flex-wrap: wrap;align-items: center;}',
'body { margin: 0;}.wp-site-blocks > .alignleft { float: left; margin-right: 2em; }.wp-site-blocks > .alignright { float: right; margin-left: 2em; }.wp-site-blocks > .aligncenter { justify-content: center; margin-left: auto; margin-right: auto; }.wp-site-blocks > * { margin-block-start: 0; margin-block-end: 0; }.wp-site-blocks > * + * { margin-block-start: 1em; }body { --wp--style--block-gap: 1em; }body .is-layout-flow > *{margin-block-start: 0;margin-block-end: 0;}body .is-layout-flow > * + *{margin-block-start: 1em;margin-block-end: 0;}body .is-layout-flex{gap: 1em;}body .is-layout-flow > .alignleft{float: left;margin-inline-start: 0;margin-inline-end: 2em;}body .is-layout-flow > .alignright{float: right;margin-inline-start: 2em;margin-inline-end: 0;}body .is-layout-flow > .aligncenter{margin-left: auto !important;margin-right: auto !important;}body .is-layout-flex{display: flex;}body .is-layout-flex{flex-wrap: wrap;align-items: center;}.wp-block-group{margin-top: 25px;margin-bottom: 50px;}.is-layout-flow > .wp-block-group{margin-block-start: 0;margin-bottom: 50px;}.is-layout-flow > * + .wp-block-group{margin-top: 25px;margin-bottom: 50px;}.is-layout-flow > *:last-child.wp-block-group{margin-top: 25px;margin-block-end: 0;}.wp-site-blocks > * + .wp-block-group {margin-top:25px;margin-bottom:50px;}',
$theme_json->get_stylesheet( array( 'styles' ) )
);
}
Expand Down Expand Up @@ -305,6 +315,29 @@ public function data_get_layout_definitions() {
),
),
),
'marginStyles' => array(
array(
'selector' => ' > ',
'rules' => array(
'margin-block-start' => '0',
'margin-bottom' => null,
),
),
array(
'selector' => ' > * + ',
'rules' => array(
'margin-top' => null,
'margin-bottom' => null,
),
),
array(
'selector' => ' > *:last-child',
'rules' => array(
'margin-top' => null,
'margin-block-end' => '0',
),
),
),
),
'flex' => array(
'name' => 'flex',
Expand Down