Skip to content

Commit

Permalink
Add featured image to Media & Text block (#51491)
Browse files Browse the repository at this point in the history
* Add featured image to Media & Text block

* Try adding the featured image option to the toolbar (replace flow)

* fix JS warning in templates where there is no featured image.

* Add deprecation, update fixtures

* Try adding index.php

* Index.php: use the $content and only replace the image source and the image background position.

* Update index.php

* Update index.php

* Add alt and class names to the image tag

* Fix white space issue

* Add a placeholder for the featured image

* Remove the deprecation

* Add condition with useFeaturedImage, remove alt text option from placeholder

* Set a minimum height for the placeholder image

* Remove set_attribute 'alt' from index.php.

* Update editor.scss

* Update packages/block-library/src/media-text/index.php

Co-authored-by: Aki Hamano <54422211+t-hamano@users.noreply.github.com>

* Update packages/block-library/src/media-text/media-container.js

Co-authored-by: Aki Hamano <54422211+t-hamano@users.noreply.github.com>

* Try removing the image mediaType and inserting the img tag in index.php.

* CS fix

Adjust spacing.

* Add condition to save.js.

* CS: Remove the truthy default value for withIllustration in media-text/media-container.js

* Update the condition that outputs the img tag

Only output the img tag if there is a mediaURL.
The mediaURL is required because img tags without a src attribute is invalid HTML.

---------

Co-authored-by: Aki Hamano <54422211+t-hamano@users.noreply.github.com>
  • Loading branch information
carolinan and t-hamano committed Mar 8, 2024
1 parent 47c22e7 commit a9a57c4
Show file tree
Hide file tree
Showing 10 changed files with 215 additions and 35 deletions.
2 changes: 1 addition & 1 deletion docs/reference-guides/core-blocks.md
Original file line number Diff line number Diff line change
Expand Up @@ -445,7 +445,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), interactivity (clientNavigation), 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, imageFill, isStackedOnMobile, linkClass, linkDestination, linkTarget, mediaAlt, mediaId, mediaLink, mediaPosition, mediaSizeSlug, mediaType, mediaUrl, mediaWidth, rel, useFeaturedImage, verticalAlignment

## Unsupported

