Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
21 changes: 21 additions & 0 deletions packages/media-fields/src/media_thumbnail/style.scss
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,27 @@
align-items: center;
position: relative;
height: 100%;

&.is-loading,
&.is-loaded {
img {
@media not (prefers-reduced-motion) {
transition: opacity 0.1s linear;
}
}
}

&.is-loading {
img {
opacity: 0;
}
}

&.is-loaded {
img {
opacity: 1;
}
}
}

.dataviews-media-field__media-thumbnail--image {
Expand Down
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
);
} );
} );
} );
149 changes: 122 additions & 27 deletions packages/media-fields/src/media_thumbnail/view.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
/**
* External dependencies
*/
import clsx from 'clsx';

/**
* WordPress dependencies
*/
Expand All @@ -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';
Expand All @@ -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;

Copy link
Copy Markdown
Member

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

🎉


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,
Expand Down Expand Up @@ -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' );

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

What about 'complete' as well? No biggie. Shame there's no loaded property on the IMG instance as well, then we'd have the complete set!

https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/complete

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I mostly picked instant here since we'd already used it in the Author field, but this state is effectively a no-op — it doesn't output any classname at all, so it skips applying an is-loaded classname. This way we can avoid the animation altogether for images that were complete (loaded) at the time of the component mounting.

All of which is to say, the model we have of loading state here is slightly different to the states of the img element itself.

Happy to rename this one to complete if it feels clearer... I mostly wanted to capture a state which says "don't do any animation, just display the image immediately if it's already loaded when we mounted" 😄

} 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,
Expand Down Expand Up @@ -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 ) }
/>
);
}
Loading