diff --git a/backport-changelog/7.0/11015.md b/backport-changelog/7.0/11015.md new file mode 100644 index 00000000000000..557b4f1cb3c979 --- /dev/null +++ b/backport-changelog/7.0/11015.md @@ -0,0 +1,3 @@ +https://github.com/WordPress/wordpress-develop/pull/11015 + +* https://github.com/WordPress/gutenberg/pull/75817 diff --git a/lib/media/class-gutenberg-rest-attachments-controller.php b/lib/media/class-gutenberg-rest-attachments-controller.php index b457dd469bcdf6..8183e75463fac1 100644 --- a/lib/media/class-gutenberg-rest-attachments-controller.php +++ b/lib/media/class-gutenberg-rest-attachments-controller.php @@ -20,41 +20,44 @@ class Gutenberg_REST_Attachments_Controller extends WP_REST_Attachments_Controll public function register_routes(): void { parent::register_routes(); - // Only register the sideload route if the parent class doesn't already have it. - if ( ! method_exists( get_parent_class( $this ), 'sideload_item' ) ) { - $valid_image_sizes = array_keys( wp_get_registered_image_subsizes() ); - - // Special case to set 'original_image' in attachment metadata. - $valid_image_sizes[] = 'original'; - // Used for PDF thumbnails. - $valid_image_sizes[] = 'full'; - - register_rest_route( - $this->namespace, - '/' . $this->rest_base . '/(?P[\d]+)/sideload', + // Override the parent's sideload route so that 'scaled' is included + // in the image_size enum. Without the override, core's handler + // validates first and rejects 'scaled' before ours is tried. + $valid_image_sizes = array_keys( wp_get_registered_image_subsizes() ); + + // Special case to set 'original_image' in attachment metadata. + $valid_image_sizes[] = 'original'; + // Client-side big image threshold: sideload the scaled version. + $valid_image_sizes[] = 'scaled'; + // Used for PDF thumbnails. + $valid_image_sizes[] = 'full'; + + register_rest_route( + $this->namespace, + '/' . $this->rest_base . '/(?P[\d]+)/sideload', + array( array( - array( - 'methods' => WP_REST_Server::CREATABLE, - 'callback' => array( $this, 'sideload_item' ), - 'permission_callback' => array( $this, 'sideload_item_permissions_check' ), - 'args' => array( - 'id' => array( - 'description' => __( 'Unique identifier for the attachment.', 'gutenberg' ), - 'type' => 'integer', - ), - 'image_size' => array( - 'description' => __( 'Image size.', 'gutenberg' ), - 'type' => 'string', - 'enum' => $valid_image_sizes, - 'required' => true, - ), + 'methods' => WP_REST_Server::CREATABLE, + 'callback' => array( $this, 'sideload_item' ), + 'permission_callback' => array( $this, 'sideload_item_permissions_check' ), + 'args' => array( + 'id' => array( + 'description' => __( 'Unique identifier for the attachment.', 'gutenberg' ), + 'type' => 'integer', + ), + 'image_size' => array( + 'description' => __( 'Image size.', 'gutenberg' ), + 'type' => 'string', + 'enum' => $valid_image_sizes, + 'required' => true, ), ), - 'allow_batch' => $this->allow_batch, - 'schema' => array( $this, 'get_public_item_schema' ), - ) - ); - } + ), + 'allow_batch' => $this->allow_batch, + 'schema' => array( $this, 'get_public_item_schema' ), + ), + true // Override core's route so 'scaled' is included in the enum. + ); } /** @@ -210,6 +213,8 @@ public function create_item( $request ) { // Disable server-side EXIF rotation so the client can handle it. // This preserves the original orientation value in the metadata. add_filter( 'wp_image_maybe_exif_rotate', '__return_false', 100 ); + // Disable server-side big image scaling since the client handles it. + add_filter( 'big_image_size_threshold', '__return_zero', 100 ); } if ( ! $request['convert_format'] ) { @@ -221,6 +226,7 @@ public function create_item( $request ) { remove_filter( 'intermediate_image_sizes_advanced', '__return_empty_array', 100 ); remove_filter( 'fallback_intermediate_image_sizes', '__return_empty_array', 100 ); remove_filter( 'wp_image_maybe_exif_rotate', '__return_false', 100 ); + remove_filter( 'big_image_size_threshold', '__return_zero', 100 ); remove_filter( 'image_editor_output_format', '__return_empty_array', 100 ); return $response; @@ -275,7 +281,7 @@ private static function filter_wp_unique_filename( $filename, $dir, $number, $at } $matches = array(); - if ( preg_match( '/(.*)(-\d+x\d+)-' . $number . '$/', $name, $matches ) ) { + if ( preg_match( '/(.*)(-\d+x\d+|-scaled)-' . $number . '$/', $name, $matches ) ) { $filename_without_suffix = $matches[1] . $matches[2] . ".$ext"; if ( $matches[1] === $orig_name && ! file_exists( "$dir/$filename_without_suffix" ) ) { return $filename_without_suffix; @@ -381,6 +387,20 @@ public function sideload_item( WP_REST_Request $request ) { if ( 'original' === $image_size ) { $metadata['original_image'] = wp_basename( $path ); + } elseif ( 'scaled' === $image_size ) { + // The current attached file is the original; record it as original_image. + $current_file = get_attached_file( $attachment_id, true ); + $metadata['original_image'] = wp_basename( $current_file ); + + // Update the attached file to point to the scaled version. + update_attached_file( $attachment_id, $path ); + + $size = wp_getimagesize( $path ); + + $metadata['width'] = $size ? $size[0] : 0; + $metadata['height'] = $size ? $size[1] : 0; + $metadata['filesize'] = wp_filesize( $path ); + $metadata['file'] = _wp_relative_upload_path( $path ); } else { $metadata['sizes'] = $metadata['sizes'] ?? array(); diff --git a/packages/upload-media/src/store/private-actions.ts b/packages/upload-media/src/store/private-actions.ts index 4ec74bb88b8735..231c3cb4e219a9 100644 --- a/packages/upload-media/src/store/private-actions.ts +++ b/packages/upload-media/src/store/private-actions.ts @@ -717,22 +717,7 @@ export function prepareItem( id: QueueItemId ) { // For images that can be processed by vips, check if we need to scale down based on threshold. if ( isImage && isVipsSupported ) { - const { bigImageSizeThreshold, imageOutputFormats } = settings; - - // If a threshold is set, add a resize operation to scale down large images. - // This matches WordPress core's behavior in wp_create_image_subsizes(). - if ( bigImageSizeThreshold ) { - operations.push( [ - OperationType.ResizeCrop, - { - resize: { - width: bigImageSizeThreshold, - height: bigImageSizeThreshold, - }, - isThresholdResize: true, - }, - ] ); - } + const { imageOutputFormats } = settings; // Check if we need to transcode to a different format. // Uses WordPress image_editor_output_format filter settings. @@ -1126,8 +1111,8 @@ export function generateThumbnails( id: QueueItemId ) { // Use sourceFile for thumbnail generation to preserve quality. // WordPress core generates thumbnails from the original (unscaled) image. // Vips will auto-rotate based on EXIF orientation during thumbnail generation. - const file = attachment.media_filename - ? renameFile( item.sourceFile, attachment.media_filename ) + const file = attachment.filename + ? renameFile( item.sourceFile, attachment.filename ) : item.sourceFile; const batchId = uuidv4(); @@ -1205,6 +1190,54 @@ export function generateThumbnails( id: QueueItemId ) { operations: thumbnailOperations, } ); } + + // Create and sideload the scaled version. + const { bigImageSizeThreshold } = settings; + if ( bigImageSizeThreshold && attachment.id ) { + // Rename sourceFile to match the server attachment filename. + const sourceForScaled = attachment.filename + ? renameFile( item.sourceFile, attachment.filename ) + : item.sourceFile; + + // Add scaling to queue. + const scaledOperations: Operation[] = [ + [ + OperationType.ResizeCrop, + { + resize: { + width: bigImageSizeThreshold, + height: bigImageSizeThreshold, + }, + isThresholdResize: true, + }, + ], + ]; + + // Add transcoding if format conversion is configured. + if ( thumbnailTranscodeOperation ) { + scaledOperations.push( thumbnailTranscodeOperation ); + } + + scaledOperations.push( OperationType.Upload ); + + dispatch.addSideloadItem( { + file: sourceForScaled, + onChange: ( [ updatedAttachment ] ) => { + if ( isBlobURL( updatedAttachment.url ) ) { + return; + } + item.onChange?.( [ updatedAttachment ] ); + }, + batchId, + parentId: item.id, + additionalData: { + post: attachment.id, + image_size: 'scaled', + convert_format: false, + }, + operations: scaledOperations, + } ); + } } dispatch.finishOperation( id, {} ); diff --git a/packages/upload-media/src/store/types.ts b/packages/upload-media/src/store/types.ts index 2c18ae9cbd3a02..579ad27d5c7e9e 100644 --- a/packages/upload-media/src/store/types.ts +++ b/packages/upload-media/src/store/types.ts @@ -193,7 +193,6 @@ export interface Attachment { mime_type: string; featured_media?: number; missing_image_sizes?: string[]; - media_filename?: string; poster?: string; /** * EXIF orientation value from the original image. diff --git a/packages/upload-media/src/test/convert-blob-to-file.ts b/packages/upload-media/src/test/convert-blob-to-file.ts new file mode 100644 index 00000000000000..9156fb3314c028 --- /dev/null +++ b/packages/upload-media/src/test/convert-blob-to-file.ts @@ -0,0 +1,66 @@ +/** + * Internal dependencies + */ +import { convertBlobToFile } from '../utils'; + +describe( 'convertBlobToFile', () => { + it( 'should return a File unchanged', () => { + const file = new File( [ 'content' ], 'photo.jpg', { + type: 'image/jpeg', + } ); + const result = convertBlobToFile( file ); + expect( result ).toBe( file ); + expect( result.name ).toBe( 'photo.jpg' ); + } ); + + it( 'should convert a Blob with a default name', () => { + const blob = new Blob( [ 'content' ], { type: 'image/png' } ); + const result = convertBlobToFile( blob ); + expect( result ).toBeInstanceOf( File ); + expect( result.name ).toBe( 'image.png' ); + expect( result.type ).toBe( 'image/png' ); + } ); + + it( 'should use "document" prefix for PDF blobs', () => { + const blob = new Blob( [ 'content' ], { type: 'application/pdf' } ); + const result = convertBlobToFile( blob ); + expect( result.name ).toBe( 'document.pdf' ); + } ); + + it( 'should preserve the name from cross-realm File objects', () => { + // Simulate a cross-realm File object (e.g., from an iframe). + // These objects have a `name` property but fail `instanceof File`. + const crossRealmFile = new Blob( [ 'content' ], { + type: 'image/jpeg', + } ); + Object.defineProperty( crossRealmFile, 'name', { + value: 'IMG_7977.jpg', + writable: false, + } ); + Object.defineProperty( crossRealmFile, 'lastModified', { + value: 1700000000000, + writable: false, + } ); + + const result = convertBlobToFile( crossRealmFile ); + expect( result ).toBeInstanceOf( File ); + expect( result.name ).toBe( 'IMG_7977.jpg' ); + expect( result.type ).toBe( 'image/jpeg' ); + expect( result.lastModified ).toBe( 1700000000000 ); + } ); + + it( 'should preserve the name for non-image cross-realm File objects', () => { + const crossRealmFile = new Blob( [ 'content' ], { + type: 'application/pdf', + } ); + Object.defineProperty( crossRealmFile, 'name', { + value: 'my-document.pdf', + writable: false, + } ); + + const result = convertBlobToFile( crossRealmFile ); + expect( result ).toBeInstanceOf( File ); + expect( result.name ).toBe( 'my-document.pdf' ); + expect( result.type ).toBe( 'application/pdf' ); + } ); +} ); diff --git a/packages/upload-media/src/utils.ts b/packages/upload-media/src/utils.ts index 3950ec03887928..b326f52be41716 100644 --- a/packages/upload-media/src/utils.ts +++ b/packages/upload-media/src/utils.ts @@ -9,6 +9,10 @@ import { _x } from '@wordpress/i18n'; * * If it is already a File object, it is returned unchanged. * + * Handles cross-realm File objects (e.g., from iframes) that have a `name` + * property but fail `instanceof File` checks because the File constructor + * differs between browsing contexts. + * * @param fileOrBlob Blob object. * @return File object. */ @@ -17,6 +21,20 @@ export function convertBlobToFile( fileOrBlob: Blob | File ): File { return fileOrBlob; } + // Handle cross-realm File objects (e.g., from iframes where the block + // editor canvas renders). These objects have a `name` property but fail + // the `instanceof File` check because each browsing context has its own + // File constructor. + if ( + 'name' in fileOrBlob && + typeof ( fileOrBlob as File ).name === 'string' + ) { + return new File( [ fileOrBlob ], ( fileOrBlob as File ).name, { + type: fileOrBlob.type, + lastModified: ( fileOrBlob as File ).lastModified, + } ); + } + // Extension is only an approximation. // The server will override it if incorrect. const ext = fileOrBlob.type.split( '/' )[ 1 ]; diff --git a/phpunit/media/class-gutenberg-rest-attachments-controller-test.php b/phpunit/media/class-gutenberg-rest-attachments-controller-test.php index 3a31dab4538fea..5b18f17ad0f93c 100644 --- a/phpunit/media/class-gutenberg-rest-attachments-controller-test.php +++ b/phpunit/media/class-gutenberg-rest-attachments-controller-test.php @@ -593,6 +593,235 @@ public function test_exif_orientation_in_schema() { $this->assertTrue( $schema['properties']['exif_orientation']['readonly'] ); } + /** + * Verifies that sideloading a scaled image sets original_image metadata + * and updates the attached file to the scaled version, matching core behavior. + * + * @see https://github.com/WordPress/wordpress-develop/blob/trunk/tests/phpunit/tests/media.php + * For similar core media tests that verify equivalent server-side behavior. + * + * @covers ::sideload_item + */ + public function test_sideload_scaled_sets_original_image_metadata() { + wp_set_current_user( self::$admin_id ); + + // Upload the original image with client-side processing. + $request = new WP_REST_Request( 'POST', '/wp/v2/media' ); + $request->set_header( 'Content-Type', 'image/jpeg' ); + $request->set_header( 'Content-Disposition', 'attachment; filename=my-photo.jpg' ); + $request->set_param( 'generate_sub_sizes', false ); + + $request->set_body( file_get_contents( DIR_TESTDATA . '/images/canola.jpg' ) ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + + $this->assertSame( 201, $response->get_status() ); + $attachment_id = $data['id']; + + // Record the original attached file path before sideloading scaled. + $original_attached_file = get_attached_file( $attachment_id, true ); + + // Sideload the -scaled version (simulating client-side big image threshold resize). + $request = new WP_REST_Request( 'POST', "/wp/v2/media/$attachment_id/sideload" ); + $request->set_header( 'Content-Type', 'image/jpeg' ); + $request->set_header( 'Content-Disposition', 'attachment; filename=my-photo-scaled.jpg' ); + $request->set_param( 'image_size', 'scaled' ); + + $request->set_body( file_get_contents( DIR_TESTDATA . '/images/canola.jpg' ) ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + + $this->assertSame( 200, $response->get_status() ); + + // Verify original_image metadata points to the original filename. + $metadata = wp_get_attachment_metadata( $attachment_id, true ); + $this->assertArrayHasKey( 'original_image', $metadata, 'original_image metadata should be set after scaled sideload.' ); + $this->assertSame( wp_basename( $original_attached_file ), $metadata['original_image'], 'original_image should be the original filename before scaling.' ); + + // Verify the attached file now points to the scaled version. + $new_attached_file = get_attached_file( $attachment_id, true ); + $this->assertStringContainsString( '-scaled', wp_basename( $new_attached_file ), 'Attached file should now be the -scaled version.' ); + $this->assertSame( 'my-photo-scaled.jpg', wp_basename( $new_attached_file ) ); + + // Verify metadata dimensions and file are updated. + $this->assertArrayHasKey( 'width', $metadata ); + $this->assertArrayHasKey( 'height', $metadata ); + $this->assertArrayHasKey( 'filesize', $metadata ); + $this->assertArrayHasKey( 'file', $metadata ); + $this->assertGreaterThan( 0, $metadata['width'] ); + $this->assertGreaterThan( 0, $metadata['height'] ); + $this->assertGreaterThan( 0, $metadata['filesize'] ); + + // Verify wp_get_original_image_path returns the original file. + $original_path = wp_get_original_image_path( $attachment_id ); + $this->assertSame( 'my-photo.jpg', wp_basename( $original_path ), 'wp_get_original_image_path() should return the original file.' ); + } + + /** + * Verifies that sideloading with image_size=original sets original_image metadata + * without changing the attached file. + * + * @covers ::sideload_item + */ + public function test_sideload_original_sets_original_image_metadata() { + wp_set_current_user( self::$admin_id ); + + // Upload via REST so the file is in the uploads directory. + $request = new WP_REST_Request( 'POST', '/wp/v2/media' ); + $request->set_header( 'Content-Type', 'image/jpeg' ); + $request->set_header( 'Content-Disposition', 'attachment; filename=canola.jpg' ); + $request->set_param( 'generate_sub_sizes', false ); + + $request->set_body( file_get_contents( DIR_TESTDATA . '/images/canola.jpg' ) ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + + $this->assertSame( 201, $response->get_status() ); + $attachment_id = $data['id']; + + // The attached file before sideload. + $attached_file_before = get_attached_file( $attachment_id, true ); + + // Sideload the "original" version. + $request = new WP_REST_Request( 'POST', "/wp/v2/media/$attachment_id/sideload" ); + $request->set_header( 'Content-Type', 'image/jpeg' ); + $request->set_header( 'Content-Disposition', 'attachment; filename=canola-original.jpg' ); + $request->set_param( 'image_size', 'original' ); + + $request->set_body( file_get_contents( DIR_TESTDATA . '/images/canola.jpg' ) ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + + $this->assertSame( 200, $response->get_status() ); + + // Verify original_image metadata is set to the sideloaded file. + $metadata = wp_get_attachment_metadata( $attachment_id, true ); + $this->assertArrayHasKey( 'original_image', $metadata ); + $this->assertSame( 'canola-original.jpg', $metadata['original_image'] ); + + // Verify the attached file was NOT changed (only scaled changes it). + $attached_file_after = get_attached_file( $attachment_id, true ); + $this->assertSame( $attached_file_before, $attached_file_after, 'Attached file should not change when sideloading original.' ); + } + + /** + * Verifies the full client-side upload flow with scaled image: + * upload original, sideload sub-sizes, sideload scaled version. + * + * After the full flow, metadata should match core's server-side behavior: + * - original_image points to the unscaled original + * - attached file points to -scaled version + * - sub-sizes are present in metadata + * + * @covers ::create_item + * @covers ::sideload_item + */ + public function test_full_client_side_upload_flow_with_scaled_image() { + wp_set_current_user( self::$admin_id ); + + // Step 1: Upload the original image with client-side processing. + $request = new WP_REST_Request( 'POST', '/wp/v2/media' ); + $request->set_header( 'Content-Type', 'image/jpeg' ); + $request->set_header( 'Content-Disposition', 'attachment; filename=landscape.jpg' ); + $request->set_param( 'generate_sub_sizes', false ); + + $request->set_body( file_get_contents( DIR_TESTDATA . '/images/canola.jpg' ) ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + + $this->assertSame( 201, $response->get_status() ); + $attachment_id = $data['id']; + $this->assertNotEmpty( $data['missing_image_sizes'], 'Should have missing image sizes after client-side upload.' ); + + // Step 2: Sideload a thumbnail sub-size. + $request = new WP_REST_Request( 'POST', "/wp/v2/media/$attachment_id/sideload" ); + $request->set_header( 'Content-Type', 'image/jpeg' ); + $request->set_header( 'Content-Disposition', 'attachment; filename=landscape-150x150.jpg' ); + $request->set_param( 'image_size', 'thumbnail' ); + + $request->set_body( file_get_contents( DIR_TESTDATA . '/images/canola.jpg' ) ); + $response = rest_get_server()->dispatch( $request ); + $this->assertSame( 200, $response->get_status() ); + + // Verify sub-size was added to metadata. + $metadata = wp_get_attachment_metadata( $attachment_id, true ); + $this->assertArrayHasKey( 'thumbnail', $metadata['sizes'] ); + $this->assertSame( 'landscape-150x150.jpg', $metadata['sizes']['thumbnail']['file'] ); + + // Step 3: Sideload the scaled version (big image threshold). + $request = new WP_REST_Request( 'POST', "/wp/v2/media/$attachment_id/sideload" ); + $request->set_header( 'Content-Type', 'image/jpeg' ); + $request->set_header( 'Content-Disposition', 'attachment; filename=landscape-scaled.jpg' ); + $request->set_param( 'image_size', 'scaled' ); + + $request->set_body( file_get_contents( DIR_TESTDATA . '/images/canola.jpg' ) ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + + $this->assertSame( 200, $response->get_status() ); + + // Verify final metadata matches expected state. + $metadata = wp_get_attachment_metadata( $attachment_id, true ); + + // original_image should point to the original unscaled file. + $this->assertArrayHasKey( 'original_image', $metadata ); + $this->assertSame( 'landscape.jpg', $metadata['original_image'], 'original_image should be the original filename.' ); + + // The attached file should now be the scaled version. + $attached_file = get_attached_file( $attachment_id, true ); + $this->assertSame( 'landscape-scaled.jpg', wp_basename( $attached_file ), 'Attached file should be the -scaled version.' ); + + // The metadata file should reflect the scaled version. + $this->assertStringContainsString( 'landscape-scaled.jpg', $metadata['file'] ); + + // Sub-sizes should still be present. + $this->assertArrayHasKey( 'thumbnail', $metadata['sizes'] ); + $this->assertSame( 'landscape-150x150.jpg', $metadata['sizes']['thumbnail']['file'] ); + + // wp_get_original_image_path should resolve to the original. + $original_path = wp_get_original_image_path( $attachment_id ); + $this->assertSame( 'landscape.jpg', wp_basename( $original_path ) ); + } + + /** + * Verifies that the scaled sideload filename filter works correctly + * and prevents WordPress from adding numeric suffixes to -scaled filenames. + * + * @covers ::sideload_item + */ + public function test_sideload_scaled_filename_not_suffixed() { + wp_set_current_user( self::$admin_id ); + + $request = new WP_REST_Request( 'POST', '/wp/v2/media' ); + $request->set_header( 'Content-Type', 'image/jpeg' ); + $request->set_header( 'Content-Disposition', 'attachment; filename=test-photo.jpg' ); + $request->set_param( 'generate_sub_sizes', false ); + + $request->set_body( file_get_contents( DIR_TESTDATA . '/images/canola.jpg' ) ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + + $this->assertSame( 201, $response->get_status() ); + $attachment_id = $data['id']; + + // Sideload the scaled version. + $request = new WP_REST_Request( 'POST', "/wp/v2/media/$attachment_id/sideload" ); + $request->set_header( 'Content-Type', 'image/jpeg' ); + $request->set_header( 'Content-Disposition', 'attachment; filename=test-photo-scaled.jpg' ); + $request->set_param( 'image_size', 'scaled' ); + + $request->set_body( file_get_contents( DIR_TESTDATA . '/images/canola.jpg' ) ); + $response = rest_get_server()->dispatch( $request ); + $data = $response->get_data(); + + $this->assertSame( 200, $response->get_status() ); + + // The filename should not have a numeric suffix like -scaled-1.jpg. + $attached_file = get_attached_file( $attachment_id, true ); + $this->assertSame( 'test-photo-scaled.jpg', wp_basename( $attached_file ), 'Scaled filename should not have a numeric suffix.' ); + $this->assertStringNotContainsString( '-scaled-1', wp_basename( $attached_file ) ); + } + /** * Verifies metadata consistency between server-side and client-side upload flows. * diff --git a/test/e2e/specs/editor/various/big-image-size-threshold.spec.js b/test/e2e/specs/editor/various/big-image-size-threshold.spec.js index 30239f121c7e38..a574b4f4ef83c4 100644 --- a/test/e2e/specs/editor/various/big-image-size-threshold.spec.js +++ b/test/e2e/specs/editor/various/big-image-size-threshold.spec.js @@ -21,6 +21,38 @@ test.use( { }, } ); +/** + * Waits for the upload queue to drain and returns the attachment ID + * from the currently selected image block. + * + * @param {Page} page Playwright page object. + * @return {Promise} The attachment ID. + */ +async function waitForUploadAndGetImageId( page ) { + // Wait for the upload queue to be empty. + await page.waitForFunction( + () => { + const uploadStore = window.wp.data.select( 'core/upload-media' ); + if ( ! uploadStore ) { + return true; // Store not available, upload happened server-side. + } + const items = uploadStore.getItems(); + return items.length === 0; + }, + { timeout: 120000 } + ); + + // Get the image ID from the block. + const imageId = await page.evaluate( + () => + window.wp.data.select( 'core/block-editor' ).getSelectedBlock() + ?.attributes?.id + ); + + expect( imageId ).toBeTruthy(); + return imageId; +} + test.describe( 'Big image size threshold', () => { test.beforeAll( async ( { requestUtils } ) => { await requestUtils.deleteAllMedia(); @@ -34,14 +66,60 @@ test.describe( 'Big image size threshold', () => { await requestUtils.deleteAllMedia(); } ); - test( 'should scale down images larger than the threshold', async ( { + test( 'should preserve original filename through client-side upload', async ( { + page, + editor, + imageBlockUtils, + requestUtils, + } ) => { + // Skip if cross-origin isolation is not enabled. + const isCrossOriginIsolated = await page.evaluate( + () => window.crossOriginIsolated + ); + // eslint-disable-next-line playwright/no-skipped-test + test.skip( + ! isCrossOriginIsolated, + 'Cross-origin isolation headers not configured on server' + ); + + await editor.insertBlock( { name: 'core/image' } ); + + const imageBlock = editor.canvas.locator( + 'role=document[name="Block: Image"i]' + ); + await expect( imageBlock ).toBeVisible(); + + // Upload with a specific filename to verify it is preserved + // through the cross-realm File handling in convertBlobToFile(). + await imageBlockUtils.uploadWithName( + imageBlock.locator( 'data-testid=form-file-upload-input' ), + '1024x768_e2e_test_image_size.jpeg', + 'my-vacation-photo.jpeg' + ); + + const image = imageBlock.getByRole( 'img', { + name: 'This image has an empty alt attribute', + } ); + await expect( image ).toBeVisible(); + + const imageId = await waitForUploadAndGetImageId( page ); + + const media = await requestUtils.rest( { + method: 'GET', + path: `/wp/v2/media/${ imageId }`, + } ); + + // The uploaded filename should be preserved in the source URL. + expect( media.source_url ).toContain( 'my-vacation-photo' ); + } ); + + test( 'should create scaled version with original_image metadata for large images', async ( { page, editor, imageBlockUtils, requestUtils, } ) => { // Skip if cross-origin isolation is not enabled. - // The vips library requires SharedArrayBuffer which needs cross-origin isolation. const isCrossOriginIsolated = await page.evaluate( () => window.crossOriginIsolated ); @@ -67,85 +145,115 @@ test.describe( 'Big image size threshold', () => { await expect( imageBlock ).toBeVisible(); // Upload a large image (3200x2400) that exceeds the default threshold (2560). - await imageBlockUtils.upload( + await imageBlockUtils.uploadWithName( + imageBlock.locator( 'data-testid=form-file-upload-input' ), + '3200x2400_e2e_test_image_responsive_lightbox.jpeg', + 'landscape-photo.jpeg' + ); + + const image = imageBlock.getByRole( 'img', { + name: 'This image has an empty alt attribute', + } ); + await expect( image ).toBeVisible(); + + const imageId = await waitForUploadAndGetImageId( page ); + + const media = await requestUtils.rest( { + method: 'GET', + path: `/wp/v2/media/${ imageId }`, + } ); + + // The scaled version should be set as the main image. + expect( media.source_url ).toContain( '-scaled' ); + + // The original_image metadata should be set to the unscaled filename. + expect( media.media_details.original_image ).toBe( + 'landscape-photo.jpeg' + ); + + // The scaled image should be within the threshold dimensions. + expect( media.media_details.width ).toBeLessThanOrEqual( 2560 ); + expect( media.media_details.height ).toBeLessThanOrEqual( 2560 ); + + // The max dimension should be exactly 2560 (the default threshold). + const maxDimension = Math.max( + media.media_details.width, + media.media_details.height + ); + expect( maxDimension ).toBe( 2560 ); + + // The scaled filename should not have a numeric suffix (e.g. -scaled-1). + // This verifies the regex fix for filter_wp_unique_filename(). + expect( media.source_url ).not.toMatch( /-scaled-\d+/ ); + } ); + + test( 'should generate thumbnails with correct base filename', async ( { + page, + editor, + imageBlockUtils, + requestUtils, + } ) => { + // Skip if cross-origin isolation is not enabled. + const isCrossOriginIsolated = await page.evaluate( + () => window.crossOriginIsolated + ); + // eslint-disable-next-line playwright/no-skipped-test + test.skip( + ! isCrossOriginIsolated, + 'Cross-origin isolation headers not configured on server' + ); + + await editor.insertBlock( { name: 'core/image' } ); + + const imageBlock = editor.canvas.locator( + 'role=document[name="Block: Image"i]' + ); + await expect( imageBlock ).toBeVisible(); + + // Upload a large image with a known filename. + await imageBlockUtils.uploadWithName( imageBlock.locator( 'data-testid=form-file-upload-input' ), - '3200x2400_e2e_test_image_responsive_lightbox.jpeg' + '3200x2400_e2e_test_image_responsive_lightbox.jpeg', + 'my-photo.jpeg' ); - // Wait for the upload to complete. const image = imageBlock.getByRole( 'img', { name: 'This image has an empty alt attribute', } ); await expect( image ).toBeVisible(); - // Wait for the image URL to be updated to the final uploaded URL. - await page.waitForFunction( - () => { - const uploadStore = - window.wp.data.select( 'core/upload-media' ); - if ( ! uploadStore ) { - return true; // Store not available, upload happened server-side. - } - const items = uploadStore.getItems(); - return items.length === 0; - }, - { timeout: 120000 } - ); - - // Get the image ID from the block. - const imageId = await page.evaluate( - () => - window.wp.data.select( 'core/block-editor' ).getSelectedBlock() - ?.attributes?.id - ); - - if ( imageId ) { - // Fetch the attachment details from the REST API. - const media = await requestUtils.rest( { - method: 'GET', - path: `/wp/v2/media/${ imageId }`, - } ); - - // The image should be scaled down (either client-side or server-side). - expect( media.media_details.width ).toBeLessThanOrEqual( 2560 ); - expect( media.media_details.height ).toBeLessThanOrEqual( 2560 ); - - if ( media.source_url.includes( '-scaled' ) ) { - // When client-side scaling adds the -scaled suffix, - // original_image may or may not be set depending on whether - // the server also processes the image. Only check if present. - if ( media.media_details.original_image ) { - expect( media.media_details.original_image ).toBeDefined(); - } - - // Verify thumbnails were generated. - const sizes = media.media_details.sizes; - expect( sizes ).toBeDefined(); - - // Check that at least some standard sizes were created. - // The exact sizes depend on theme/site configuration. - const hasStandardSizes = - sizes.thumbnail || sizes.medium || sizes.large; - expect( hasStandardSizes ).toBeTruthy(); - - // If thumbnail exists, verify it has reasonable dimensions. - // Default thumbnail size is 150x150. - if ( sizes.thumbnail ) { - expect( sizes.thumbnail.width ).toBeLessThanOrEqual( 150 ); - expect( sizes.thumbnail.height ).toBeLessThanOrEqual( 150 ); - } - - // If medium exists, verify dimensions. - // Default medium size is 300x300. - if ( sizes.medium ) { - expect( sizes.medium.width ).toBeLessThanOrEqual( 300 ); - expect( sizes.medium.height ).toBeLessThanOrEqual( 300 ); - } + const imageId = await waitForUploadAndGetImageId( page ); + + const media = await requestUtils.rest( { + method: 'GET', + path: `/wp/v2/media/${ imageId }`, + } ); + + // Verify thumbnails were generated. + const sizes = media.media_details.sizes; + expect( sizes ).toBeDefined(); + + // Check that at least some standard sizes were created. + const hasStandardSizes = sizes.thumbnail || sizes.medium || sizes.large; + expect( hasStandardSizes ).toBeTruthy(); + + // Verify thumbnail filenames use the correct base filename (my-photo), + // not a UUID or wrong name. This validates the attachment.filename fix + // in generateThumbnails(). + const sizeEntries = Object.entries( sizes ); + for ( const [ sizeName, sizeData ] of sizeEntries ) { + if ( sizeName === 'full' ) { + continue; } + // Each thumbnail file should start with "my-photo-". + expect( sizeData.file ).toMatch( /^my-photo-/ ); } + + // Verify the scaled version filename. + expect( media.source_url ).toContain( 'my-photo-scaled' ); } ); - test( 'should not scale images smaller than the threshold', async ( { + test( 'should not scale or set original_image for images below threshold', async ( { page, editor, imageBlockUtils, @@ -169,51 +277,33 @@ test.describe( 'Big image size threshold', () => { await expect( imageBlock ).toBeVisible(); // Upload a small image (1024x768) that is below the default threshold (2560). - await imageBlockUtils.upload( + await imageBlockUtils.uploadWithName( imageBlock.locator( 'data-testid=form-file-upload-input' ), - '1024x768_e2e_test_image_size.jpeg' + '1024x768_e2e_test_image_size.jpeg', + 'small-photo.jpeg' ); - // Wait for the upload to complete. const image = imageBlock.getByRole( 'img', { name: 'This image has an empty alt attribute', } ); await expect( image ).toBeVisible(); - // Wait for the upload queue to be empty. - await page.waitForFunction( - () => { - const uploadStore = - window.wp.data.select( 'core/upload-media' ); - if ( ! uploadStore ) { - return true; - } - const items = uploadStore.getItems(); - return items.length === 0; - }, - { timeout: 120000 } - ); - - // Get the image ID from the block. - const imageId = await page.evaluate( - () => - window.wp.data.select( 'core/block-editor' ).getSelectedBlock() - ?.attributes?.id - ); - - if ( imageId ) { - // Fetch the attachment details from the REST API. - const media = await requestUtils.rest( { - method: 'GET', - path: `/wp/v2/media/${ imageId }`, - } ); - - // The image should NOT be scaled since it's below the threshold. - expect( media.source_url ).not.toContain( '-scaled' ); - // Original dimensions should be preserved. - expect( media.media_details.width ).toBe( 1024 ); - expect( media.media_details.height ).toBe( 768 ); - } + const imageId = await waitForUploadAndGetImageId( page ); + + const media = await requestUtils.rest( { + method: 'GET', + path: `/wp/v2/media/${ imageId }`, + } ); + + // The image should NOT be scaled since it's below the threshold. + expect( media.source_url ).not.toContain( '-scaled' ); + + // original_image should NOT be set for images below the threshold. + expect( media.media_details.original_image ).toBeUndefined(); + + // Original dimensions should be preserved exactly. + expect( media.media_details.width ).toBe( 1024 ); + expect( media.media_details.height ).toBe( 768 ); } ); } ); @@ -245,4 +335,28 @@ class ImageBlockUtils { return fileName; } + + /** + * Uploads a file while preserving or renaming to a specific filename. + * Unlike upload() which renames to a UUID, this keeps the original name + * (or uses a custom rename), enabling tests that verify filename handling. + * + * @param {import('@playwright/test').Locator} inputElement The file input element. + * @param {string} customFile Source file in assets directory. + * @param {string|null} rename Optional filename to use instead of original. + * @return {Promise} The filename used for upload. + */ + async uploadWithName( inputElement, customFile, rename = null ) { + const tmpDirectory = await fs.mkdtemp( + path.join( os.tmpdir(), 'gutenberg-test-image-' ) + ); + const targetName = rename || customFile; + const tmpFileName = path.join( tmpDirectory, targetName ); + const filePath = path.join( this.basePath, customFile ); + await fs.copyFile( filePath, tmpFileName ); + + await inputElement.setInputFiles( tmpFileName ); + + return targetName; + } }