Expand Down
2 changes: 1 addition & 1 deletion lib/blocks.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ function gutenberg_reregister_core_block_types() {
'html',
'list',
'list-item',
'media-text',
'missing',
'more',
'nextpage',
Expand Down Expand Up @@ -78,6 +77,7 @@ function gutenberg_reregister_core_block_types() {
'latest-comments.php' => 'core/latest-comments',
'latest-posts.php' => 'core/latest-posts',
'loginout.php' => 'core/loginout',
'media-text.php' => 'core/media-text',
'navigation.php' => 'core/navigation',
'navigation-link.php' => 'core/navigation-link',
'navigation-submenu.php' => 'core/navigation-submenu',
Expand Down
5 changes: 5 additions & 0 deletions packages/block-library/src/media-text/block.json
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,13 @@
},
"allowedBlocks": {
"type": "array"
},
"useFeaturedImage": {
"type": "boolean",
"default": false
}
},
"usesContext": [ "postId", "postType" ],
"supports": {
"anchor": true,
"align": [ "wide", "full" ],
Expand Down
99 changes: 80 additions & 19 deletions packages/block-library/src/media-text/edit.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import {
} from '@wordpress/components';
import { isBlobURL, getBlobTypeByURL } from '@wordpress/blob';
import { pullLeft, pullRight } from '@wordpress/icons';
import { store as coreStore } from '@wordpress/core-data';
import { useEntityProp, store as coreStore } from '@wordpress/core-data';

/**
* Internal dependencies
Expand Down Expand Up @@ -127,7 +127,12 @@ function attributesFromMedia( {
};
}

function MediaTextEdit( { attributes, isSelected, setAttributes } ) {
function MediaTextEdit( {
attributes,
isSelected,
setAttributes,
context: { postId, postType },
} ) {
const {
focalPoint,
href,
Expand All @@ -145,9 +150,42 @@ function MediaTextEdit( { attributes, isSelected, setAttributes } ) {
rel,
verticalAlignment,
allowedBlocks,
useFeaturedImage,
} = attributes;
const mediaSizeSlug = attributes.mediaSizeSlug || DEFAULT_MEDIA_SIZE_SLUG;

const [ featuredImage ] = useEntityProp(
'postType',
postType,
'featured_media',
postId
);

const featuredImageMedia = useSelect(
( select ) =>
featuredImage &&
select( coreStore ).getMedia( featuredImage, { context: 'view' } ),
[ featuredImage ]
);

const featuredImageURL = useFeaturedImage
? featuredImageMedia?.source_url
: '';
const featuredImageAlt = useFeaturedImage
? featuredImageMedia?.alt_text
: '';

const toggleUseFeaturedImage = () => {
setAttributes( {
imageFill: false,
mediaType: 'image',
mediaId: undefined,
mediaUrl: undefined,
mediaAlt: undefined,
useFeaturedImage: ! useFeaturedImage,
} );
};

const { imageSizes, image } = useSelect(
( select ) => {
const { getSettings } = select( blockEditorStore );
Expand Down Expand Up @@ -261,25 +299,30 @@ function MediaTextEdit( { attributes, isSelected, setAttributes } ) {
}
/>
) }
{ imageFill && mediaUrl && mediaType === 'image' && (
<FocalPointPicker
__nextHasNoMarginBottom
__next40pxDefaultSize
label={ __( 'Focal point' ) }
url={ mediaUrl }
value={ focalPoint }
onChange={ ( value ) =>
setAttributes( { focalPoint: value } )
}
onDragStart={ imperativeFocalPointPreview }
onDrag={ imperativeFocalPointPreview }
/>
) }
{ mediaType === 'image' && (
{ imageFill &&
( mediaUrl || featuredImageURL ) &&
mediaType === 'image' && (
<FocalPointPicker
__nextHasNoMarginBottom
label={ __( 'Focal point' ) }
url={
useFeaturedImage && featuredImageURL
? featuredImageURL
: mediaUrl
}
value={ focalPoint }
onChange={ ( value ) =>
setAttributes( { focalPoint: value } )
}
onDragStart={ imperativeFocalPointPreview }
onDrag={ imperativeFocalPointPreview }
/>
) }
{ mediaType === 'image' && ( mediaUrl || featuredImageURL ) && (
<TextareaControl
__nextHasNoMarginBottom
label={ __( 'Alternative text' ) }
value={ mediaAlt }
value={ mediaAlt || featuredImageAlt }
onChange={ onMediaAltChange }
help={
<>
Expand All @@ -303,6 +346,16 @@ function MediaTextEdit( { attributes, isSelected, setAttributes } ) {
) }
/>
) }
{ ( mediaUrl || featuredImageURL ) && (
<RangeControl
__nextHasNoMarginBottom
label={ __( 'Media width' ) }
value={ temporaryMediaWidth || mediaWidth }
onChange={ commitWidthChange }
min={ WIDTH_CONSTRAINT_PERCENTAGE }
max={ 100 - WIDTH_CONSTRAINT_PERCENTAGE }
/>
) }
</PanelBody>
);

Expand Down Expand Up @@ -353,7 +406,11 @@ function MediaTextEdit( { attributes, isSelected, setAttributes } ) {
onChangeUrl={ onSetHref }
linkDestination={ linkDestination }
mediaType={ mediaType }
mediaUrl={ image && image.source_url }
mediaUrl={
useFeaturedImage && featuredImageURL
? featuredImageURL
: image && image.source_url
}
mediaLink={ image && image.link }
linkTarget={ linkTarget }
linkClass={ linkClass }
Expand All @@ -370,6 +427,7 @@ function MediaTextEdit( { attributes, isSelected, setAttributes } ) {
commitWidthChange={ commitWidthChange }
ref={ refMediaContainer }
enableResize={ blockEditingMode === 'default' }
toggleUseFeaturedImage={ toggleUseFeaturedImage }
{ ...{
focalPoint,
imageFill,
Expand All @@ -381,6 +439,9 @@ function MediaTextEdit( { attributes, isSelected, setAttributes } ) {
mediaType,
mediaUrl,
mediaWidth,
useFeaturedImage,
featuredImageURL,
featuredImageAlt,
} }
/>
{ mediaPosition !== 'right' && <div { ...innerBlocksProps } /> }
Expand Down
8 changes: 7 additions & 1 deletion packages/block-library/src/media-text/editor.scss
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,17 @@
width: 100% !important;
}

.wp-block-media-text.is-image-fill .editor-media-container__resizer {
.wp-block-media-text.is-image-fill .editor-media-container__resizer,
.wp-block-media-text.is-image-fill .components-placeholder.has-illustration {
// The resizer sets an inline height but for the image fill we set it to full height.
height: 100% !important;
}

.wp-block-media-text > .block-editor-block-list__layout > .block-editor-block-list__block {
max-width: unset;
}

/* Make the featured image placeholder the same height as the media selection area. */
.wp-block-media-text--placeholder-image {
min-height: 205px;
}
66 changes: 66 additions & 0 deletions packages/block-library/src/media-text/index.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php
/**
* Server-side rendering of the `core/media-text` block.
*
* @package WordPress
*/

/**
* Renders the `core/media-text` block on server.
*
* @param array $attributes The block attributes.
* @param string $content The block rendered content.
*
* @return string Returns the Media & Text block markup, if useFeaturedImage is true.
*/
function render_block_core_media_text( $attributes, $content ) {
if ( false === $attributes['useFeaturedImage'] ) {
return $content;
}

if ( in_the_loop() ) {
update_post_thumbnail_cache();
}

$current_featured_image = get_the_post_thumbnail_url();
if ( ! $current_featured_image ) {
return $content;
}

$image_tag = '<figure class="wp-block-media-text__media"><img>';
$content = preg_replace( '/<figure\s+class="wp-block-media-text__media">/', $image_tag, $content );

$processor = new WP_HTML_Tag_Processor( $content );
if ( isset( $attributes['imageFill'] ) && $attributes['imageFill'] ) {
$position = '50% 50%';
if ( isset( $attributes['focalPoint'] ) ) {
$position = round( $attributes['focalPoint']['x'] * 100 ) . '% ' . round( $attributes['focalPoint']['y'] * 100 ) . '%';
}
$processor->next_tag( 'figure' );
$processor->set_attribute( 'style', 'background-image:url(' . esc_url( $current_featured_image ) . ');background-position:' . $position . ';' );
}
$processor->next_tag( 'img' );
$media_size_slug = 'full';
if ( isset( $attributes['mediaSizeSlug'] ) ) {
$media_size_slug = $attributes['mediaSizeSlug'];
}
$processor->set_attribute( 'src', esc_url( $current_featured_image ) );
$processor->set_attribute( 'class', 'wp-image-' . get_post_thumbnail_id() . ' size-' . $media_size_slug );

$content = $processor->get_updated_html();

return $content;
}

/**
* Registers the `core/media-text` block renderer on server.
*/
function register_block_core_media_text() {
register_block_type_from_metadata(
__DIR__ . '/media-text',
array(
'render_callback' => 'render_block_core_media_text',
)
);
}
add_action( 'init', 'register_block_core_media_text' );

0 comments on commit a9a57c4

Please sign in to comment.