Skip to content

Commit

Permalink
Add block spacing and layout to Post Template (WordPress#49050)
Browse files Browse the repository at this point in the history
* Add static column number option

* Address feedback and fix Group placeholder

* Revert non-responsive option

* Try using grid layout in Post Template

* Update Post Template to use auto-fill columns

* Add block spacing to post template

* Show gap control by default

* Add unstable columns grid property

* Rename layout column attribute.

* Add a media query to reproduce current responsiveness

* Move layout controls to Post Template block

* Reduce max columns to 6.

* Remove unstable prefix

* fix cols breaking out of container

* Try adding deprecation

* Fix broken loop

* Update fixtures

* Code improvements

* Add some comments to the CSS.

* Add back deleted line

* Remove legacy attributes in deprecation

* Fix deprecation logic

* Update fixtures

* Fallback gap for classic themes

* fix spacing

* match old default value

* Update PHP test strings.

* Fix tag discrepancy in fixtures
  • Loading branch information
tellthemachines authored and sethrubenstein committed Jul 13, 2023
1 parent 9834632 commit ae75e2f
Show file tree
Hide file tree
Showing 31 changed files with 468 additions and 147 deletions.
4 changes: 2 additions & 2 deletions docs/reference-guides/core-blocks.md
Original file line number Diff line number Diff line change
Expand Up @@ -600,7 +600,7 @@ Contains the block elements used to render a post, like the title, date, feature
- **Name:** core/post-template
- **Category:** theme
- **Parent:** core/query
- **Supports:** align (full, wide), anchor, color (background, gradients, link, text), typography (fontSize, lineHeight), ~~html~~, ~~reusable~~
- **Supports:** align (full, wide), anchor, color (background, gradients, link, text), spacing (blockGap), typography (fontSize, lineHeight), ~~html~~, ~~reusable~~
- **Attributes:**

## Post Terms
Expand Down Expand Up @@ -656,7 +656,7 @@ An advanced block that allows displaying post types based on different query par
- **Name:** core/query
- **Category:** theme
- **Supports:** align (full, wide), anchor, ~~html~~
- **Attributes:** displayLayout, namespace, query, queryId, tagName
- **Attributes:** namespace, query, queryId, tagName

## No results

Expand Down
17 changes: 12 additions & 5 deletions lib/block-supports/layout.php
Original file line number Diff line number Diff line change
Expand Up @@ -280,12 +280,19 @@ function gutenberg_get_layout_style( $selector, $layout, $has_block_gap_support
}
}
} elseif ( 'grid' === $layout_type ) {
$minimum_column_width = ! empty( $layout['minimumColumnWidth'] ) ? $layout['minimumColumnWidth'] : '12rem';
if ( ! empty( $layout['columnCount'] ) ) {
$layout_styles[] = array(
'selector' => $selector,
'declarations' => array( 'grid-template-columns' => 'repeat(' . $layout['columnCount'] . ', minmax(0, 1fr))' ),
);
} else {
$minimum_column_width = ! empty( $layout['minimumColumnWidth'] ) ? $layout['minimumColumnWidth'] : '12rem';

$layout_styles[] = array(
'selector' => $selector,
'declarations' => array( 'grid-template-columns' => 'repeat(auto-fill, minmax(min(' . $minimum_column_width . ', 100%), 1fr))' ),
);
$layout_styles[] = array(
'selector' => $selector,
'declarations' => array( 'grid-template-columns' => 'repeat(auto-fill, minmax(min(' . $minimum_column_width . ', 100%), 1fr))' ),
);
}

if ( $has_block_gap_support && isset( $gap_value ) ) {
$combined_gap_value = '';
Expand Down
17 changes: 12 additions & 5 deletions lib/class-wp-theme-json-gutenberg.php
Original file line number Diff line number Diff line change
Expand Up @@ -1073,11 +1073,13 @@ public function get_stylesheet( $types = array( 'variables', 'styles', 'presets'
}
$stylesheet .= $this->get_block_classes( $style_nodes );
} elseif ( in_array( 'base-layout-styles', $types, true ) ) {
$root_selector = static::ROOT_BLOCK_SELECTOR;
$columns_selector = '.wp-block-columns';
$root_selector = static::ROOT_BLOCK_SELECTOR;
$columns_selector = '.wp-block-columns';
$post_template_selector = '.wp-block-post-template';
if ( ! empty( $options['scope'] ) ) {
$root_selector = static::scope_selector( $options['scope'], $root_selector );
$columns_selector = static::scope_selector( $options['scope'], $columns_selector );
$root_selector = static::scope_selector( $options['scope'], $root_selector );
$columns_selector = static::scope_selector( $options['scope'], $columns_selector );
$post_template_selector = static::scope_selector( $options['scope'], $post_template_selector );
}
if ( ! empty( $options['root_selector'] ) ) {
$root_selector = $options['root_selector'];
Expand All @@ -1094,6 +1096,11 @@ public function get_stylesheet( $types = array( 'variables', 'styles', 'presets'
'selector' => $columns_selector,
'name' => 'core/columns',
),
array(
'path' => array( 'styles', 'blocks', 'core/post-template' ),
'selector' => $post_template_selector,
'name' => 'core/post-template',
),
);

foreach ( $base_styles_nodes as $base_style_node ) {
Expand Down Expand Up @@ -1298,7 +1305,7 @@ protected function get_layout_styles( $block_metadata ) {
if ( null !== $block_gap_value && false !== $block_gap_value && '' !== $block_gap_value ) {
foreach ( $layout_definitions as $layout_definition_key => $layout_definition ) {
// Allow outputting fallback gap styles for flex layout type when block gap support isn't available.
if ( ! $has_block_gap_support && 'flex' !== $layout_definition_key ) {
if ( ! $has_block_gap_support && 'flex' !== $layout_definition_key && 'grid' !== $layout_definition_key ) {
continue;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -460,7 +460,11 @@ export function getLayoutStyles( {
Object.values( tree.settings.layout.definitions ).forEach(
( { className, name, spacingStyles } ) => {
// Allow outputting fallback gap styles for flex layout type when block gap support isn't available.
if ( ! hasBlockGapSupport && 'flex' !== name ) {
if (
! hasBlockGapSupport &&
'flex' !== name &&
'grid' !== name
) {
return;
}

Expand Down
32 changes: 29 additions & 3 deletions packages/block-editor/src/layouts/grid.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@ export default {
layout = {},
onChange,
} ) {
return (
return layout?.columnCount ? (
<GridLayoutColumnsControl layout={ layout } onChange={ onChange } />
) : (
<GridLayoutMinimumWidthControl
layout={ layout }
onChange={ onChange }
Expand All @@ -53,7 +55,7 @@ export default {
hasBlockGapSupport,
layoutDefinitions,
} ) {
const { minimumColumnWidth = '12rem' } = layout;
const { minimumColumnWidth = '12rem', columnCount = null } = layout;

// If a block's block.json skips serialization for spacing or spacing.blockGap,
// don't apply the user-defined value to the styles.
Expand All @@ -66,7 +68,11 @@ export default {
let output = '';
const rules = [];

if ( minimumColumnWidth ) {
if ( columnCount ) {
rules.push(
`grid-template-columns: repeat(${ columnCount }, minmax(0, 1fr))`
);
} else if ( minimumColumnWidth ) {
rules.push(
`grid-template-columns: repeat(auto-fill, minmax(min(${ minimumColumnWidth }, 100%), 1fr))`
);
Expand Down Expand Up @@ -170,3 +176,23 @@ function GridLayoutMinimumWidthControl( { layout, onChange } ) {
</fieldset>
);
}

// Enables setting number of grid columns
function GridLayoutColumnsControl( { layout, onChange } ) {
const { columnCount = 3 } = layout;

return (
<RangeControl
label={ __( 'Columns' ) }
value={ columnCount }
onChange={ ( value ) =>
onChange( {
...layout,
columnCount: value,
} )
}
min={ 1 }
max={ 6 }
/>
);
}
12 changes: 9 additions & 3 deletions packages/block-library/src/post-template/block.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,7 @@
"html": false,
"align": [ "wide", "full" ],
"anchor": true,
"__experimentalLayout": {
"allowEditing": false
},
"__experimentalLayout": true,
"color": {
"gradients": true,
"link": true,
Expand All @@ -43,6 +41,14 @@
"__experimentalDefaultControls": {
"fontSize": true
}
},
"spacing": {
"blockGap": {
"__experimentalDefault": "1.25em"
},
"__experimentalDefaultControls": {
"blockGap": true
}
}
},
"style": "wp-block-post-template",
Expand Down
98 changes: 66 additions & 32 deletions packages/block-library/src/post-template/edit.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,16 @@ import { memo, useMemo, useState } from '@wordpress/element';
import { useSelect } from '@wordpress/data';
import { __ } from '@wordpress/i18n';
import {
BlockControls,
BlockContextProvider,
__experimentalUseBlockPreview as useBlockPreview,
useBlockProps,
useInnerBlocksProps,
store as blockEditorStore,
} from '@wordpress/block-editor';
import { Spinner } from '@wordpress/components';
import { Spinner, ToolbarGroup } from '@wordpress/components';
import { store as coreStore } from '@wordpress/core-data';
import { list, grid } from '@wordpress/icons';

const TEMPLATE = [
[ 'core/post-title' ],
Expand Down Expand Up @@ -70,6 +72,7 @@ function PostTemplateBlockPreview( {
const MemoizedPostTemplateBlockPreview = memo( PostTemplateBlockPreview );

export default function PostTemplateEdit( {
setAttributes,
clientId,
context: {
query: {
Expand All @@ -95,11 +98,13 @@ export default function PostTemplateEdit( {
} = {},
queryContext = [ { page: 1 } ],
templateSlug,
displayLayout: { type: layoutType = 'flex', columns = 1 } = {},
previewPostType,
},
attributes: { layout },
__unstableLayoutClassNames,
} ) {
const { type: layoutType, columnCount = 3 } = layout || {};

const [ { page } ] = queryContext;
const [ activeBlockContextId, setActiveBlockContextId ] = useState();
const { posts, blocks } = useSelect(
Expand Down Expand Up @@ -215,12 +220,9 @@ export default function PostTemplateEdit( {
} ) ),
[ posts ]
);
const hasLayoutFlex = layoutType === 'flex' && columns > 1;

const blockProps = useBlockProps( {
className: classnames( __unstableLayoutClassNames, {
'is-flex-container': hasLayoutFlex,
[ `columns-${ columns }` ]: hasLayoutFlex,
} ),
className: classnames( __unstableLayoutClassNames ),
} );

if ( ! posts ) {
Expand All @@ -235,35 +237,67 @@ export default function PostTemplateEdit( {
return <p { ...blockProps }> { __( 'No results found.' ) }</p>;
}

const setDisplayLayout = ( newDisplayLayout ) =>
setAttributes( {
layout: { ...layout, ...newDisplayLayout },
} );

const displayLayoutControls = [
{
icon: list,
title: __( 'List view' ),
onClick: () => setDisplayLayout( { type: 'default' } ),
isActive: layoutType === 'default' || layoutType === 'constrained',
},
{
icon: grid,
title: __( 'Grid view' ),
onClick: () =>
setDisplayLayout( {
type: 'grid',
columnCount,
} ),
isActive: layoutType === 'grid',
},
];

// To avoid flicker when switching active block contexts, a preview is rendered
// for each block context, but the preview for the active block context is hidden.
// This ensures that when it is displayed again, the cached rendering of the
// block preview is used, instead of having to re-render the preview from scratch.
return (
<ul { ...blockProps }>
{ blockContexts &&
blockContexts.map( ( blockContext ) => (
<BlockContextProvider
key={ blockContext.postId }
value={ blockContext }
>
{ blockContext.postId ===
( activeBlockContextId ||
blockContexts[ 0 ]?.postId ) ? (
<PostTemplateInnerBlocks />
) : null }
<MemoizedPostTemplateBlockPreview
blocks={ blocks }
blockContextId={ blockContext.postId }
setActiveBlockContextId={ setActiveBlockContextId }
isHidden={
blockContext.postId ===
( activeBlockContextId ||
blockContexts[ 0 ]?.postId )
}
/>
</BlockContextProvider>
) ) }
</ul>
<>
<BlockControls>
<ToolbarGroup controls={ displayLayoutControls } />
</BlockControls>

<ul { ...blockProps }>
{ blockContexts &&
blockContexts.map( ( blockContext ) => (
<BlockContextProvider
key={ blockContext.postId }
value={ blockContext }
>
{ blockContext.postId ===
( activeBlockContextId ||
blockContexts[ 0 ]?.postId ) ? (
<PostTemplateInnerBlocks />
) : null }
<MemoizedPostTemplateBlockPreview
blocks={ blocks }
blockContextId={ blockContext.postId }
setActiveBlockContextId={
setActiveBlockContextId
}
isHidden={
blockContext.postId ===
( activeBlockContextId ||
blockContexts[ 0 ]?.postId )
}
/>
</BlockContextProvider>
) ) }
</ul>
</>
);
}
9 changes: 8 additions & 1 deletion packages/block-library/src/post-template/style.scss
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
&.wp-block-post-template {
background: none;
}

// These rules no longer apply but should be kept for backwards compatibility.
&.is-flex-container {
flex-direction: row;
display: flex;
Expand All @@ -30,3 +30,10 @@
}
}
}

@media ( max-width: $break-small ) {
// Temporary specificity bump until "wp-container" layout specificity is revisited.
.wp-block-post-template-is-layout-grid.wp-block-post-template-is-layout-grid.wp-block-post-template-is-layout-grid.wp-block-post-template-is-layout-grid {
grid-template-columns: 1fr;
}
}
6 changes: 0 additions & 6 deletions packages/block-library/src/query/block.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,6 @@
"type": "string",
"default": "div"
},
"displayLayout": {
"type": "object",
"default": {
"type": "list"
}
},
"namespace": {
"type": "string"
}
Expand Down
Loading

0 comments on commit ae75e2f

Please sign in to comment.