Repository navigation
Media Thumbnail Field: Optimise image loading #75811
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
Changes from all commits
45f58ab
5a135e1
b406b4d
0bd1e88
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,161 @@ | ||
| /** | ||
| * Internal dependencies | ||
| */ | ||
| import { getBestImageUrl } from '../view'; | ||
|
|
||
| type Media = Parameters< typeof getBestImageUrl >[ 0 ]; | ||
|
|
||
| const baseMedia: Media = { | ||
| id: 1, | ||
| date: '2024-01-01T00:00:00', | ||
| date_gmt: '2024-01-01T00:00:00', | ||
| guid: { | ||
| raw: 'https://example.com/?attachment_id=1', | ||
| rendered: 'https://example.com/?attachment_id=1', | ||
| }, | ||
| modified: '2024-01-01T00:00:00', | ||
| modified_gmt: '2024-01-01T00:00:00', | ||
| slug: 'test-image', | ||
| status: 'publish', | ||
| type: 'attachment', | ||
| link: 'https://example.com/test-image/', | ||
| title: { raw: 'Test Image', rendered: 'Test Image' }, | ||
| author: 1, | ||
| featured_media: 0, | ||
| comment_status: 'open', | ||
| ping_status: 'closed', | ||
| template: '', | ||
| permalink_template: '', | ||
| generated_slug: 'test-image', | ||
| class_list: [ 'attachment' ], | ||
| caption: { raw: '', rendered: '' }, | ||
| description: { raw: '', rendered: '' }, | ||
| alt_text: 'A test image', | ||
| media_type: 'image', | ||
| mime_type: 'image/jpeg', | ||
| post: null, | ||
| source_url: 'https://example.com/original.jpg', | ||
| missing_image_sizes: [], | ||
| meta: {}, | ||
| media_details: { | ||
| sizes: { | ||
| thumbnail: { | ||
| file: 'original-150x150.jpg', | ||
| width: 150, | ||
| height: 150, | ||
| mime_type: 'image/jpeg', | ||
| source_url: 'https://example.com/thumb.jpg', | ||
| }, | ||
| medium: { | ||
| file: 'original-300x200.jpg', | ||
| width: 300, | ||
| height: 200, | ||
| mime_type: 'image/jpeg', | ||
| source_url: 'https://example.com/medium.jpg', | ||
| }, | ||
| large: { | ||
| file: 'original-1024x683.jpg', | ||
| width: 1024, | ||
| height: 683, | ||
| mime_type: 'image/jpeg', | ||
| source_url: 'https://example.com/large.jpg', | ||
| }, | ||
| }, | ||
| }, | ||
| }; | ||
|
|
||
| describe( 'getBestImageUrl', () => { | ||
| describe( 'when media_details.sizes is unavailable', () => { | ||
| it( 'returns source_url when media_details has no sizes', () => { | ||
| const media = { | ||
| ...baseMedia, | ||
| media_details: { sizes: {} }, | ||
| }; | ||
| expect( getBestImageUrl( media ) ).toBe( baseMedia.source_url ); | ||
| } ); | ||
| } ); | ||
|
|
||
| describe( 'when configSizes is not provided or unparseable', () => { | ||
| it( 'returns source_url when configSizes is undefined', () => { | ||
| expect( getBestImageUrl( baseMedia ) ).toBe( baseMedia.source_url ); | ||
| } ); | ||
|
|
||
| it( 'returns source_url when configSizes is not a number', () => { | ||
| expect( getBestImageUrl( baseMedia, 'auto' ) ).toBe( | ||
| baseMedia.source_url | ||
| ); | ||
| } ); | ||
| } ); | ||
|
|
||
| describe( 'size selection with a valid target width', () => { | ||
| it( 'picks the smallest size >= target width', () => { | ||
| expect( getBestImageUrl( baseMedia, '200px' ) ).toBe( | ||
| 'https://example.com/medium.jpg' | ||
| ); | ||
| } ); | ||
|
|
||
| it( 'picks an exact match', () => { | ||
| expect( getBestImageUrl( baseMedia, '300px' ) ).toBe( | ||
| 'https://example.com/medium.jpg' | ||
| ); | ||
| } ); | ||
|
|
||
| it( 'picks the smallest available size when target is very small', () => { | ||
| expect( getBestImageUrl( baseMedia, '50px' ) ).toBe( | ||
| 'https://example.com/thumb.jpg' | ||
| ); | ||
| } ); | ||
|
|
||
| it( 'falls back to the largest size when target exceeds all sizes', () => { | ||
| expect( getBestImageUrl( baseMedia, '2000px' ) ).toBe( | ||
| 'https://example.com/large.jpg' | ||
| ); | ||
| } ); | ||
| } ); | ||
|
|
||
| // These tests deliberately omit required Size fields (width, height, etc.) | ||
| // to verify runtime defensiveness, so we cast via `unknown` to bypass TS. | ||
| describe( 'when size entries have missing or invalid widths', () => { | ||
| it( 'skips entries without a width and selects from valid ones', () => { | ||
| const media = { | ||
| ...baseMedia, | ||
| media_details: { | ||
| sizes: { | ||
| broken: { | ||
| source_url: 'https://example.com/broken.jpg', | ||
| }, | ||
| medium: { | ||
| file: 'original-300x200.jpg', | ||
| width: 300, | ||
| height: 200, | ||
| mime_type: 'image/jpeg', | ||
| source_url: 'https://example.com/medium.jpg', | ||
| }, | ||
| }, | ||
| }, | ||
| } as unknown as Media; | ||
| expect( getBestImageUrl( media, '200px' ) ).toBe( | ||
| 'https://example.com/medium.jpg' | ||
| ); | ||
| } ); | ||
|
|
||
| it( 'falls back to source_url when all entries lack a valid width', () => { | ||
| const media = { | ||
| ...baseMedia, | ||
| media_details: { | ||
| sizes: { | ||
| broken: { | ||
| source_url: 'https://example.com/broken.jpg', | ||
| }, | ||
| also_broken: { | ||
| source_url: 'https://example.com/also-broken.jpg', | ||
| }, | ||
| }, | ||
| }, | ||
| } as unknown as Media; | ||
| expect( getBestImageUrl( media, '200px' ) ).toBe( | ||
| baseMedia.source_url | ||
| ); | ||
| } ); | ||
| } ); | ||
| } ); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,8 @@ | ||
| /** | ||
| * External dependencies | ||
| */ | ||
| import clsx from 'clsx'; | ||
|
|
||
| /** | ||
| * WordPress dependencies | ||
| */ | ||
|
|
@@ -8,7 +13,7 @@ import { | |
| __experimentalVStack as VStack, | ||
| Icon, | ||
| } from '@wordpress/components'; | ||
| import { useState } from '@wordpress/element'; | ||
| import { useState, useRef, useLayoutEffect } from '@wordpress/element'; | ||
| import type { Attachment } from '@wordpress/core-data'; | ||
| import { getFilename } from '@wordpress/url'; | ||
| import type { DataViewRenderFieldProps } from '@wordpress/dataviews'; | ||
|
|
@@ -18,6 +23,59 @@ import type { DataViewRenderFieldProps } from '@wordpress/dataviews'; | |
| import { getMediaTypeFromMimeType } from '../utils/get-media-type-from-mime-type'; | ||
| import type { MediaItem } from '../types'; | ||
|
|
||
| /** | ||
| * Given the available image sizes and a target display width, returns the URL | ||
| * of the smallest size whose width is >= the target. Falls back to the largest | ||
| * available size, or the original source_url. | ||
| * | ||
| * @param featuredMedia The media item with size details. | ||
| * @param configSizes The target display size string (e.g. '900px'). | ||
| */ | ||
| export function getBestImageUrl( | ||
| featuredMedia: Attachment | MediaItem, | ||
| configSizes?: string | ||
| ): string { | ||
| const sizes = featuredMedia?.media_details?.sizes; | ||
| if ( ! sizes ) { | ||
| return featuredMedia.source_url; | ||
| } | ||
|
|
||
| const sizeEntries = Object.values( sizes ); | ||
|
|
||
| if ( ! sizeEntries.length ) { | ||
| return featuredMedia.source_url; | ||
| } | ||
|
|
||
| // Parse target width from config.sizes (e.g. '900px' → 900). | ||
| const targetWidth = configSizes ? parseInt( configSizes, 10 ) : NaN; | ||
|
|
||
| if ( ! Number.isNaN( targetWidth ) ) { | ||
| // Filter to entries that have a valid numeric width. | ||
| const validEntries = sizeEntries.filter( | ||
| ( s ) => typeof s.width === 'number' && ! Number.isNaN( s.width ) | ||
| ); | ||
|
|
||
| if ( ! validEntries.length ) { | ||
| return featuredMedia.source_url; | ||
| } | ||
|
|
||
| // Sort ascending by width. | ||
| const sorted = [ ...validEntries ].sort( | ||
| ( a, b ) => a.width - b.width | ||
| ); | ||
| // Pick the smallest size that is >= target width. | ||
| const match = sorted.find( ( s ) => s.width >= targetWidth ); | ||
| if ( match ) { | ||
| return match.source_url; | ||
| } | ||
| // No size large enough — use the largest available. | ||
| return sorted[ sorted.length - 1 ].source_url; | ||
| } | ||
|
|
||
| // If we can't parse the target, fall back to source_url. | ||
| return featuredMedia.source_url; | ||
| } | ||
|
|
||
| function FallbackView( { | ||
| item, | ||
| filename, | ||
|
|
@@ -50,6 +108,64 @@ function FallbackView( { | |
| ); | ||
| } | ||
|
|
||
| function ImageView( { | ||
| item, | ||
| configSizes, | ||
| onError, | ||
| }: { | ||
| item: Attachment | MediaItem; | ||
| configSizes?: string; | ||
| onError: () => void; | ||
| } ) { | ||
| const imageUrl = getBestImageUrl( item, configSizes ); | ||
|
|
||
| /* | ||
| * Use three states to avoid fade-in animation for cached images: | ||
| * 'instant' = image already cached, 'loading' = waiting, 'loaded' = just finished. | ||
| * | ||
| * useLayoutEffect runs synchronously after DOM mutations but before paint, | ||
| * so we can check img.complete to detect disk-cached images and skip the | ||
| * fade-in animation entirely. | ||
| */ | ||
| const imgRef = useRef< HTMLImageElement >( null ); | ||
| const [ loadingState, setLoadingState ] = useState< | ||
| 'instant' | 'loading' | 'loaded' | ||
| >( 'loading' ); | ||
|
|
||
| useLayoutEffect( () => { | ||
| if ( imgRef.current?.complete ) { | ||
| setLoadingState( 'instant' ); | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. What about 'complete' as well? No biggie. Shame there's no https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/complete
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I mostly picked All of which is to say, the model we have of loading state here is slightly different to the states of the Happy to rename this one to |
||
| } else { | ||
| setLoadingState( 'loading' ); | ||
| } | ||
| }, [ imageUrl ] ); | ||
|
|
||
| const handleLoad = () => { | ||
| if ( loadingState === 'loading' ) { | ||
| setLoadingState( 'loaded' ); | ||
| } | ||
| }; | ||
|
|
||
| return ( | ||
| <div | ||
| className={ clsx( 'dataviews-media-field__media-thumbnail', { | ||
| 'is-loading': loadingState === 'loading', | ||
| 'is-loaded': loadingState === 'loaded', | ||
| } ) } | ||
| > | ||
| <img | ||
| ref={ imgRef } | ||
| className="dataviews-media-field__media-thumbnail--image" | ||
| src={ imageUrl } | ||
| alt={ item.alt_text || item.title.raw } | ||
| onLoad={ handleLoad } | ||
| onError={ onError } | ||
| loading="lazy" | ||
| /> | ||
| </div> | ||
| ); | ||
| } | ||
|
|
||
| export default function MediaThumbnailView( { | ||
| item, | ||
| config, | ||
|
|
@@ -91,31 +207,10 @@ export default function MediaThumbnailView( { | |
| } | ||
|
|
||
| return ( | ||
| <div className="dataviews-media-field__media-thumbnail"> | ||
| <img | ||
| className="dataviews-media-field__media-thumbnail--image" | ||
| src={ featuredMedia.source_url } | ||
| srcSet={ | ||
| featuredMedia?.media_details?.sizes | ||
| ? ( | ||
| Object.values( | ||
| featuredMedia.media_details.sizes | ||
| ) as Array< { | ||
| source_url: string; | ||
| width: number; | ||
| } > | ||
| ) | ||
| .map( | ||
| ( size ) => | ||
| `${ size.source_url } ${ size.width }w` | ||
| ) | ||
| .join( ', ' ) | ||
| : undefined | ||
| } | ||
| sizes={ config?.sizes || '100vw' } | ||
| alt={ featuredMedia.alt_text || featuredMedia.title.raw } | ||
| onError={ () => setImageError( true ) } | ||
| /> | ||
| </div> | ||
| <ImageView | ||
| item={ featuredMedia } | ||
| configSizes={ config?.sizes } | ||
| onError={ () => setImageError( true ) } | ||
| /> | ||
| ); | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is working pretty well for grid and table sizes:
Kapture.2026-02-23.at.18.02.01.mp4
🎉