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

Replace ImageSizeControl component with DimensionsTool component #53831

Open
wants to merge 13 commits into
base: trunk
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/reference-guides/core-blocks.md
Expand Up @@ -397,7 +397,7 @@ Display a list of your most recent posts. ([Source](https://github.com/WordPress
- **Name:** core/latest-posts
- **Category:** widgets
- **Supports:** align, color (background, gradients, link, text), spacing (margin, padding), typography (fontSize, lineHeight), ~~html~~
- **Attributes:** addLinkToFeaturedImage, categories, columns, displayAuthor, displayFeaturedImage, displayPostContent, displayPostContentRadio, displayPostDate, excerptLength, featuredImageAlign, featuredImageSizeHeight, featuredImageSizeSlug, featuredImageSizeWidth, order, orderBy, postLayout, postsToShow, selectedAuthor
- **Attributes:** addLinkToFeaturedImage, categories, columns, displayAuthor, displayFeaturedImage, displayPostContent, displayPostContentRadio, displayPostDate, excerptLength, featuredImageAlign, featuredImageAspectRation, featuredImageScale, featuredImageSizeHeight, featuredImageSizeSlug, featuredImageSizeWidth, order, orderBy, postLayout, postsToShow, selectedAuthor

## List

Expand Down Expand Up @@ -434,7 +434,7 @@ Set media and words side-by-side for a richer layout. ([Source](https://github.c
- **Name:** core/media-text
- **Category:** media
- **Supports:** align (full, wide), anchor, color (background, gradients, heading, link, text), spacing (margin, padding), typography (fontSize, lineHeight), ~~html~~
- **Attributes:** align, allowedBlocks, focalPoint, href, imageFill, isStackedOnMobile, linkClass, linkDestination, linkTarget, mediaAlt, mediaId, mediaLink, mediaPosition, mediaSizeSlug, mediaType, mediaUrl, mediaWidth, rel, verticalAlignment
- **Attributes:** align, allowedBlocks, focalPoint, href, imageAspectRatio, imageFill, imageHeight, imageScale, imageWidth, isStackedOnMobile, linkClass, linkDestination, linkTarget, mediaAlt, mediaId, mediaLink, mediaPosition, mediaSizeSlug, mediaType, mediaUrl, mediaWidth, rel, verticalAlignment

## Unsupported

Expand Down
12 changes: 8 additions & 4 deletions packages/block-library/src/latest-posts/block.json
Expand Up @@ -70,12 +70,16 @@
"default": "thumbnail"
},
"featuredImageSizeWidth": {
"type": "number",
"default": null
"type": "string"
},
"featuredImageSizeHeight": {
"type": "number",
"default": null
"type": "string"
},
"featuredImageScale": {
"type": "string"
},
"featuredImageAspectRation": {
Copy link
Contributor

Choose a reason for hiding this comment

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

Is this a typo? Did you mean featuredImageAspectRatio?

"type": "string"
},
"addLinkToFeaturedImage": {
"type": "boolean",
Expand Down
211 changes: 138 additions & 73 deletions packages/block-library/src/latest-posts/edit.js
Expand Up @@ -16,16 +16,19 @@ import {
Spinner,
ToggleControl,
ToolbarGroup,
__experimentalToolsPanel as ToolsPanel,
__experimentalToolsPanelItem as ToolsPanelItem,
__experimentalUseCustomUnits as useCustomUnits,
} from '@wordpress/components';
import { __, sprintf } from '@wordpress/i18n';
import { __, _x, sprintf } from '@wordpress/i18n';
import { dateI18n, format, getSettings } from '@wordpress/date';
import {
InspectorControls,
BlockAlignmentToolbar,
BlockControls,
__experimentalImageSizeControl as ImageSizeControl,
useBlockProps,
store as blockEditorStore,
privateApis as blockEditorPrivateApis,
} from '@wordpress/block-editor';
import { useSelect, useDispatch } from '@wordpress/data';
import { pin, list, grid } from '@wordpress/icons';
Expand All @@ -43,6 +46,8 @@ import {
MAX_POSTS_COLUMNS,
} from './constants';

import { unlock } from '../lock-unlock';

/**
* Module Constants
*/
Expand All @@ -56,6 +61,21 @@ const USERS_LIST_QUERY = {
context: 'view',
};

const { DimensionsTool, ResolutionTool } = unlock( blockEditorPrivateApis );

const scaleOptions = [
{
value: 'cover',
label: _x( 'Cover', 'Scale option for dimensions control' ),
help: __( 'Image covers the space evenly.' ),
},
{
value: 'contain',
label: _x( 'Contain', 'Scale option for dimensions control' ),
help: __( 'Image is contained without distortion.' ),
},
];

function getFeaturedImageDetails( post, size ) {
const image = post._embedded?.[ 'wp:featuredmedia' ]?.[ '0' ];

Expand Down Expand Up @@ -87,16 +107,11 @@ export default function LatestPostsEdit( { attributes, setAttributes } ) {
featuredImageSizeSlug,
featuredImageSizeWidth,
featuredImageSizeHeight,
featuredImageScale,
featuredImageAspectRation,
addLinkToFeaturedImage,
} = attributes;
const {
imageSizes,
latestPosts,
defaultImageWidth,
defaultImageHeight,
categoriesList,
authorList,
} = useSelect(
const { imageSizes, latestPosts, categoriesList, authorList } = useSelect(
( select ) => {
const { getEntityRecords, getUsers } = select( coreStore );
const settings = select( blockEditorStore ).getSettings();
Expand All @@ -116,12 +131,6 @@ export default function LatestPostsEdit( { attributes, setAttributes } ) {
);

return {
defaultImageWidth:
settings.imageDimensions?.[ featuredImageSizeSlug ]
?.width ?? 0,
defaultImageHeight:
settings.imageDimensions?.[ featuredImageSizeSlug ]
?.height ?? 0,
imageSizes: settings.imageSizes,
latestPosts: getEntityRecords(
'postType',
Expand Down Expand Up @@ -197,6 +206,19 @@ export default function LatestPostsEdit( { attributes, setAttributes } ) {
setAttributes( { categories: allCategories } );
};

const updateImage = ( newSizeSlug ) => {
setAttributes( {
featuredImageSizeSlug: newSizeSlug,
} );
};

// TODO: Can allow more units after figuring out how they should interact
// with the ResizableBox and ImageEditor components. Calculations later on
// for those components are currently assuming px units.
const dimensionsUnitsOptions = useCustomUnits( {
availableUnits: [ 'px' ],
} );

const hasPosts = !! latestPosts?.length;
const inspectorControls = (
<InspectorControls>
Expand Down Expand Up @@ -261,75 +283,116 @@ export default function LatestPostsEdit( { attributes, setAttributes } ) {
/>
</PanelBody>

<PanelBody title={ __( 'Featured image' ) }>
<ToggleControl
__nextHasNoMarginBottom
label={ __( 'Display featured image' ) }
checked={ displayFeaturedImage }
onChange={ ( value ) =>
setAttributes( { displayFeaturedImage: value } )
<ToolsPanel label={ __( 'Featured image' ) }>
<ToolsPanelItem
label={ __( 'Featured image' ) }
isShownByDefault={ true }
hasValue={ () => displayFeaturedImage === true }
onDeselect={ () =>
setAttributes( { displayFeaturedImage: false } )
}
/>
>
<ToggleControl
__nextHasNoMarginBottom
label={ __( 'Display featured image' ) }
checked={ displayFeaturedImage }
onChange={ ( value ) =>
setAttributes( { displayFeaturedImage: value } )
}
/>
</ToolsPanelItem>
{ displayFeaturedImage && (
<>
<ImageSizeControl
onChange={ ( value ) => {
const newAttrs = {};
if ( value.hasOwnProperty( 'width' ) ) {
newAttrs.featuredImageSizeWidth =
value.width;
}
if ( value.hasOwnProperty( 'height' ) ) {
newAttrs.featuredImageSizeHeight =
value.height;
}
setAttributes( newAttrs );
<DimensionsTool
value={ {
width: featuredImageSizeWidth,
height: featuredImageSizeHeight,
scale: featuredImageScale,
aspectRatio: featuredImageAspectRation,
} }
slug={ featuredImageSizeSlug }
width={ featuredImageSizeWidth }
height={ featuredImageSizeHeight }
imageWidth={ defaultImageWidth }
imageHeight={ defaultImageHeight }
imageSizeOptions={ imageSizeOptions }
imageSizeHelp={ __(
'Select the size of the source image.'
) }
onChangeImage={ ( value ) =>
onChange={ ( {
width: newWidth,
height: newHeight,
scale: newScale,
aspectRatio: newAspectRatio,
} ) => {
// Rebuilding the object forces setting `undefined`
// for values that are removed since setAttributes
// doesn't do anything with keys that aren't set.
setAttributes( {
// CSS includes `height: auto`, but we need
// `width: auto` to fix the aspect ratio when
// only height is set due to the width and
// height attributes set via the server.
featuredImageSizeWidth:
! newWidth && newHeight
? 'auto'
: newWidth,
featuredImageSizeHeight: newHeight,
featuredImageScale: newScale,
featuredImageAspectRation: newAspectRatio,
} );
} }
defaultScale="cover"
defaultAspectRatio="auto"
scaleOptions={ scaleOptions }
unitsOptions={ dimensionsUnitsOptions }
/>
<ResolutionTool
value={ featuredImageSizeSlug }
onChange={ updateImage }
options={ imageSizeOptions }
/>
<ToolsPanelItem
label={ __( 'Image alignment' ) }
isShownByDefault={ displayFeaturedImage }
hasValue={ () => featuredImageAlign !== undefined }
onDeselect={ () =>
setAttributes( {
featuredImageSizeSlug: value,
featuredImageSizeWidth: undefined,
featuredImageSizeHeight: undefined,
featuredImageAlign: undefined,
} )
}
/>
<BaseControl className="editor-latest-posts-image-alignment-control">
<BaseControl.VisualLabel>
{ __( 'Image alignment' ) }
</BaseControl.VisualLabel>
<BlockAlignmentToolbar
value={ featuredImageAlign }
>
<BaseControl className="editor-latest-posts-image-alignment-control">
<BaseControl.VisualLabel>
{ __( 'Image alignment' ) }
</BaseControl.VisualLabel>
<BlockAlignmentToolbar
value={ featuredImageAlign }
onChange={ ( value ) =>
setAttributes( {
featuredImageAlign: value,
} )
}
controls={ [ 'left', 'center', 'right' ] }
isCollapsed={ false }
/>
</BaseControl>
</ToolsPanelItem>
<ToolsPanelItem
label={ __( 'Add link to featured image' ) }
isShownByDefault={ displayFeaturedImage }
hasValue={ () => addLinkToFeaturedImage === true }
onDeselect={ () =>
setAttributes( {
addLinkToFeaturedImage: false,
} )
}
>
<ToggleControl
__nextHasNoMarginBottom
label={ __( 'Add link to featured image' ) }
checked={ addLinkToFeaturedImage }
onChange={ ( value ) =>
setAttributes( {
featuredImageAlign: value,
addLinkToFeaturedImage: value,
} )
}
controls={ [ 'left', 'center', 'right' ] }
isCollapsed={ false }
/>
</BaseControl>
<ToggleControl
__nextHasNoMarginBottom
label={ __( 'Add link to featured image' ) }
checked={ addLinkToFeaturedImage }
onChange={ ( value ) =>
setAttributes( {
addLinkToFeaturedImage: value,
} )
}
/>
</ToolsPanelItem>
</>
) }
</PanelBody>
</ToolsPanel>

<PanelBody title={ __( 'Sorting and filtering' ) }>
<QueryControls
Expand Down Expand Up @@ -465,9 +528,11 @@ export default function LatestPostsEdit( { attributes, setAttributes } ) {
<img
src={ imageSourceUrl }
alt={ featuredImageAlt }
width={ featuredImageSizeWidth }
height={ featuredImageSizeHeight }
style={ {
maxWidth: featuredImageSizeWidth,
maxHeight: featuredImageSizeHeight,
objectFit: featuredImageScale,
aspectRatio: featuredImageAspectRation,
} }
/>
);
Expand Down
29 changes: 20 additions & 9 deletions packages/block-library/src/latest-posts/index.php
Expand Up @@ -75,25 +75,36 @@
$list_items_markup .= '<li>';

if ( $attributes['displayFeaturedImage'] && has_post_thumbnail( $post ) ) {
$image_style = '';
$image_styles = [];

Check failure on line 78 in packages/block-library/src/latest-posts/index.php

View workflow job for this annotation

GitHub Actions / PHP coding standards

Short array syntax is not allowed
$image_attrs = [];

Check warning on line 79 in packages/block-library/src/latest-posts/index.php

View workflow job for this annotation

GitHub Actions / PHP coding standards

Equals sign not aligned with surrounding assignments; expected 2 spaces but found 1 space

Check failure on line 79 in packages/block-library/src/latest-posts/index.php

View workflow job for this annotation

GitHub Actions / PHP coding standards

Short array syntax is not allowed
if ( isset( $attributes['featuredImageSizeWidth'] ) ) {
$image_style .= sprintf( 'max-width:%spx;', $attributes['featuredImageSizeWidth'] );
$image_attrs[] = 'width="' . esc_attr( $attributes['featuredImageSizeWidth'] ) . '"';
}
if ( isset( $attributes['featuredImageSizeHeight'] ) ) {
$image_style .= sprintf( 'max-height:%spx;', $attributes['featuredImageSizeHeight'] );
$image_attrs[] = 'height="' . esc_attr( $attributes['featuredImageSizeHeight'] ) . '"';
}
if ( isset( $attributes['featuredImageScale'] ) ) {
$image_styles[] = 'object-fit: ' . esc_attr( $attributes['featuredImageScale'] ) . ';';
}
if ( isset( $attributes['featuredImageAspectRation'] ) ) {
$image_styles[] = 'aspect-ratio: ' . esc_attr( $attributes['featuredImageAspectRation'] ) . ';';
}
$featured_image_classes = 'attachment-' . $attributes['featuredImageSizeSlug'] . ' size-' . $attributes['featuredImageSizeSlug'] . ' wp-post-image';

$image_classes = 'wp-block-latest-posts__featured-image';
if ( isset( $attributes['featuredImageAlign'] ) ) {
$image_classes .= ' align' . $attributes['featuredImageAlign'];
}

$featured_image = get_the_post_thumbnail(
$post,
$attributes['featuredImageSizeSlug'],
array(
'style' => esc_attr( $image_style ),
)
$featured_image_url = get_the_post_thumbnail_url( $post, $attributes['featuredImageSizeSlug'] );

$featured_image = sprintf(
'<img class="%1$s" src="%2$s" alt="%3$s" %4$s style="%5$s" decoding="async">',
esc_attr( $featured_image_classes ),
esc_attr( $featured_image_url ),
esc_attr( $title ),
implode( ' ', $image_attrs ),
implode( '', $image_styles)

Check failure on line 107 in packages/block-library/src/latest-posts/index.php

View workflow job for this annotation

GitHub Actions / PHP coding standards

Expected 1 spaces before closing parenthesis; 0 found
);
if ( $attributes['addLinkToFeaturedImage'] ) {
$featured_image = sprintf(
Expand Down
10 changes: 8 additions & 2 deletions packages/block-library/src/latest-posts/style.scss
Expand Up @@ -59,9 +59,15 @@
display: inline-block;
}
img {
height: auto;
width: auto;
max-width: 100%;

&:not([width]) {
width: auto;
}

&:not([height]) {
height: auto;
}
}
&.alignleft {
/*rtl:ignore*/
Expand Down