diff --git a/docs/manifest.json b/docs/manifest.json index 7b6fde01c985e2..78e562b5b4557d 100644 --- a/docs/manifest.json +++ b/docs/manifest.json @@ -2105,6 +2105,12 @@ "markdown_source": "../packages/wordcount/README.md", "parent": "packages" }, + { + "title": "@wordpress/worker-threads", + "slug": "packages-worker-threads", + "markdown_source": "../packages/worker-threads/README.md", + "parent": "packages" + }, { "title": "@wordpress/build", "slug": "packages-wp-build", diff --git a/lib/compat/wordpress-7.0/preload.php b/lib/compat/wordpress-7.0/preload.php index 0a046c52376ebd..0c650114cb2a1a 100644 --- a/lib/compat/wordpress-7.0/preload.php +++ b/lib/compat/wordpress-7.0/preload.php @@ -26,3 +26,34 @@ static function ( $path ) { return $paths; } add_filter( 'block_editor_rest_api_preload_paths', 'gutenberg_block_editor_preload_paths_6_9', 10, 2 ); + +/** + * Filters the block editor preload paths to include media processing fields. + * + * The packages/core-data/src/entities.js file requests additional fields + * (image_sizes, image_size_threshold) on the root endpoint that are not + * included in WordPress Core's default preload paths. This filter ensures + * the preloaded URL matches exactly what the JavaScript requests. + * + * @since 20.1.0 + * + * @param array $paths REST API paths to preload. + * @return array Filtered preload paths. + */ +function gutenberg_block_editor_preload_paths_root_fields( $paths ) { + // Complete list of fields expected by packages/core-data/src/entities.js. + // This must match exactly for preloading to work (same fields, same order). + // @see packages/core-data/src/entities.js rootEntitiesConfig.__unstableBase + $root_fields = 'description,gmt_offset,home,image_sizes,image_size_threshold,image_output_formats,jpeg_interlaced,png_interlaced,gif_interlaced,name,site_icon,site_icon_url,site_logo,timezone_string,url,page_for_posts,page_on_front,show_on_front'; + + foreach ( $paths as $key => $path ) { + if ( is_string( $path ) && str_starts_with( $path, '/?_fields=' ) ) { + // Replace with the complete fields list to ensure exact match. + $paths[ $key ] = '/?_fields=' . $root_fields; + break; + } + } + + return $paths; +} +add_filter( 'block_editor_rest_api_preload_paths', 'gutenberg_block_editor_preload_paths_root_fields' ); diff --git a/lib/experimental/media/class-gutenberg-rest-attachments-controller.php b/lib/experimental/media/class-gutenberg-rest-attachments-controller.php index 71bf7b7a958351..547eb773fe1f03 100644 --- a/lib/experimental/media/class-gutenberg-rest-attachments-controller.php +++ b/lib/experimental/media/class-gutenberg-rest-attachments-controller.php @@ -5,6 +5,34 @@ * @package MediaExperiments */ +/** + * Debug logging for client-side media processing. + * Set $debug_enabled to true to enable logging. + * + * @param string $message Log message. + * @param array $data Optional data to include in log. + */ +function gutenberg_media_debug_log( $message, $data = array() ) { + // Set to true to enable debug logging. + $debug_enabled = false; + + if ( ! $debug_enabled ) { + return; + } + + $timestamp = gmdate( 'H:i:s.v' ); + $prefix = "[MEDIA:PHP] $timestamp"; + + if ( ! empty( $data ) ) { + $data_str = wp_json_encode( $data, JSON_PRETTY_PRINT ); + // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log + error_log( "$prefix $message\n └─ Details: $data_str" ); + } else { + // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log + error_log( "$prefix $message" ); + } +} + /** * Class Gutenberg_REST_Attachments_Controller. */ @@ -78,10 +106,31 @@ public function get_endpoint_args_for_item_schema( $method = WP_REST_Server::CRE return $args; } + /** + * Retrieves the attachment's schema, conforming to JSON Schema. + * + * Adds exif_orientation field to the schema. + * + * @return array Item schema data. + */ + public function get_item_schema() { + $schema = parent::get_item_schema(); + + $schema['properties']['exif_orientation'] = array( + 'description' => __( 'EXIF orientation value from the original image. Values 1-8 follow the EXIF specification. A value other than 1 indicates the image needs rotation.', 'gutenberg' ), + 'type' => 'integer', + 'context' => array( 'edit' ), + 'readonly' => true, + ); + + return $schema; + } + /** * Prepares a single attachment output for response. * * Ensures 'missing_image_sizes' is set for PDFs and not just images. + * Adds 'exif_orientation' for images that need client-side rotation. * * @param WP_Post $item Attachment object. * @param WP_REST_Request $request Request object. @@ -92,10 +141,31 @@ public function prepare_item_for_response( $item, $request ): WP_REST_Response { $data = $response->get_data(); - // Handle missing image sizes for PDFs. - $fields = $this->get_fields_for_response( $request ); + // Add EXIF orientation for images. + if ( rest_is_field_included( 'exif_orientation', $fields ) ) { + $mime_type = get_post_mime_type( $item ); + + if ( wp_attachment_is_image( $item ) ) { + $metadata = wp_get_attachment_metadata( $item->ID, true ); + + // Get the EXIF orientation from the image metadata. + // This is stored by wp_read_image_metadata() during upload. + $orientation = 1; // Default: no rotation needed. + if ( + is_array( $metadata ) && + isset( $metadata['image_meta']['orientation'] ) + ) { + $orientation = (int) $metadata['image_meta']['orientation']; + } + + $data['exif_orientation'] = $orientation; + } + } + + // Handle missing image sizes for PDFs. + if ( rest_is_field_included( 'missing_image_sizes', $fields ) && empty( $data['missing_image_sizes'] ) @@ -155,13 +225,31 @@ public function prepare_item_for_response( $item, $request ): WP_REST_Response { * @return WP_REST_Response|WP_Error Response object on success, WP_Error object on failure. */ public function create_item( $request ) { + $files = $request->get_file_params(); + $file_info = isset( $files['file'] ) ? $files['file'] : array(); + + gutenberg_media_debug_log( + 'Creating attachment (upload)', + array( + 'filename' => isset( $file_info['name'] ) ? $file_info['name'] : 'unknown', + 'size' => isset( $file_info['size'] ) ? size_format( $file_info['size'] ) : 'unknown', + 'type' => isset( $file_info['type'] ) ? $file_info['type'] : 'unknown', + 'generate_sub_sizes' => $request['generate_sub_sizes'] ? 'yes' : 'no (client-side)', + 'convert_format' => $request['convert_format'] ? 'yes' : 'no (client-side)', + ) + ); + if ( ! $request['generate_sub_sizes'] ) { + gutenberg_media_debug_log( 'Server-side sub-size generation DISABLED (client will generate)' ); add_filter( 'intermediate_image_sizes_advanced', '__return_empty_array', 100 ); add_filter( 'fallback_intermediate_image_sizes', '__return_empty_array', 100 ); - + // 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 ); } if ( ! $request['convert_format'] ) { + gutenberg_media_debug_log( 'Server-side format conversion DISABLED (client will convert)' ); add_filter( 'image_editor_output_format', '__return_empty_array', 100 ); } @@ -169,8 +257,30 @@ 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( 'image_editor_output_format', '__return_empty_array', 100 ); + if ( is_wp_error( $response ) ) { + gutenberg_media_debug_log( + 'Attachment creation FAILED', + array( + 'error_code' => $response->get_error_code(), + 'error_message' => $response->get_error_message(), + ) + ); + } else { + $data = $response->get_data(); + gutenberg_media_debug_log( + 'Attachment created successfully', + array( + 'attachment_id' => isset( $data['id'] ) ? $data['id'] : 'unknown', + 'url' => isset( $data['source_url'] ) ? $data['source_url'] : 'unknown', + 'missing_image_sizes' => isset( $data['missing_image_sizes'] ) ? $data['missing_image_sizes'] : array(), + 'exif_orientation' => isset( $data['exif_orientation'] ) ? $data['exif_orientation'] : 1, + ) + ); + } + return $response; } @@ -243,10 +353,32 @@ private function filter_wp_unique_filename( $filename, $ext, $dir, $unique_filen */ public function sideload_item( WP_REST_Request $request ) { $attachment_id = $request['id']; + $image_size = $request['image_size']; + + $files = $request->get_file_params(); + $file_info = isset( $files['file'] ) ? $files['file'] : array(); + + gutenberg_media_debug_log( + 'Sideloading sub-size image', + array( + 'attachment_id' => $attachment_id, + 'image_size' => $image_size, + 'filename' => isset( $file_info['name'] ) ? $file_info['name'] : 'unknown', + 'size' => isset( $file_info['size'] ) ? size_format( $file_info['size'] ) : 'unknown', + 'type' => isset( $file_info['type'] ) ? $file_info['type'] : 'unknown', + ) + ); $post = $this->get_post( $attachment_id ); if ( is_wp_error( $post ) ) { + gutenberg_media_debug_log( + 'Sideload FAILED - invalid attachment', + array( + 'attachment_id' => $attachment_id, + 'error' => $post->get_error_message(), + ) + ); return $post; } @@ -315,6 +447,15 @@ public function sideload_item( WP_REST_Request $request ) { remove_filter( 'image_editor_output_format', '__return_empty_array', 100 ); if ( is_wp_error( $file ) ) { + gutenberg_media_debug_log( + 'Sideload FAILED - file upload error', + array( + 'attachment_id' => $attachment_id, + 'image_size' => $image_size, + 'error_code' => $file->get_error_code(), + 'error_message' => $file->get_error_message(), + ) + ); return $file; } @@ -347,6 +488,16 @@ public function sideload_item( WP_REST_Request $request ) { wp_update_attachment_metadata( $attachment_id, $metadata ); + gutenberg_media_debug_log( + 'Sideload completed successfully', + array( + 'attachment_id' => $attachment_id, + 'image_size' => $image_size, + 'file_path' => wp_basename( $path ), + 'dimensions' => isset( $size ) && $size ? $size[0] . 'x' . $size[1] : 'unknown', + ) + ); + $response_request = new WP_REST_Request( WP_REST_Server::READABLE, rest_get_route_for_post( $attachment_id ) diff --git a/lib/experimental/media/load.php b/lib/experimental/media/load.php index 5e7b00173ca616..f99383ed6d77f2 100644 --- a/lib/experimental/media/load.php +++ b/lib/experimental/media/load.php @@ -5,6 +5,34 @@ * @package gutenberg */ +/** + * Debug logging for client-side media processing (load.php). + * Set $debug_enabled to true to enable logging. + * + * @param string $message Log message. + * @param array $data Optional data to include in log. + */ +function gutenberg_media_load_debug_log( $message, $data = array() ) { + // Set to true to enable debug logging. + $debug_enabled = false; + + if ( ! $debug_enabled ) { + return; + } + + $timestamp = gmdate( 'H:i:s.v' ); + $prefix = "[MEDIA:PHP:LOAD] $timestamp"; + + if ( ! empty( $data ) ) { + $data_str = wp_json_encode( $data, JSON_PRETTY_PRINT ); + // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log + error_log( "$prefix $message\n └─ Details: $data_str" ); + } else { + // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log + error_log( "$prefix $message" ); + } +} + /** * Returns a list of all available image sizes. * @@ -41,6 +69,11 @@ function gutenberg_get_default_image_output_formats() { $output_formats = array(); foreach ( $input_formats as $mime_type ) { + /* + * The filename parameter is empty because we're querying default format + * mappings, not processing a specific file. The filter returns mappings + * for each input type based on the mime type. + */ /** This filter is documented in wp-includes/media.php */ $output_formats = apply_filters( 'image_editor_output_format', // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound @@ -78,6 +111,18 @@ function gutenberg_media_processing_filter_rest_index( WP_REST_Response $respons $response->data['jpeg_interlaced'] = $jpeg_interlaced; $response->data['png_interlaced'] = $png_interlaced; $response->data['gif_interlaced'] = $gif_interlaced; + + gutenberg_media_load_debug_log( + 'REST API settings provided to client', + array( + 'image_size_threshold' => $image_size_threshold, + 'image_sizes_count' => count( $response->data['image_sizes'] ), + 'image_sizes' => array_keys( $response->data['image_sizes'] ), + 'jpeg_interlaced' => $jpeg_interlaced, + 'png_interlaced' => $png_interlaced, + 'gif_interlaced' => $gif_interlaced, + ) + ); } return $response; @@ -255,6 +300,15 @@ function gutenberg_start_cross_origin_isolation_output_buffer(): void { $coep = $is_safari ? 'require-corp' : 'credentialless'; + gutenberg_media_load_debug_log( + 'Setting up cross-origin isolation for WebAssembly/SharedArrayBuffer', + array( + 'is_safari' => $is_safari ? 'yes' : 'no', + 'COOP' => 'same-origin', + 'COEP' => $coep, + ) + ); + ob_start( function ( string $output ) use ( $coep ): string { header( 'Cross-Origin-Opener-Policy: same-origin' ); diff --git a/package-lock.json b/package-lock.json index 605fb38bf11d8c..1c4010a776c134 100644 --- a/package-lock.json +++ b/package-lock.json @@ -35,6 +35,7 @@ "@types/uuid": "8.3.1", "@vitejs/plugin-react": "5.1.2", "@wordpress/build": "file:./packages/wp-build", + "@wordpress/vips": "1.0.0-prerelease", "ajv": "8.17.1", "babel-jest": "29.7.0", "babel-loader": "9.2.1", @@ -26352,12 +26353,6 @@ "node": ">=0.10.0" } }, - "node_modules/clean-git-ref": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/clean-git-ref/-/clean-git-ref-2.0.1.tgz", - "integrity": "sha512-bLSptAy2P0s6hU4PzuIMKmMJJSE6gLXGH1cntDu7bWJUksvuM+7ReOK61mozULErYvP6a15rnYl0zFDef+pyPw==", - "license": "Apache-2.0" - }, "node_modules/clean-stack": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-2.2.0.tgz", @@ -54836,15 +54831,6 @@ "integrity": "sha512-zksaLKM2fVlnB5jQQDqKXXwYHLQUVH9es+5TOOHwGOVJOCeRBCiPjwSg+3tN2AdTCzjgli4jijCH290kXb/zWQ==", "license": "Apache-2.0" }, - "node_modules/wasm-vips": { - "version": "0.0.10", - "resolved": "https://registry.npmjs.org/wasm-vips/-/wasm-vips-0.0.10.tgz", - "integrity": "sha512-ZDIRjxTm03iRRXM9WwvVh8MH+mKHUBedJTC/MYd/cVGZxShnYcEd0BB7gSGDpxgkzcPSYUnN1HQJipDBhxVHTg==", - "license": "MIT", - "engines": { - "node": ">=16.4.0" - } - }, "node_modules/watchpack": { "version": "1.7.5", "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-1.7.5.tgz", @@ -59647,6 +59633,7 @@ "@wordpress/reusable-blocks": "file:../reusable-blocks", "@wordpress/rich-text": "file:../rich-text", "@wordpress/server-side-render": "file:../server-side-render", + "@wordpress/upload-media": "file:../upload-media", "@wordpress/url": "file:../url", "@wordpress/warning": "file:../warning", "@wordpress/wordcount": "file:../wordcount", @@ -62176,6 +62163,7 @@ "@wordpress/preferences": "file:../preferences", "@wordpress/private-apis": "file:../private-apis", "@wordpress/url": "file:../url", + "@wordpress/vips": "1.0.0-prerelease", "uuid": "^9.0.1" }, "engines": { @@ -62241,13 +62229,22 @@ "license": "GPL-2.0-or-later", "dependencies": { "@wordpress/worker-threads": "file:../worker-threads", - "wasm-vips": "^0.0.10" + "wasm-vips": "^0.0.16" }, "engines": { "node": ">=18.12.0", "npm": ">=8.19.2" } }, + "packages/vips/node_modules/wasm-vips": { + "version": "0.0.16", + "resolved": "https://registry.npmjs.org/wasm-vips/-/wasm-vips-0.0.16.tgz", + "integrity": "sha512-4/bEq8noAFt7DX3VT+Vt5AgNtnnOLwvmrDbduWfiv9AV+VYkbUU4f9Dam9e6khRqPinyClFHCqiwATTTJEiGwA==", + "license": "MIT", + "engines": { + "node": ">=16.4.0" + } + }, "packages/warning": { "name": "@wordpress/warning", "version": "3.39.0", diff --git a/package.json b/package.json index dc951832296bc0..daffe9ff02646b 100644 --- a/package.json +++ b/package.json @@ -57,6 +57,7 @@ "@types/uuid": "8.3.1", "@vitejs/plugin-react": "5.1.2", "@wordpress/build": "file:./packages/wp-build", + "@wordpress/vips": "1.0.0-prerelease", "ajv": "8.17.1", "babel-jest": "29.7.0", "babel-loader": "9.2.1", diff --git a/packages/block-editor/src/components/provider/index.js b/packages/block-editor/src/components/provider/index.js index 07f7bc644bd70f..874b1203065d85 100644 --- a/packages/block-editor/src/components/provider/index.js +++ b/packages/block-editor/src/components/provider/index.js @@ -19,6 +19,7 @@ import { BlockRefsProvider } from './block-refs-provider'; import { unlock } from '../../lock-unlock'; import KeyboardShortcuts from '../keyboard-shortcuts'; import useMediaUploadSettings from './use-media-upload-settings'; +import useUploadSaveLock from './use-upload-save-lock'; /** @typedef {import('@wordpress/data').WPDataRegistry} WPDataRegistry */ @@ -51,7 +52,7 @@ function mediaUpload( } ) { void registry.dispatch( uploadStore ).addItems( { - files: filesList, + files: Array.from( filesList ), onChange: onFileChange, onSuccess, onBatchSuccess, @@ -121,7 +122,7 @@ export const ExperimentalBlockEditorProvider = withRegistryProvider( settings={ mediaUploadSettings } useSubRegistry={ false } > - { children } + { children } ); } @@ -130,6 +131,18 @@ export const ExperimentalBlockEditorProvider = withRegistryProvider( } ); +/** + * Wrapper component that manages post save locks based on upload state. + * Must be rendered inside MediaUploadProvider to access the upload-media store. + * + * @param {Object} props Component props. + * @param {Object} props.children Children elements. + */ +function UploadSaveLockWrapper( { children } ) { + useUploadSaveLock(); + return children; +} + export const BlockEditorProvider = ( props ) => { return ( diff --git a/packages/block-editor/src/components/provider/use-media-upload-settings.js b/packages/block-editor/src/components/provider/use-media-upload-settings.js index 40390a77e746ef..93cc7ab632308e 100644 --- a/packages/block-editor/src/components/provider/use-media-upload-settings.js +++ b/packages/block-editor/src/components/provider/use-media-upload-settings.js @@ -17,6 +17,12 @@ function useMediaUploadSettings( settings = {} ) { mediaSideload: settings.mediaSideload, maxUploadFileSize: settings.maxUploadFileSize, allowedMimeTypes: settings.allowedMimeTypes, + allImageSizes: settings.allImageSizes, + bigImageSizeThreshold: settings.bigImageSizeThreshold, + imageOutputFormats: settings.imageOutputFormats, + jpegInterlaced: settings.jpegInterlaced, + pngInterlaced: settings.pngInterlaced, + gifInterlaced: settings.gifInterlaced, } ), [ settings ] ); diff --git a/packages/block-editor/src/components/provider/use-upload-save-lock.js b/packages/block-editor/src/components/provider/use-upload-save-lock.js new file mode 100644 index 00000000000000..20d60dcc260e82 --- /dev/null +++ b/packages/block-editor/src/components/provider/use-upload-save-lock.js @@ -0,0 +1,49 @@ +/** + * WordPress dependencies + */ +import { useSelect, useRegistry } from '@wordpress/data'; +import { useEffect } from '@wordpress/element'; +import { store as uploadStore } from '@wordpress/upload-media'; + +const LOCK_NAME = 'upload-in-progress'; + +/** + * A hook that locks post saving and autosaving while media uploads are in progress. + * This prevents users from publishing or saving while files are still uploading. + * + * Note: This hook dynamically accesses the editor store to avoid creating a + * circular dependency between block-editor and editor packages. The lock + * functionality only activates when the editor store is available. + */ +export default function useUploadSaveLock() { + const registry = useRegistry(); + + const { isUploading, hasEditorStore } = useSelect( ( select ) => { + // Check if the editor store is registered to avoid errors + // in contexts where it's not available (e.g., standalone block editor). + const stores = registry.stores; + const editorStoreExists = !! stores[ 'core/editor' ]; + + return { + isUploading: select( uploadStore ).isUploading(), + hasEditorStore: editorStoreExists, + }; + }, [] ); + + useEffect( () => { + if ( ! hasEditorStore ) { + return; + } + + const { dispatch } = registry; + const editorDispatch = dispatch( 'core/editor' ); + + if ( isUploading ) { + editorDispatch.lockPostSaving( LOCK_NAME ); + editorDispatch.lockPostAutosaving( LOCK_NAME ); + } else { + editorDispatch.unlockPostSaving( LOCK_NAME ); + editorDispatch.unlockPostAutosaving( LOCK_NAME ); + } + }, [ isUploading, hasEditorStore, registry ] ); +} diff --git a/packages/core-data/src/entities.js b/packages/core-data/src/entities.js index f81bbbfbb3995f..f0de2b51541df9 100644 --- a/packages/core-data/src/entities.js +++ b/packages/core-data/src/entities.js @@ -42,11 +42,19 @@ export const rootEntitiesConfig = [ baseURL: '/', baseURLParams: { // Please also change the preload path when changing this. - // @see lib/compat/wordpress-6.8/preload.php + // @see lib/compat/wordpress-7.0/preload.php + // @see packages/wp-build/templates/page.php.template + // @see packages/wp-build/templates/page-wp-admin.php.template _fields: [ 'description', 'gmt_offset', 'home', + 'image_sizes', + 'image_size_threshold', + 'image_output_formats', + 'jpeg_interlaced', + 'png_interlaced', + 'gif_interlaced', 'name', 'site_icon', 'site_icon_url', diff --git a/packages/editor/package.json b/packages/editor/package.json index fe51cef6d9a5a1..66091f455b10ba 100644 --- a/packages/editor/package.json +++ b/packages/editor/package.json @@ -98,6 +98,7 @@ "@wordpress/reusable-blocks": "file:../reusable-blocks", "@wordpress/rich-text": "file:../rich-text", "@wordpress/server-side-render": "file:../server-side-render", + "@wordpress/upload-media": "file:../upload-media", "@wordpress/url": "file:../url", "@wordpress/warning": "file:../warning", "@wordpress/wordcount": "file:../wordcount", diff --git a/packages/editor/src/components/provider/index.js b/packages/editor/src/components/provider/index.js index c9e1a4a071ca4e..2eec1c118b56a9 100644 --- a/packages/editor/src/components/provider/index.js +++ b/packages/editor/src/components/provider/index.js @@ -30,6 +30,7 @@ import DisableNonPageContentBlocks from './disable-non-page-content-blocks'; import NavigationBlockEditingMode from './navigation-block-editing-mode'; import { useHideBlocksFromInserter } from './use-hide-blocks-from-inserter'; import useCommands from '../commands'; +import useUploadSaveLock from './use-upload-save-lock'; import BlockRemovalWarnings from '../block-removal-warnings'; import StartPageOptions from '../start-page-options'; import KeyboardShortcutHelpModal from '../keyboard-shortcut-help-modal'; @@ -352,6 +353,9 @@ export const ExperimentalEditorProvider = withRegistryProvider( // Register the editor commands. useCommands(); + // Lock post saving when media uploads are in progress (experimental feature). + useUploadSaveLock(); + if ( ! isReady || ! mode ) { return null; } diff --git a/packages/editor/src/components/provider/use-block-editor-settings.js b/packages/editor/src/components/provider/use-block-editor-settings.js index 60cad35baa1484..16d32e9c5363c3 100644 --- a/packages/editor/src/components/provider/use-block-editor-settings.js +++ b/packages/editor/src/components/provider/use-block-editor-settings.js @@ -45,6 +45,7 @@ const BLOCK_EDITOR_SETTINGS = [ '__experimentalDiscussionSettings', '__experimentalFeatures', '__experimentalGlobalStylesBaseStyles', + 'allImageSizes', 'alignWide', 'blockInspectorTabs', 'maxUploadFileSize', @@ -115,6 +116,12 @@ const { function useBlockEditorSettings( settings, postType, postId, renderingMode ) { const isLargeViewport = useViewportMatch( 'medium' ); const { + allImageSizes, + bigImageSizeThreshold, + imageOutputFormats, + jpegInterlaced, + pngInterlaced, + gifInterlaced, allowRightClickOverrides, blockTypes, focusMode, @@ -152,6 +159,9 @@ function useBlockEditorSettings( settings, postType, postId, renderingMode ) { ? getEntityRecord( 'root', 'site' ) : undefined; + // Fetch image sizes from REST API index for client-side media processing. + const baseData = getEntityRecord( 'root', '__unstableBase' ); + function getSectionRootBlock() { if ( renderingMode === 'template-locked' ) { return getBlocksByName( 'core/post-content' )?.[ 0 ] ?? ''; @@ -166,6 +176,12 @@ function useBlockEditorSettings( settings, postType, postId, renderingMode ) { } return { + allImageSizes: baseData?.image_sizes, + bigImageSizeThreshold: baseData?.image_size_threshold, + imageOutputFormats: baseData?.image_output_formats, + jpegInterlaced: baseData?.jpeg_interlaced, + pngInterlaced: baseData?.png_interlaced, + gifInterlaced: baseData?.gif_interlaced, allowRightClickOverrides: get( 'core', 'allowRightClickOverrides' @@ -318,6 +334,12 @@ function useBlockEditorSettings( settings, postType, postId, renderingMode ) { ), [ globalStylesDataKey ]: globalStylesData, [ globalStylesLinksDataKey ]: globalStylesLinksData, + allImageSizes, + bigImageSizeThreshold, + imageOutputFormats, + jpegInterlaced, + pngInterlaced, + gifInterlaced, allowedBlockTypes, allowRightClickOverrides, focusMode: focusMode && ! forceDisableFocusMode, @@ -420,6 +442,12 @@ function useBlockEditorSettings( settings, postType, postId, renderingMode ) { editMediaEntity, wrappedOnNavigateToEntityRecord, deviceType, + allImageSizes, + bigImageSizeThreshold, + imageOutputFormats, + jpegInterlaced, + pngInterlaced, + gifInterlaced, ] ); } diff --git a/packages/editor/src/components/provider/use-upload-save-lock.js b/packages/editor/src/components/provider/use-upload-save-lock.js new file mode 100644 index 00000000000000..c4acc9cc315dfc --- /dev/null +++ b/packages/editor/src/components/provider/use-upload-save-lock.js @@ -0,0 +1,66 @@ +/** + * WordPress dependencies + */ +import { useSelect, useDispatch } from '@wordpress/data'; +import { useEffect } from '@wordpress/element'; +import { store as uploadStore } from '@wordpress/upload-media'; + +/** + * Internal dependencies + */ +import { store as editorStore } from '../../store'; + +const LOCK_NAME = 'upload-in-progress'; + +/** + * A hook that locks post saving and autosaving while media uploads are in progress. + * This prevents users from publishing or saving while files are still uploading. + * + * Only active when the experimental media processing feature is enabled. + */ +export default function useUploadSaveLock() { + const isExperimentEnabled = window.__experimentalMediaProcessing; + + const isUploading = useSelect( + ( select ) => { + if ( ! isExperimentEnabled ) { + return false; + } + return select( uploadStore ).isUploading(); + }, + [ isExperimentEnabled ] + ); + + const { + lockPostSaving, + unlockPostSaving, + lockPostAutosaving, + unlockPostAutosaving, + } = useDispatch( editorStore ); + + useEffect( () => { + if ( ! isExperimentEnabled ) { + return; + } + + if ( isUploading ) { + lockPostSaving( LOCK_NAME ); + lockPostAutosaving( LOCK_NAME ); + } else { + unlockPostSaving( LOCK_NAME ); + unlockPostAutosaving( LOCK_NAME ); + } + + return () => { + unlockPostSaving( LOCK_NAME ); + unlockPostAutosaving( LOCK_NAME ); + }; + }, [ + isExperimentEnabled, + isUploading, + lockPostSaving, + unlockPostSaving, + lockPostAutosaving, + unlockPostAutosaving, + ] ); +} diff --git a/packages/editor/src/utils/media-upload/index.js b/packages/editor/src/utils/media-upload/index.js index 179d68c0ea4440..967adcced834c3 100644 --- a/packages/editor/src/utils/media-upload/index.js +++ b/packages/editor/src/utils/media-upload/index.js @@ -62,6 +62,9 @@ export default function mediaUpload( { ? currentPost.id : currentPost?.wp_id; const setSaveLock = () => { + if ( window.__experimentalMediaProcessing ) { + return; // Skip - handled by useUploadSaveLock in editor provider + } lockPostSaving( lockKey ); lockPostAutosaving( lockKey ); imageIsUploading = true; @@ -69,6 +72,9 @@ export default function mediaUpload( { const postData = currentPostId ? { post: currentPostId } : {}; const clearSaveLock = () => { + if ( window.__experimentalMediaProcessing ) { + return; // Skip - handled by useUploadSaveLock in editor provider + } unlockPostSaving( lockKey ); unlockPostAutosaving( lockKey ); imageIsUploading = false; diff --git a/packages/editor/tsconfig.json b/packages/editor/tsconfig.json index c4c02a2d28a93a..30649dce563de6 100644 --- a/packages/editor/tsconfig.json +++ b/packages/editor/tsconfig.json @@ -35,6 +35,7 @@ { "path": "../private-apis" }, { "path": "../rich-text" }, { "path": "../url" }, + { "path": "../upload-media" }, { "path": "../warning" }, { "path": "../wordcount" } ] diff --git a/packages/scripts/config/webpack.config.js b/packages/scripts/config/webpack.config.js index 5674c78f1f88eb..795f86abad1cf2 100644 --- a/packages/scripts/config/webpack.config.js +++ b/packages/scripts/config/webpack.config.js @@ -1,17 +1,17 @@ /** * External dependencies */ +const { exec } = require( 'child_process' ); +const { realpathSync } = require( 'fs' ); +const { basename, dirname, relative, resolve, sep } = require( 'path' ); const { BundleAnalyzerPlugin } = require( 'webpack-bundle-analyzer' ); const CopyWebpackPlugin = require( 'copy-webpack-plugin' ); const webpack = require( 'webpack' ); const browserslist = require( 'browserslist' ); const MiniCSSExtractPlugin = require( 'mini-css-extract-plugin' ); -const { basename, dirname, relative, resolve, sep } = require( 'path' ); const ReactRefreshWebpackPlugin = require( '@pmmmwh/react-refresh-webpack-plugin' ); const TerserPlugin = require( 'terser-webpack-plugin' ); -const { realpathSync } = require( 'fs' ); const { sync: glob } = require( 'fast-glob' ); -const { exec } = require( 'child_process' ); /** * WordPress dependencies diff --git a/packages/upload-media/package.json b/packages/upload-media/package.json index 331a10d67fc91d..4630779c2398df 100644 --- a/packages/upload-media/package.json +++ b/packages/upload-media/package.json @@ -50,6 +50,7 @@ "@wordpress/preferences": "file:../preferences", "@wordpress/private-apis": "file:../private-apis", "@wordpress/url": "file:../url", + "@wordpress/vips": "1.0.0-prerelease", "uuid": "^9.0.1" }, "peerDependencies": { diff --git a/packages/upload-media/src/store/actions.ts b/packages/upload-media/src/store/actions.ts index 3df010aaac4b83..6516dec1f0aa75 100644 --- a/packages/upload-media/src/store/actions.ts +++ b/packages/upload-media/src/store/actions.ts @@ -31,9 +31,16 @@ import type { removeItem, revokeBlobUrls, } from './private-actions'; +import { vipsCancelOperations } from './utils'; import { validateMimeType } from '../validate-mime-type'; import { validateMimeTypeForUser } from '../validate-mime-type-for-user'; import { validateFileSize } from '../validate-file-size'; +import { + logInfo, + logCancel, + logError, + logBatchComplete, +} from './utils/debug-logger'; type ActionCreators = { addItem: typeof addItem; @@ -94,6 +101,14 @@ export function addItems( { }: AddItemsArgs ) { return async ( { select, dispatch }: ThunkArgs ) => { const batchId = uuidv4(); + + logInfo( `Adding ${ files.length } file(s) to upload queue`, { + batchId, + fileCount: files.length, + fileNames: files.map( ( f ) => f.name ), + allowedTypes: allowedTypes || 'all', + } ); + for ( const file of files ) { /* Check if the caller (e.g. a block) supports this mime type. @@ -157,15 +172,18 @@ export function cancelItem( id: QueueItemId, error: Error, silent = false ) { return; } + logCancel( id, item.file.name, error ); + item.abortController?.abort(); + // Cancel any ongoing vips operations for this item. + await vipsCancelOperations( id ); + if ( ! silent ) { const { onError } = item; onError?.( error ?? new Error( 'Upload cancelled' ) ); if ( ! onError && error ) { - // TODO: Find better way to surface errors with sideloads etc. - // eslint-disable-next-line no-console -- Deliberately log errors here. - console.error( 'Upload cancelled', error ); + logError( 'cancelItem', error, id ); } } @@ -179,6 +197,7 @@ export function cancelItem( id: QueueItemId, error: Error, silent = false ) { // All items of this batch were cancelled or finished. if ( item.batchId && select.isBatchUploaded( item.batchId ) ) { + logBatchComplete( item.batchId ); item.onBatchSuccess?.(); } }; @@ -202,6 +221,11 @@ export function retryItem( id: QueueItemId ) { return; } + logInfo( `Retrying failed item: ${ item.file.name }`, { + itemId: id, + previousError: item.error.message, + } ); + dispatch< RetryItemAction >( { type: Type.RetryItem, id, diff --git a/packages/upload-media/src/store/index.ts b/packages/upload-media/src/store/index.ts index c74f59ea7a7cf3..dbf2aa40212273 100644 --- a/packages/upload-media/src/store/index.ts +++ b/packages/upload-media/src/store/index.ts @@ -1,7 +1,7 @@ /** * WordPress dependencies */ -import { createReduxStore, register } from '@wordpress/data'; +import { createReduxStore, register, select } from '@wordpress/data'; /** * Internal dependencies @@ -36,7 +36,11 @@ export const store = createReduxStore( STORE_NAME, { actions, } ); -register( store ); +// The upload-media package is bundled into multiple packages (block-editor, editor). +// Guard against duplicate registration when both bundles are loaded on the same page. +if ( ! select( store ) ) { + register( store ); +} // @ts-ignore unlock( store ).registerPrivateActions( privateActions ); // @ts-ignore diff --git a/packages/upload-media/src/store/private-actions.ts b/packages/upload-media/src/store/private-actions.ts index 962574a1c0f03d..531ddbb88d820a 100644 --- a/packages/upload-media/src/store/private-actions.ts +++ b/packages/upload-media/src/store/private-actions.ts @@ -14,19 +14,53 @@ type WPDataRegistry = ReturnType< typeof createRegistry >; /** * Internal dependencies */ -import { cloneFile, convertBlobToFile } from '../utils'; +import { cloneFile, convertBlobToFile, renameFile } from '../utils'; import { StubFile } from '../stub-file'; +import { UploadError } from '../upload-error'; +import { + vipsResizeImage, + vipsRotateImage, + vipsConvertImageFormat, +} from './utils'; +import { + logQueueAdd, + logSideloadAdd, + logProcessStart, + logOperationStart, + logOperationComplete, + logResizeCrop, + logResizeComplete, + logRotation, + logRotationComplete, + logTranscode, + logTranscodeComplete, + logUploadStart, + logUploadComplete, + logSideloadStart, + logSideloadComplete, + logThumbnailGenerationStart, + logThumbnailCreate, + logQueueRemove, + logError, + logItemPause, + logItemResume, + logConcurrencyLimit, + logBatchComplete, + createTimer, +} from './utils/debug-logger'; import type { AddAction, AdditionalData, AddOperationsAction, BatchId, CacheBlobUrlAction, + ImageFormat, OnBatchSuccessHandler, OnChangeHandler, OnErrorHandler, OnSuccessHandler, Operation, + OperationArgs, OperationFinishAction, OperationStartAction, PauseItemAction, @@ -36,6 +70,7 @@ import type { ResumeItemAction, ResumeQueueAction, RevokeBlobUrlsAction, + SideloadAdditionalData, Settings, State, UpdateProgressAction, @@ -47,13 +82,19 @@ import type { cancelItem } from './actions'; type ActionCreators = { cancelItem: typeof cancelItem; addItem: typeof addItem; + addSideloadItem: typeof addSideloadItem; removeItem: typeof removeItem; pauseItem: typeof pauseItem; - resumeItem: typeof resumeItem; + resumeItemByPostId: typeof resumeItemByPostId; prepareItem: typeof prepareItem; processItem: typeof processItem; finishOperation: typeof finishOperation; uploadItem: typeof uploadItem; + sideloadItem: typeof sideloadItem; + resizeCropItem: typeof resizeCropItem; + rotateItem: typeof rotateItem; + transcodeImageItem: typeof transcodeImageItem; + generateThumbnails: typeof generateThumbnails; updateItemProgress: typeof updateItemProgress; revokeBlobUrls: typeof revokeBlobUrls; < T = Record< string, unknown > >( args: T ): void; @@ -74,6 +115,32 @@ type ThunkArgs = { registry: WPDataRegistry; }; +/** + * Determines if an upload should be paused to avoid race conditions. + * + * When sideloading thumbnails, we need to pause uploads if another + * upload to the same post is already in progress. + * + * @param item Queue item to check. + * @param operation Current operation type. + * @param select Store selectors. + * @return Whether the upload should be paused. + */ +function shouldPauseForSideload( + item: QueueItem, + operation: OperationType | undefined, + select: Selectors +): boolean { + if ( + operation !== OperationType.Upload || + ! item.parentId || + ! item.additionalData.post + ) { + return false; + } + return select.isUploadingToPost( item.additionalData.post as number ); +} + interface AddItemArgs { // It should always be a File, but some consumers might still pass Blobs only. file: File | Blob; @@ -125,6 +192,8 @@ export function addItem( { // See https://github.com/WordPress/gutenberg/pull/65693 for an example. const file = convertBlobToFile( fileOrBlob ); + logQueueAdd( itemId, file.name, file.size, file.type, batchId ); + let blobUrl; // StubFile could be coming from addItemFromUrl(). @@ -169,6 +238,68 @@ export function addItem( { }; } +interface AddSideloadItemArgs { + file: File; + onChange?: OnChangeHandler; + additionalData?: AdditionalData; + operations?: Operation[]; + batchId?: BatchId; + parentId?: QueueItemId; +} + +/** + * Adds a new item to the upload queue for sideloading. + * + * This is typically a client-side generated thumbnail. + * + * @param $0 + * @param $0.file File + * @param [$0.batchId] Batch ID. + * @param [$0.parentId] Parent ID. + * @param [$0.onChange] Function called each time a file or a temporary representation of the file is available. + * @param [$0.additionalData] Additional data to include in the request. + * @param [$0.operations] List of operations to perform. Defaults to automatically determined list, based on the file. + */ +export function addSideloadItem( { + file, + onChange, + additionalData, + operations, + batchId, + parentId, +}: AddSideloadItemArgs ) { + return ( { dispatch }: ThunkArgs ) => { + const itemId = uuidv4(); + + const imageSize = + ( additionalData as SideloadAdditionalData )?.image_size || + 'unknown'; + logSideloadAdd( itemId, file.name, parentId || 'none', imageSize ); + + dispatch< AddAction >( { + type: Type.Add, + item: { + id: itemId, + batchId, + status: ItemStatus.Processing, + sourceFile: cloneFile( file ), + file, + onChange, + additionalData: { + ...additionalData, + }, + parentId, + operations: Array.isArray( operations ) + ? operations + : [ OperationType.Prepare ], + abortController: new AbortController(), + }, + } ); + + dispatch.processItem( itemId ); + }; +} + /** * Processes a single item in the queue. * @@ -182,14 +313,42 @@ export function processItem( id: QueueItemId ) { return; } - const item = select.getItem( id ) as QueueItem; + const item = select.getItem( id ); + if ( ! item ) { + return; + } - const { attachment, onChange, onSuccess, onBatchSuccess, batchId } = - item; + logProcessStart( id, item.file.name ); + + const { + attachment, + onChange, + onSuccess, + onBatchSuccess, + batchId, + parentId, + } = item; const operation = Array.isArray( item.operations?.[ 0 ] ) ? item.operations[ 0 ][ 0 ] : item.operations?.[ 0 ]; + const operationArgs = Array.isArray( item.operations?.[ 0 ] ) + ? item.operations[ 0 ][ 1 ] + : undefined; + + // If we're sideloading a thumbnail, pause upload to avoid race conditions. + // It will be resumed after the previous upload finishes. + if ( shouldPauseForSideload( item, operation, select ) ) { + logItemPause( + id, + 'Waiting for previous upload to same post to complete' + ); + dispatch< PauseItemAction >( { + type: Type.PauseItem, + id, + } ); + return; + } /* * If the next operation is an upload, check concurrency limit. @@ -200,6 +359,11 @@ export function processItem( id: QueueItemId ) { const settings = select.getSettings(); const activeCount = select.getActiveUploadCount(); if ( activeCount >= settings.maxConcurrentUploads ) { + logConcurrencyLimit( + id, + activeCount, + settings.maxConcurrentUploads + ); return; } } @@ -215,15 +379,43 @@ export function processItem( id: QueueItemId ) { */ if ( ! operation ) { - if ( attachment ) { - onSuccess?.( [ attachment ] ); + if ( + parentId || + ( ! parentId && ! select.isUploadingByParentId( id ) ) + ) { + if ( attachment ) { + onSuccess?.( [ attachment ] ); + } + + dispatch.removeItem( id ); + dispatch.revokeBlobUrls( id ); + + if ( batchId && select.isBatchUploaded( batchId ) ) { + logBatchComplete( batchId ); + onBatchSuccess?.(); + } } - // dispatch.removeItem( id ); - dispatch.revokeBlobUrls( id ); + // All other side-loaded items have been removed, so remove the parent too. + if ( parentId && batchId && select.isBatchUploaded( batchId ) ) { + const parentItem = select.getItem( parentId ) as QueueItem; + if ( ! parentItem ) { + return; + } - if ( batchId && select.isBatchUploaded( batchId ) ) { - onBatchSuccess?.(); + if ( attachment ) { + parentItem.onSuccess?.( [ attachment ] ); + } + + dispatch.removeItem( parentId ); + dispatch.revokeBlobUrls( parentId ); + + if ( + parentItem.batchId && + select.isBatchUploaded( parentItem.batchId ) + ) { + parentItem.onBatchSuccess?.(); + } } /* @@ -234,24 +426,50 @@ export function processItem( id: QueueItemId ) { return; } - if ( ! operation ) { - // This shouldn't really happen. - return; - } - dispatch< OperationStartAction >( { type: Type.OperationStart, id, operation, } ); + logOperationStart( id, operation, item.file.name ); + switch ( operation ) { case OperationType.Prepare: dispatch.prepareItem( item.id ); break; + case OperationType.ResizeCrop: + dispatch.resizeCropItem( + item.id, + operationArgs as OperationArgs[ OperationType.ResizeCrop ] + ); + break; + + case OperationType.Rotate: + dispatch.rotateItem( + item.id, + operationArgs as OperationArgs[ OperationType.Rotate ] + ); + break; + + case OperationType.TranscodeImage: + dispatch.transcodeImageItem( + item.id, + operationArgs as OperationArgs[ OperationType.TranscodeImage ] + ); + break; + case OperationType.Upload: - dispatch.uploadItem( id ); + if ( item.parentId ) { + dispatch.sideloadItem( id ); + } else { + dispatch.uploadItem( id ); + } + break; + + case OperationType.ThumbnailGeneration: + dispatch.generateThumbnails( id ); break; } }; @@ -303,23 +521,25 @@ export function pauseItem( id: QueueItemId ) { } /** - * Resumes a specific paused item in the queue. + * Resumes processing for a given post/attachment ID. * - * @param id Item ID. + * This function looks up paused uploads by post ID and resumes them. + * It's typically called after a sideload completes to resume paused + * thumbnail uploads. + * + * @param postOrAttachmentId Post or attachment ID. */ -export function resumeItem( id: QueueItemId ) { +export function resumeItemByPostId( postOrAttachmentId: number ) { return async ( { select, dispatch }: ThunkArgs ) => { - const item = select.getItem( id ); - if ( ! item || item.status !== ItemStatus.Paused ) { - return; + const item = select.getPausedUploadForPost( postOrAttachmentId ); + if ( item ) { + logItemResume( item.id ); + dispatch< ResumeItemAction >( { + type: Type.ResumeItem, + id: item.id, + } ); + dispatch.processItem( item.id ); } - - dispatch< ResumeItemAction >( { - type: Type.ResumeItem, - id, - } ); - - dispatch.processItem( id ); }; } @@ -335,6 +555,8 @@ export function removeItem( id: QueueItemId ) { return; } + logQueueRemove( id, item.file.name ); + dispatch( { type: Type.Remove, id, @@ -356,6 +578,10 @@ export function finishOperation( const item = select.getItem( id ); const previousOperation = item?.currentOperation; + if ( previousOperation && item ) { + logOperationComplete( id, previousOperation, item.file.name ); + } + dispatch< OperationFinishAction >( { type: Type.OperationFinish, id, @@ -377,6 +603,41 @@ export function finishOperation( }; } +const VALID_IMAGE_FORMATS = [ 'jpeg', 'webp', 'avif', 'png', 'gif' ] as const; + +/** + * Checks if a format string is a valid ImageFormat. + * + * @param format The format string to validate. + * @return Whether the format is valid. + */ +function isValidImageFormat( format: string ): format is ImageFormat { + return VALID_IMAGE_FORMATS.includes( format as ImageFormat ); +} + +/** + * Gets the appropriate interlace setting for the given output format. + * + * @param outputMimeType The output mime type. + * @param settings The upload settings. + * @return Whether to use interlaced encoding. + */ +function getInterlacedSetting( + outputMimeType: string, + settings: Settings +): boolean { + switch ( outputMimeType ) { + case 'image/jpeg': + return settings.jpegInterlaced ?? false; + case 'image/png': + return settings.pngInterlaced ?? false; + case 'image/gif': + return settings.gifInterlaced ?? false; + default: + return false; + } +} + /** * Prepares an item for initial processing. * @@ -392,8 +653,44 @@ export function finishOperation( * @param id Item ID. */ export function prepareItem( id: QueueItemId ) { - return async ( { dispatch }: ThunkArgs ) => { - const operations: Operation[] = [ OperationType.Upload ]; + return async ( { select, dispatch }: ThunkArgs ) => { + const item = select.getItem( id ); + if ( ! item ) { + return; + } + const { file } = item; + + const operations: Operation[] = []; + + const isImage = file.type.startsWith( 'image/' ); + + // For images, check if we need to scale down based on threshold. + if ( isImage ) { + const bigImageSizeThreshold = + select.getSettings().bigImageSizeThreshold; + + // 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, + }, + ] ); + } + + operations.push( + OperationType.Upload, + OperationType.ThumbnailGeneration + ); + } else { + operations.push( OperationType.Upload ); + } dispatch< AddOperationsAction >( { type: Type.AddOperations, @@ -412,7 +709,12 @@ export function prepareItem( id: QueueItemId ) { */ export function uploadItem( id: QueueItemId ) { return async ( { select, dispatch }: ThunkArgs ) => { - const item = select.getItem( id ) as QueueItem; + const item = select.getItem( id ); + if ( ! item ) { + return; + } + + logUploadStart( id, item.file.name, item.file.size ); select.getSettings().mediaUpload( { filesList: [ item.file ], @@ -420,23 +722,550 @@ export function uploadItem( id: QueueItemId ) { signal: item.abortController?.signal, onFileChange: ( [ attachment ] ) => { if ( ! isBlobURL( attachment.url ) ) { + logUploadComplete( + id, + item.file.name, + attachment.id, + attachment.url + ); dispatch.finishOperation( id, { attachment, } ); } }, onSuccess: ( [ attachment ] ) => { + logUploadComplete( + id, + item.file.name, + attachment.id, + attachment.url + ); dispatch.finishOperation( id, { attachment, } ); }, onError: ( error ) => { + logError( 'uploadItem', error, id ); + dispatch.cancelItem( id, error ); + }, + } ); + }; +} + +/** + * Sideloads an item to the server. + * + * @param id Item ID. + */ +export function sideloadItem( id: QueueItemId ) { + return async ( { select, dispatch }: ThunkArgs ) => { + const item = select.getItem( id ); + if ( ! item ) { + return; + } + + const { + post, + image_size: imageSize, + ...additionalData + } = item.additionalData as SideloadAdditionalData; + + const mediaSideload = select.getSettings().mediaSideload; + if ( ! mediaSideload ) { + // If sideloading is not supported, skip this operation. + dispatch.finishOperation( id, {} ); + return; + } + + logSideloadStart( + id, + item.file.name, + post as number, + imageSize || 'unknown' + ); + + mediaSideload( { + file: item.file, + attachmentId: post as number, + additionalData: { image_size: imageSize, ...additionalData }, + signal: item.abortController?.signal, + onFileChange: ( [ attachment ] ) => { + logSideloadComplete( + id, + item.file.name, + imageSize || 'unknown' + ); + dispatch.finishOperation( id, { attachment } ); + dispatch.resumeItemByPostId( post as number ); + }, + onError: ( error ) => { + logError( 'sideloadItem', error, id ); dispatch.cancelItem( id, error ); + dispatch.resumeItemByPostId( post as number ); }, } ); }; } +type ResizeCropItemArgs = OperationArgs[ OperationType.ResizeCrop ]; + +/** + * Resizes and crops an existing image item. + * + * @param id Item ID. + * @param [args] Additional arguments for the operation. + */ +export function resizeCropItem( id: QueueItemId, args?: ResizeCropItemArgs ) { + return async ( { select, dispatch }: ThunkArgs ) => { + const item = select.getItem( id ); + if ( ! item ) { + return; + } + + if ( ! args?.resize ) { + dispatch.finishOperation( id, { + file: item.file, + } ); + return; + } + + // Add dimension suffix for sub-sizes (thumbnails). + const addSuffix = Boolean( item.parentId ); + // Add '-scaled' suffix for big image threshold resizing. + const scaledSuffix = Boolean( args.isThresholdResize ); + + logResizeCrop( + id, + item.file.name, + args.resize, + Boolean( args.isThresholdResize ), + addSuffix + ); + + try { + const timer = createTimer(); + const file = await vipsResizeImage( + item.id, + item.file, + args.resize, + false, // smartCrop + addSuffix, + item.abortController?.signal, + scaledSuffix + ); + const duration = timer.stop(); + + // Log resize completion with dimensions + const imageFile = file as { + width?: number; + height?: number; + originalWidth?: number; + originalHeight?: number; + }; + logResizeComplete( + id, + file.name, + imageFile.originalWidth || 0, + imageFile.originalHeight || 0, + imageFile.width || 0, + imageFile.height || 0, + file.size + ); + + logOperationComplete( id, 'ResizeCrop', file.name, duration ); + + const blobUrl = createBlobURL( file ); + dispatch< CacheBlobUrlAction >( { + type: Type.CacheBlobUrl, + id, + blobUrl, + } ); + + dispatch.finishOperation( id, { + file, + attachment: { + url: blobUrl, + }, + } ); + } catch ( error ) { + logError( + 'resizeCropItem', + error instanceof Error ? error : String( error ), + id + ); + dispatch.cancelItem( + id, + new UploadError( { + code: 'IMAGE_TRANSCODING_ERROR', + message: 'File could not be uploaded', + file: item.file, + cause: error instanceof Error ? error : undefined, + } ) + ); + } + }; +} + +type RotateItemArgs = OperationArgs[ OperationType.Rotate ]; + +/** + * Rotates an image based on EXIF orientation. + * + * This is used for images that need rotation but don't need resizing + * (i.e., smaller than the big image size threshold). + * Matches WordPress core's behavior of creating a '-rotated' version. + * + * @param id Item ID. + * @param [args] Rotation arguments including EXIF orientation value. + */ +export function rotateItem( id: QueueItemId, args?: RotateItemArgs ) { + return async ( { select, dispatch }: ThunkArgs ) => { + const item = select.getItem( id ); + if ( ! item ) { + return; + } + + // If no orientation provided or orientation is 1 (normal), skip rotation. + if ( ! args?.orientation || args.orientation === 1 ) { + dispatch.finishOperation( id, { + file: item.file, + } ); + return; + } + + logRotation( id, item.file.name, args.orientation ); + + try { + const timer = createTimer(); + const file = await vipsRotateImage( + item.id, + item.file, + args.orientation, + item.abortController?.signal + ); + const duration = timer.stop(); + + // Log rotation completion with new dimensions + const imageFile = file as { width?: number; height?: number }; + logRotationComplete( + id, + file.name, + imageFile.width || 0, + imageFile.height || 0 + ); + + logOperationComplete( id, 'Rotate', file.name, duration ); + + const blobUrl = createBlobURL( file ); + dispatch< CacheBlobUrlAction >( { + type: Type.CacheBlobUrl, + id, + blobUrl, + } ); + + dispatch.finishOperation( id, { + file, + attachment: { + url: blobUrl, + }, + } ); + } catch ( error ) { + logError( + 'rotateItem', + error instanceof Error ? error : String( error ), + id + ); + dispatch.cancelItem( + id, + new UploadError( { + code: 'IMAGE_ROTATION_ERROR', + message: 'Image could not be rotated', + file: item.file, + cause: error instanceof Error ? error : undefined, + } ) + ); + } + }; +} + +type TranscodeImageItemArgs = OperationArgs[ OperationType.TranscodeImage ]; + +/** + * Transcodes an image to a different format. + * + * This operation converts images between formats (e.g., PNG to WebP, JPEG to AVIF) + * based on the WordPress image_editor_output_format filter settings. + * + * @param id Item ID. + * @param [args] Transcode arguments including output format, quality, and interlace settings. + */ +export function transcodeImageItem( + id: QueueItemId, + args?: TranscodeImageItemArgs +) { + return async ( { select, dispatch }: ThunkArgs ) => { + const item = select.getItem( id ); + if ( ! item ) { + return; + } + + // If no output format specified, skip transcoding. + if ( ! args?.outputFormat ) { + dispatch.finishOperation( id, { + file: item.file, + } ); + return; + } + + const outputMimeType = `image/${ args.outputFormat }` as + | 'image/jpeg' + | 'image/png' + | 'image/webp' + | 'image/avif' + | 'image/gif'; + const quality = args.outputQuality ?? 0.82; + const interlaced = args.interlaced ?? false; + + logTranscode( + id, + item.file.name, + item.file.type, + outputMimeType, + quality + ); + + try { + const timer = createTimer(); + const originalSize = item.file.size; + + const file = await vipsConvertImageFormat( + item.id, + item.file, + outputMimeType, + quality, + interlaced + ); + + const duration = timer.stop(); + + logTranscodeComplete( + id, + file.name, + outputMimeType, + originalSize, + file.size + ); + + logOperationComplete( id, 'TranscodeImage', file.name, duration ); + + const blobUrl = createBlobURL( file ); + dispatch< CacheBlobUrlAction >( { + type: Type.CacheBlobUrl, + id, + blobUrl, + } ); + + dispatch.finishOperation( id, { + file, + attachment: { + url: blobUrl, + }, + } ); + } catch ( error ) { + logError( + 'transcodeImageItem', + error instanceof Error ? error : String( error ), + id + ); + dispatch.cancelItem( + id, + new UploadError( { + code: 'MEDIA_TRANSCODING_ERROR', + message: + 'Image could not be transcoded to the target format', + file: item.file, + cause: error instanceof Error ? error : undefined, + } ) + ); + } + }; +} + +/** + * Adds thumbnail versions to the queue for sideloading. + * + * Also handles image rotation for images that need EXIF-based rotation + * but weren't scaled down (and thus weren't auto-rotated by vips). + * + * @param id Item ID. + */ +export function generateThumbnails( id: QueueItemId ) { + return async ( { select, dispatch }: ThunkArgs ) => { + const item = select.getItem( id ); + if ( ! item ) { + return; + } + + if ( ! item.attachment ) { + dispatch.finishOperation( id, {} ); + return; + } + const attachment = item.attachment; + + // Check if image needs rotation. + // If exif_orientation is not 1, the image needs rotation. + // Images that were scaled (bigImageSizeThreshold) are already rotated by vips. + const needsRotation = + attachment.exif_orientation && + attachment.exif_orientation !== 1 && + ! item.file.name.includes( '-scaled' ); + + // If rotation is needed for a non-scaled image, sideload the rotated version. + // This matches WordPress core's behavior of creating a -rotated version. + if ( needsRotation && attachment.id ) { + try { + const rotatedFile = await vipsRotateImage( + item.id, + item.sourceFile, + attachment.exif_orientation as number, + item.abortController?.signal + ); + + // Sideload the rotated file as the "original" to set original_image metadata. + // The server will store this in $metadata['original_image']. + dispatch.addSideloadItem( { + file: rotatedFile, + batchId: uuidv4(), + parentId: item.id, + additionalData: { + post: attachment.id, + image_size: 'original', + convert_format: false, + }, + operations: [ OperationType.Upload ], + } ); + } catch { + // If rotation fails, continue with thumbnail generation. + // Thumbnails will still be rotated correctly by vips. + // eslint-disable-next-line no-console + console.warn( + 'Failed to rotate image, continuing with thumbnails' + ); + } + } + + // Client-side thumbnail generation for images. + if ( + ! item.parentId && + attachment.missing_image_sizes && + attachment.missing_image_sizes.length > 0 + ) { + logThumbnailGenerationStart( + id, + item.file.name, + attachment.missing_image_sizes + ); + + // 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 ) + : item.sourceFile; + const batchId = uuidv4(); + + const settings = select.getSettings(); + const allImageSizes = settings.allImageSizes || {}; + const { imageOutputFormats } = settings; + + // Check if thumbnails should be transcoded to a different format. + const sourceType = item.sourceFile.type; + const outputMimeType = imageOutputFormats?.[ sourceType ]; + const shouldTranscodeThumbnails = + outputMimeType && outputMimeType !== sourceType; + + for ( const name of attachment.missing_image_sizes ) { + const imageSize = allImageSizes[ name ]; + if ( ! imageSize ) { + // eslint-disable-next-line no-console + console.warn( + `Image size "${ name }" not found in configuration` + ); + continue; + } + + logThumbnailCreate( + id, + name, + imageSize.width, + imageSize.height, + imageSize.crop + ); + + // Build operations list for this thumbnail. + const thumbnailOperations: Operation[] = [ + [ OperationType.ResizeCrop, { resize: imageSize } ], + ]; + + // Add transcoding if format conversion is configured. + // Note: For PNG->JPEG thumbnails, we rely on the main image + // transparency check. If the main image was not transcoded + // (due to having transparency), thumbnails won't be either. + // This matches the server behavior. + if ( shouldTranscodeThumbnails ) { + const formatPart = outputMimeType.split( '/' )[ 1 ]; + if ( isValidImageFormat( formatPart ) ) { + thumbnailOperations.push( [ + OperationType.TranscodeImage, + { + outputFormat: formatPart, + outputQuality: 0.82, + interlaced: getInterlacedSetting( + outputMimeType, + settings + ), + }, + ] ); + } + } + + thumbnailOperations.push( OperationType.Upload ); + + dispatch.addSideloadItem( { + file, + onChange: ( [ updatedAttachment ] ) => { + // If the sub-size is still being generated, there is no need + // to invoke the callback below. It would just override + // the main image in the editor with the sub-size. + if ( isBlobURL( updatedAttachment.url ) ) { + return; + } + + // This might be confusing, but the idea is to update the original + // image item in the editor with the new one with the added sub-size. + item.onChange?.( [ updatedAttachment ] ); + }, + batchId, + parentId: item.id, + additionalData: { + // Sideloading does not use the parent post ID but the + // attachment ID as the image sizes need to be added to it. + post: attachment.id, + image_size: name, + convert_format: false, + }, + operations: [ + [ OperationType.ResizeCrop, { resize: imageSize } ], + OperationType.Upload, + ], + } ); + } + } + + dispatch.finishOperation( id, {} ); + }; +} + /** * Revokes all blob URLs for a given item, freeing up memory. * diff --git a/packages/upload-media/src/store/private-selectors.ts b/packages/upload-media/src/store/private-selectors.ts index 07003b4f672254..cace7e257e030b 100644 --- a/packages/upload-media/src/store/private-selectors.ts +++ b/packages/upload-media/src/store/private-selectors.ts @@ -155,6 +155,21 @@ export function getFailedItems( state: State ): QueueItem[] { return state.queue.filter( ( item ) => item.error !== undefined ); } +/** + * Determines whether any upload is currently in progress for items with a given parent ID. + * + * @param state Upload state. + * @param parentId Parent item ID. + * + * @return Whether any child item is still uploading. + */ +export function isUploadingByParentId( + state: State, + parentId: QueueItemId +): boolean { + return state.queue.some( ( item ) => item.parentId === parentId ); +} + /** * Returns the progress of a specific item. * diff --git a/packages/upload-media/src/store/test/actions.ts b/packages/upload-media/src/store/test/actions.ts index adb38ab27128e3..0a3ae211fab717 100644 --- a/packages/upload-media/src/store/test/actions.ts +++ b/packages/upload-media/src/store/test/actions.ts @@ -19,6 +19,15 @@ jest.mock( '@wordpress/blob', () => ( { revokeBlobURL: jest.fn(), } ) ); +jest.mock( '../utils', () => ( { + __esModule: true, + vipsCancelOperations: jest.fn( () => Promise.resolve( true ) ), + vipsResizeImage: jest.fn(), +} ) ); + +// Import the mocked module to access the mock function. +import { vipsCancelOperations } from '../utils'; + function createRegistryWithStores() { // Create a registry and register used stores. const registry = createRegistry(); @@ -109,4 +118,121 @@ describe( 'actions', () => { ); } ); } ); + + describe( 'addSideloadItem', () => { + it( 'adds a sideload item with parent ID', () => { + // Add parent item first. + unlock( registry.dispatch( uploadStore ) ).addItem( { + file: jpegFile, + } ); + const parentItem = unlock( + registry.select( uploadStore ) + ).getAllItems()[ 0 ]; + + unlock( registry.dispatch( uploadStore ) ).addSideloadItem( { + file: jpegFile, + parentId: parentItem.id, + additionalData: { post: 123, image_size: 'thumbnail' }, + } ); + + const items = unlock( + registry.select( uploadStore ) + ).getAllItems(); + expect( items ).toHaveLength( 2 ); + expect( items[ 1 ].parentId ).toBe( parentItem.id ); + expect( items[ 1 ].additionalData ).toEqual( + expect.objectContaining( { + post: 123, + image_size: 'thumbnail', + } ) + ); + } ); + + it( 'adds a sideload item with custom operations', () => { + unlock( registry.dispatch( uploadStore ) ).addSideloadItem( { + file: jpegFile, + additionalData: { post: 456, image_size: 'medium' }, + } ); + + const items = unlock( + registry.select( uploadStore ) + ).getAllItems(); + expect( items ).toHaveLength( 1 ); + expect( items[ 0 ].status ).toBe( ItemStatus.Processing ); + } ); + } ); + + describe( 'cancelItem', () => { + beforeEach( () => { + ( vipsCancelOperations as jest.Mock ).mockClear(); + } ); + + it( 'calls vipsCancelOperations when cancelling', async () => { + unlock( registry.dispatch( uploadStore ) ).addItem( { + file: jpegFile, + } ); + const item = unlock( + registry.select( uploadStore ) + ).getAllItems()[ 0 ]; + + await registry + .dispatch( uploadStore ) + .cancelItem( item.id, new Error( 'User cancelled' ) ); + + expect( vipsCancelOperations ).toHaveBeenCalledWith( item.id ); + } ); + + it( 'removes item from queue after cancelling', async () => { + unlock( registry.dispatch( uploadStore ) ).addItem( { + file: jpegFile, + } ); + const item = unlock( + registry.select( uploadStore ) + ).getAllItems()[ 0 ]; + + await registry + .dispatch( uploadStore ) + .cancelItem( item.id, new Error( 'User cancelled' ) ); + + expect( + unlock( registry.select( uploadStore ) ).getAllItems() + ).toHaveLength( 0 ); + } ); + + it( 'calls onError callback when not silent', async () => { + const onError = jest.fn(); + unlock( registry.dispatch( uploadStore ) ).addItem( { + file: jpegFile, + onError, + } ); + const item = unlock( + registry.select( uploadStore ) + ).getAllItems()[ 0 ]; + + await registry + .dispatch( uploadStore ) + .cancelItem( item.id, new Error( 'Test error' ) ); + + expect( onError ).toHaveBeenCalledWith( + expect.objectContaining( { message: 'Test error' } ) + ); + } ); + + it( 'does not call onError when silent', async () => { + const onError = jest.fn(); + unlock( registry.dispatch( uploadStore ) ).addItem( { + file: jpegFile, + onError, + } ); + const item = unlock( + registry.select( uploadStore ) + ).getAllItems()[ 0 ]; + + await registry + .dispatch( uploadStore ) + .cancelItem( item.id, new Error( 'Test error' ), true ); + + expect( onError ).not.toHaveBeenCalled(); + } ); + } ); } ); diff --git a/packages/upload-media/src/store/test/selectors.ts b/packages/upload-media/src/store/test/selectors.ts index aebd775883e616..742a02ec3f0142 100644 --- a/packages/upload-media/src/store/test/selectors.ts +++ b/packages/upload-media/src/store/test/selectors.ts @@ -12,6 +12,7 @@ import { getFailedItems, getItemProgress, getPendingUploads, + isUploadingByParentId, } from '../private-selectors'; import { ItemStatus, @@ -235,4 +236,48 @@ describe( 'selectors', () => { expect( getItemProgress( state, '999' ) ).toBeUndefined(); } ); } ); + + describe( 'isUploadingByParentId', () => { + it( 'should return true if there are items with matching parent ID', () => { + const state: State = { + queue: [ + { + id: '1', + parentId: 'parent-1', + status: ItemStatus.Processing, + }, + { + id: '2', + status: ItemStatus.Processing, + }, + ] as QueueItem[], + queueStatus: 'paused', + blobUrls: {}, + settings: { + mediaUpload: jest.fn(), + }, + }; + + expect( isUploadingByParentId( state, 'parent-1' ) ).toBe( true ); + expect( isUploadingByParentId( state, 'parent-2' ) ).toBe( false ); + } ); + + it( 'should return false if no items have a parent ID', () => { + const state: State = { + queue: [ + { + id: '1', + status: ItemStatus.Processing, + }, + ] as QueueItem[], + queueStatus: 'paused', + blobUrls: {}, + settings: { + mediaUpload: jest.fn(), + }, + }; + + expect( isUploadingByParentId( state, 'parent-1' ) ).toBe( false ); + } ); + } ); } ); diff --git a/packages/upload-media/src/store/test/vips.ts b/packages/upload-media/src/store/test/vips.ts new file mode 100644 index 00000000000000..ef076652c57d0c --- /dev/null +++ b/packages/upload-media/src/store/test/vips.ts @@ -0,0 +1,323 @@ +/** + * External dependencies + */ + +// Mock the vips worker module. +// The mock functions must be declared inside the factory to avoid hoisting issues. +jest.mock( '@wordpress/vips/worker', () => ( { + vipsConvertImageFormat: jest.fn(), + vipsCompressImage: jest.fn(), + vipsHasTransparency: jest.fn(), + vipsResizeImage: jest.fn(), + vipsRotateImage: jest.fn(), + vipsCancelOperations: jest.fn(), +} ) ); + +// Import the mocked module to get access to the mock functions. +import * as vipsWorker from '@wordpress/vips/worker'; + +/** + * Internal dependencies + */ +import { ImageFile } from '../../image-file'; +import type { ImageSizeCrop } from '../types'; + +// Import after mock is set up. +import { + vipsConvertImageFormat, + vipsCompressImage, + vipsHasTransparency, + vipsResizeImage, + vipsRotateImage, + vipsCancelOperations, +} from '../utils/vips'; + +// Cast to jest.Mock for type safety. +const mockConvertImageFormat = vipsWorker.vipsConvertImageFormat as jest.Mock; +const mockCompressImage = vipsWorker.vipsCompressImage as jest.Mock; +const mockHasTransparency = vipsWorker.vipsHasTransparency as jest.Mock; +const mockResizeImage = vipsWorker.vipsResizeImage as jest.Mock; +const mockRotateImage = vipsWorker.vipsRotateImage as jest.Mock; +const mockCancelOperations = vipsWorker.vipsCancelOperations as jest.Mock; + +const jpegFile = new File( [ 'test-content' ], 'test.jpg', { + type: 'image/jpeg', + lastModified: 1234567890, +} ); + +const pngFile = new File( [ 'test-content' ], 'image.png', { + type: 'image/png', + lastModified: 1234567890, +} ); + +describe( 'vips utilities', () => { + beforeEach( () => { + jest.clearAllMocks(); + } ); + + describe( 'vipsConvertImageFormat', () => { + it( 'converts image and returns new File with correct extension', async () => { + mockConvertImageFormat.mockResolvedValue( new ArrayBuffer( 10 ) ); + + const result = await vipsConvertImageFormat( + 'item-1', + jpegFile, + 'image/webp', + 0.8 + ); + + expect( result.name ).toBe( 'test.webp' ); + expect( result.type ).toBe( 'image/webp' ); + expect( mockConvertImageFormat ).toHaveBeenCalledTimes( 1 ); + expect( mockConvertImageFormat.mock.calls[ 0 ][ 0 ] ).toBe( + 'item-1' + ); + expect( mockConvertImageFormat.mock.calls[ 0 ][ 2 ] ).toBe( + 'image/jpeg' + ); + expect( mockConvertImageFormat.mock.calls[ 0 ][ 3 ] ).toBe( + 'image/webp' + ); + expect( mockConvertImageFormat.mock.calls[ 0 ][ 4 ] ).toBe( 0.8 ); + } ); + + it( 'converts PNG to AVIF with interlacing', async () => { + mockConvertImageFormat.mockResolvedValue( new ArrayBuffer( 5 ) ); + + const result = await vipsConvertImageFormat( + 'item-2', + pngFile, + 'image/avif', + 0.9, + true + ); + + expect( result.name ).toBe( 'image.avif' ); + expect( result.type ).toBe( 'image/avif' ); + expect( mockConvertImageFormat.mock.calls[ 0 ][ 5 ] ).toBe( true ); + } ); + } ); + + describe( 'vipsCompressImage', () => { + it( 'compresses image preserving filename and type', async () => { + mockCompressImage.mockResolvedValue( new ArrayBuffer( 5 ) ); + + const result = await vipsCompressImage( 'item-1', jpegFile, 0.8 ); + + expect( result.name ).toBe( 'test.jpg' ); + expect( result.type ).toBe( 'image/jpeg' ); + expect( mockCompressImage ).toHaveBeenCalledTimes( 1 ); + expect( mockCompressImage.mock.calls[ 0 ][ 0 ] ).toBe( 'item-1' ); + expect( mockCompressImage.mock.calls[ 0 ][ 2 ] ).toBe( + 'image/jpeg' + ); + expect( mockCompressImage.mock.calls[ 0 ][ 3 ] ).toBe( 0.8 ); + } ); + + it( 'compresses image with interlacing option', async () => { + mockCompressImage.mockResolvedValue( new ArrayBuffer( 5 ) ); + + const result = await vipsCompressImage( + 'item-2', + pngFile, + 0.7, + true + ); + + expect( result.name ).toBe( 'image.png' ); + expect( mockCompressImage.mock.calls[ 0 ][ 4 ] ).toBe( true ); + } ); + } ); + + describe( 'vipsHasTransparency', () => { + let mockFetch: jest.Mock; + + beforeEach( () => { + mockFetch = jest.fn().mockResolvedValue( { + ok: true, + arrayBuffer: () => Promise.resolve( new ArrayBuffer( 0 ) ), + } as Response ); + window.fetch = mockFetch; + } ); + + it( 'returns true when image has transparency', async () => { + mockHasTransparency.mockResolvedValue( true ); + + const result = await vipsHasTransparency( 'blob:test-url' ); + + expect( result ).toBe( true ); + expect( mockFetch ).toHaveBeenCalledWith( 'blob:test-url' ); + expect( mockHasTransparency ).toHaveBeenCalledTimes( 1 ); + } ); + + it( 'returns false when image has no transparency', async () => { + mockHasTransparency.mockResolvedValue( false ); + + const result = await vipsHasTransparency( + 'https://example.com/img' + ); + + expect( result ).toBe( false ); + } ); + } ); + + describe( 'vipsResizeImage', () => { + it( 'resizes image and returns ImageFile with dimensions and suffix', async () => { + mockResizeImage.mockResolvedValue( { + buffer: new ArrayBuffer( 10 ), + width: 150, + height: 150, + originalWidth: 300, + originalHeight: 300, + } ); + + const resize: ImageSizeCrop = { width: 150, height: 150 }; + const result = await vipsResizeImage( + 'item-1', + jpegFile, + resize, + false, + true + ); + + expect( result ).toBeInstanceOf( ImageFile ); + // ImageFile extends File, so name/type are direct properties. + expect( result.name ).toBe( 'test-150x150.jpg' ); + expect( result.type ).toBe( 'image/jpeg' ); + expect( result.width ).toBe( 150 ); + expect( result.height ).toBe( 150 ); + expect( result.originalWidth ).toBe( 300 ); + expect( result.originalHeight ).toBe( 300 ); + } ); + + it( 'does not add suffix when dimensions unchanged', async () => { + mockResizeImage.mockResolvedValue( { + buffer: new ArrayBuffer( 10 ), + width: 300, + height: 300, + originalWidth: 300, + originalHeight: 300, + } ); + + const resize: ImageSizeCrop = { width: 300, height: 300 }; + const result = await vipsResizeImage( + 'item-1', + jpegFile, + resize, + false, + true + ); + + expect( result.name ).toBe( 'test.jpg' ); + } ); + + it( 'does not add suffix when addSuffix is false', async () => { + mockResizeImage.mockResolvedValue( { + buffer: new ArrayBuffer( 10 ), + width: 150, + height: 150, + originalWidth: 300, + originalHeight: 300, + } ); + + const resize: ImageSizeCrop = { width: 150, height: 150 }; + const result = await vipsResizeImage( + 'item-1', + jpegFile, + resize, + false, + false + ); + + expect( result.name ).toBe( 'test.jpg' ); + } ); + + it( 'passes smart crop parameter to worker', async () => { + mockResizeImage.mockResolvedValue( { + buffer: new ArrayBuffer( 10 ), + width: 100, + height: 100, + originalWidth: 200, + originalHeight: 200, + } ); + + const resize: ImageSizeCrop = { + width: 100, + height: 100, + crop: true, + }; + await vipsResizeImage( 'item-1', jpegFile, resize, true, true ); + + expect( mockResizeImage ).toHaveBeenCalledTimes( 1 ); + expect( mockResizeImage.mock.calls[ 0 ][ 0 ] ).toBe( 'item-1' ); + expect( mockResizeImage.mock.calls[ 0 ][ 2 ] ).toBe( 'image/jpeg' ); + expect( mockResizeImage.mock.calls[ 0 ][ 3 ] ).toEqual( resize ); + expect( mockResizeImage.mock.calls[ 0 ][ 4 ] ).toBe( true ); + } ); + } ); + + describe( 'vipsRotateImage', () => { + it( 'rotates image and returns ImageFile with -rotated suffix', async () => { + mockRotateImage.mockResolvedValue( { + buffer: new ArrayBuffer( 10 ), + width: 200, + height: 300, + } ); + + const result = await vipsRotateImage( 'item-1', jpegFile, 6 ); + + expect( result ).toBeInstanceOf( ImageFile ); + expect( result.name ).toBe( 'test-rotated.jpg' ); + expect( result.type ).toBe( 'image/jpeg' ); + expect( result.width ).toBe( 200 ); + expect( result.height ).toBe( 300 ); + + expect( mockRotateImage ).toHaveBeenCalledTimes( 1 ); + expect( mockRotateImage.mock.calls[ 0 ][ 0 ] ).toBe( 'item-1' ); + expect( mockRotateImage.mock.calls[ 0 ][ 2 ] ).toBe( 'image/jpeg' ); + expect( mockRotateImage.mock.calls[ 0 ][ 3 ] ).toBe( 6 ); + } ); + + it( 'returns original file when orientation is 1 (no rotation needed)', async () => { + const result = await vipsRotateImage( 'item-1', jpegFile, 1 ); + + expect( result ).toBe( jpegFile ); + expect( mockRotateImage ).not.toHaveBeenCalled(); + } ); + + it( 'handles different EXIF orientation values', async () => { + mockRotateImage.mockResolvedValue( { + buffer: new ArrayBuffer( 10 ), + width: 300, + height: 200, + } ); + + // Test orientation 3 (180° rotation) + await vipsRotateImage( 'item-1', jpegFile, 3 ); + expect( mockRotateImage.mock.calls[ 0 ][ 3 ] ).toBe( 3 ); + + // Test orientation 8 (90° CCW rotation) + await vipsRotateImage( 'item-2', jpegFile, 8 ); + expect( mockRotateImage.mock.calls[ 1 ][ 3 ] ).toBe( 8 ); + } ); + } ); + + describe( 'vipsCancelOperations', () => { + it( 'calls worker cancelOperations with item ID', async () => { + mockCancelOperations.mockResolvedValue( true ); + + const result = await vipsCancelOperations( 'item-123' ); + + expect( mockCancelOperations ).toHaveBeenCalledWith( 'item-123' ); + expect( result ).toBe( true ); + } ); + + it( 'returns false when no operations were cancelled', async () => { + mockCancelOperations.mockResolvedValue( false ); + + const result = await vipsCancelOperations( 'item-456' ); + + expect( result ).toBe( false ); + } ); + } ); +} ); diff --git a/packages/upload-media/src/store/types.ts b/packages/upload-media/src/store/types.ts index 444d02069d75bc..07108b4d03ff17 100644 --- a/packages/upload-media/src/store/types.ts +++ b/packages/upload-media/src/store/types.ts @@ -25,6 +25,7 @@ export interface QueueItem { sourceUrl?: string; sourceAttachmentId?: number; abortController?: AbortController; + parentId?: QueueItemId; } export interface State { @@ -129,15 +130,78 @@ interface UploadMediaArgs { signal?: AbortSignal; } +/** + * Arguments for sideloading a file to an existing attachment. + * + * Sideloading adds additional image sizes (thumbnails) to an already + * uploaded attachment without creating a new attachment. + */ +export interface SideloadMediaArgs { + /** File to sideload (typically a resized version of the original). */ + file: File; + /** Attachment ID to add the sideloaded file to. */ + attachmentId: number; + /** Additional data to include in the request. */ + additionalData?: AdditionalData; + /** Function called when an error happens. */ + onError?: OnErrorHandler; + /** Function called when the file or a temporary representation is available. */ + onFileChange?: OnChangeHandler; + /** Abort signal to cancel the sideload operation. */ + signal?: AbortSignal; +} + export interface Settings { + // Registered image sizes from the server. + allImageSizes?: Record< + string, + { width: number; height: number; crop: boolean } + >; // Function for uploading files to the server. mediaUpload: ( args: UploadMediaArgs ) => void; + // Function for sideloading files to existing attachments. + mediaSideload?: ( args: SideloadMediaArgs ) => void; // List of allowed mime types and file extensions. allowedMimeTypes?: Record< string, string > | null; // Maximum upload file size. maxUploadFileSize?: number; // Maximum number of concurrent uploads. maxConcurrentUploads: number; + /** + * Big image size threshold in pixels. + * Images larger than this will be scaled down before upload. + * Default is 2560 (matching WordPress core). + */ + bigImageSizeThreshold?: number; + /** + * Output format mapping from WordPress image_editor_output_format filter. + * Maps input MIME types to output MIME types for format conversion. + * + * @example + * ```js + * // Convert PNG to WebP, JPEG to AVIF + * { 'image/png': 'image/webp', 'image/jpeg': 'image/avif' } + * ``` + */ + imageOutputFormats?: Record< string, string >; + /** + * Whether to use interlaced/progressive encoding for JPEG images. + * Progressive JPEGs load gradually, showing a low-quality preview first. + * Controlled by WordPress image_save_progressive filter. + */ + jpegInterlaced?: boolean; + /** + * Whether to use interlaced encoding for PNG images. + * Interlaced PNGs display progressively during loading. + * Controlled by WordPress image_save_progressive filter. + */ + pngInterlaced?: boolean; + /** + * Whether to use interlaced encoding for GIF images. + * Interlaced GIFs display progressively during loading. + * Controlled by WordPress image_save_progressive filter. + */ + gifInterlaced?: boolean; } // Must match the Attachment type from the media-utils package. @@ -153,7 +217,24 @@ 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. + * Values 1-8 follow the EXIF specification. + * A value other than 1 indicates the image needs rotation. + * + * Orientation values: + * 1 = Normal (no rotation needed) + * 2 = Flipped horizontally + * 3 = Rotated 180° + * 4 = Flipped vertically + * 5 = Rotated 90° CCW and flipped horizontally + * 6 = Rotated 90° CW + * 7 = Rotated 90° CW and flipped horizontally + * 8 = Rotated 90° CCW + */ + exif_orientation?: number; } export type OnChangeHandler = ( attachments: Partial< Attachment >[] ) => void; @@ -172,9 +253,64 @@ export enum ItemStatus { export enum OperationType { Prepare = 'PREPARE', Upload = 'UPLOAD', + ResizeCrop = 'RESIZE_CROP', + Rotate = 'ROTATE', + TranscodeImage = 'TRANSCODE_IMAGE', + ThumbnailGeneration = 'THUMBNAIL_GENERATION', +} + +/** + * Defines the dimensions and cropping behavior for an image size. + */ +export interface ImageSizeCrop { + /** Target width in pixels. */ + width: number; + /** Target height in pixels. */ + height: number; + /** + * Crop behavior. + * - `true` for hard crop centered. + * - Positional array like `['left', 'top']` for specific crop anchor. + * - `false` or undefined for soft proportional resize. + */ + crop?: + | boolean + | [ 'left' | 'center' | 'right', 'top' | 'center' | 'bottom' ]; + /** Size name identifier (e.g., 'thumbnail', 'medium'). */ + name?: string; } -export interface OperationArgs {} +export interface OperationArgs { + [ OperationType.ResizeCrop ]: { + resize: ImageSizeCrop; + /** + * Whether this resize is for the big image size threshold. + * If true, uses '-scaled' suffix instead of dimension suffix. + */ + isThresholdResize?: boolean; + }; + [ OperationType.Rotate ]: { + /** + * EXIF orientation value (1-8) indicating the required rotation. + * Used to apply the correct rotation/flip transformation. + */ + orientation: number; + }; + [ OperationType.TranscodeImage ]: { + /** + * Output image format (e.g., 'jpeg', 'webp', 'avif', 'png'). + */ + outputFormat: ImageFormat; + /** + * Output quality (0-1). Defaults to 0.82 (82%). + */ + outputQuality?: number; + /** + * Whether to use interlaced/progressive encoding. + */ + interlaced?: boolean; + }; +} type OperationWithArgs< T extends keyof OperationArgs = keyof OperationArgs > = [ T, OperationArgs[ T ] ]; @@ -183,4 +319,17 @@ export type Operation = OperationType | OperationWithArgs; export type AdditionalData = Record< string, unknown >; +/** + * Additional data specific to sideload operations. + * + * This extends the base AdditionalData with fields required for + * sideloading image sizes to an existing attachment. + */ +export interface SideloadAdditionalData extends AdditionalData { + /** The attachment ID to add the image size to. */ + post: number; + /** The name of the image size being generated (e.g., 'thumbnail', 'medium'). */ + image_size: string; +} + export type ImageFormat = 'jpeg' | 'webp' | 'avif' | 'png' | 'gif'; diff --git a/packages/upload-media/src/store/utils/debug-logger.ts b/packages/upload-media/src/store/utils/debug-logger.ts new file mode 100644 index 00000000000000..beac9354b56261 --- /dev/null +++ b/packages/upload-media/src/store/utils/debug-logger.ts @@ -0,0 +1,635 @@ +/** + * Debug logger for client-side media processing. + * + * Provides detailed console logging for tracking the media upload pipeline. + * Set DEBUG_ENABLED to true to enable logging. + */ + +/* eslint-disable jsdoc/require-param */ + +// Set to true to enable debug logging for client-side media processing. +// Keep disabled by default to avoid test failures from unexpected console output. +const DEBUG_ENABLED = false; + +// Color codes for different log types. +const COLORS = { + queue: '#4CAF50', // Green - queue operations + operation: '#2196F3', // Blue - operation lifecycle + vips: '#9C27B0', // Purple - VIPS image processing + upload: '#FF9800', // Orange - upload/sideload operations + thumbnail: '#00BCD4', // Cyan - thumbnail generation + error: '#F44336', // Red - errors + info: '#607D8B', // Gray - general info + timing: '#795548', // Brown - timing information +} as const; + +type LogCategory = keyof typeof COLORS; + +interface LogOptions { + category: LogCategory; + data?: Record< string, unknown >; +} + +/** + * Formats bytes into human-readable size. + */ +function formatBytes( bytes: number ): string { + if ( bytes === 0 ) { + return '0 Bytes'; + } + const k = 1024; + const sizes = [ 'Bytes', 'KB', 'MB', 'GB' ]; + const i = Math.floor( Math.log( bytes ) / Math.log( k ) ); + return ( + parseFloat( ( bytes / Math.pow( k, i ) ).toFixed( 2 ) ) + + ' ' + + sizes[ i ] + ); +} + +/** + * Gets a timestamp string for logging. + */ +function getTimestamp(): string { + return new Date().toISOString().split( 'T' )[ 1 ].slice( 0, -1 ); +} + +/** + * Core logging function with styled output. + */ +function log( message: string, options: LogOptions ): void { + if ( ! DEBUG_ENABLED ) { + return; + } + + const { category, data } = options; + const color = COLORS[ category ]; + const timestamp = getTimestamp(); + const prefix = `[MEDIA:${ category.toUpperCase() }]`; + + // eslint-disable-next-line no-console + console.log( + `%c${ timestamp } ${ prefix }%c ${ message }`, + `color: ${ color }; font-weight: bold;`, + 'color: inherit;' + ); + + if ( data && Object.keys( data ).length > 0 ) { + // eslint-disable-next-line no-console + console.log( '%c └─ Details:', 'color: #888;', data ); + } +} + +/** + * Log when an item is added to the queue. + */ +export function logQueueAdd( + itemId: string, + fileName: string, + fileSize: number, + fileType: string, + batchId?: string +): void { + log( `Item added to queue: ${ fileName }`, { + category: 'queue', + data: { + itemId, + fileName, + fileSize: formatBytes( fileSize ), + fileType, + batchId: batchId || 'none', + }, + } ); +} + +/** + * Log when a sideload item is added to the queue. + */ +export function logSideloadAdd( + itemId: string, + fileName: string, + parentId: string, + imageSize: string +): void { + log( `Sideload item added: ${ fileName } (${ imageSize })`, { + category: 'thumbnail', + data: { + itemId, + fileName, + parentId, + imageSize, + }, + } ); +} + +/** + * Log when an item starts processing. + */ +export function logProcessStart( itemId: string, fileName: string ): void { + log( `Processing started: ${ fileName }`, { + category: 'queue', + data: { itemId }, + } ); +} + +/** + * Log when an operation starts. + */ +export function logOperationStart( + itemId: string, + operation: string, + fileName: string +): void { + log( `Operation started: ${ operation } on ${ fileName }`, { + category: 'operation', + data: { itemId, operation }, + } ); +} + +/** + * Log when an operation completes. + */ +export function logOperationComplete( + itemId: string, + operation: string, + fileName: string, + duration?: number +): void { + const durationStr = duration ? ` (${ duration }ms)` : ''; + log( + `Operation completed: ${ operation } on ${ fileName }${ durationStr }`, + { + category: 'operation', + data: { itemId, operation, durationMs: duration }, + } + ); +} + +/** + * Log when prepare determines operations. + */ +export function logPrepareOperations( + itemId: string, + fileName: string, + operations: string[] +): void { + log( `Prepared operations for ${ fileName }`, { + category: 'queue', + data: { + itemId, + operations, + operationCount: operations.length, + }, + } ); +} + +/** + * Log resize/crop operation details. + */ +export function logResizeCrop( + itemId: string, + fileName: string, + resize: { width: number; height: number; crop?: boolean | string[] }, + isThreshold: boolean, + isSubSize: boolean +): void { + let type = 'Resize/Crop'; + if ( isThreshold ) { + type = 'Big Image Threshold Resize'; + } else if ( isSubSize ) { + type = 'Thumbnail Generation'; + } + log( `${ type }: ${ fileName }`, { + category: 'vips', + data: { + itemId, + targetWidth: resize.width, + targetHeight: resize.height, + crop: resize.crop || false, + isThreshold, + isSubSize, + }, + } ); +} + +/** + * Log resize completion with dimensions. + */ +export function logResizeComplete( + itemId: string, + fileName: string, + originalWidth: number, + originalHeight: number, + newWidth: number, + newHeight: number, + newFileSize: number +): void { + const wasResized = + originalWidth !== newWidth || originalHeight !== newHeight; + log( + `Resize completed: ${ fileName } ${ originalWidth }x${ originalHeight } → ${ newWidth }x${ newHeight }`, + { + category: 'vips', + data: { + itemId, + originalDimensions: `${ originalWidth }x${ originalHeight }`, + newDimensions: `${ newWidth }x${ newHeight }`, + newFileSize: formatBytes( newFileSize ), + wasResized, + }, + } + ); +} + +/** + * Log rotation operation. + */ +export function logRotation( + itemId: string, + fileName: string, + orientation: number +): void { + const orientationNames: Record< number, string > = { + 1: 'Normal', + 2: 'Flipped horizontally', + 3: 'Rotated 180°', + 4: 'Flipped vertically', + 5: 'Rotated 90° CCW + flipped horizontally', + 6: 'Rotated 90° CW', + 7: 'Rotated 90° CW + flipped horizontally', + 8: 'Rotated 90° CCW', + }; + log( `EXIF Rotation: ${ fileName }`, { + category: 'vips', + data: { + itemId, + orientation, + orientationName: orientationNames[ orientation ] || 'Unknown', + }, + } ); +} + +/** + * Log rotation completion. + */ +export function logRotationComplete( + itemId: string, + fileName: string, + newWidth: number, + newHeight: number +): void { + log( `Rotation completed: ${ fileName }`, { + category: 'vips', + data: { + itemId, + newDimensions: `${ newWidth }x${ newHeight }`, + }, + } ); +} + +/** + * Log format transcoding operation. + */ +export function logTranscode( + itemId: string, + fileName: string, + inputFormat: string, + outputFormat: string, + quality: number +): void { + log( `Transcoding: ${ fileName } (${ inputFormat } → ${ outputFormat })`, { + category: 'vips', + data: { + itemId, + inputFormat, + outputFormat, + quality: Math.round( quality * 100 ) + '%', + }, + } ); +} + +/** + * Log format transcoding completion. + */ +export function logTranscodeComplete( + itemId: string, + fileName: string, + outputFormat: string, + inputSize: number, + outputSize: number +): void { + const savings = Math.round( ( 1 - outputSize / inputSize ) * 100 ); + log( `Transcoding completed: ${ fileName }`, { + category: 'vips', + data: { + itemId, + outputFormat, + inputSize: formatBytes( inputSize ), + outputSize: formatBytes( outputSize ), + savings: savings > 0 ? `${ savings }%` : 'none', + }, + } ); +} + +/** + * Log upload start. + */ +export function logUploadStart( + itemId: string, + fileName: string, + fileSize: number +): void { + log( `Upload started: ${ fileName }`, { + category: 'upload', + data: { + itemId, + fileSize: formatBytes( fileSize ), + }, + } ); +} + +/** + * Log upload completion. + */ +export function logUploadComplete( + itemId: string, + fileName: string, + attachmentId: number | undefined, + url: string | undefined +): void { + log( `Upload completed: ${ fileName }`, { + category: 'upload', + data: { + itemId, + attachmentId, + url, + }, + } ); +} + +/** + * Log sideload start. + */ +export function logSideloadStart( + itemId: string, + fileName: string, + attachmentId: number, + imageSize: string +): void { + log( `Sideload started: ${ fileName } as ${ imageSize }`, { + category: 'upload', + data: { + itemId, + attachmentId, + imageSize, + }, + } ); +} + +/** + * Log sideload completion. + */ +export function logSideloadComplete( + itemId: string, + fileName: string, + imageSize: string +): void { + log( `Sideload completed: ${ fileName } as ${ imageSize }`, { + category: 'upload', + data: { + itemId, + imageSize, + }, + } ); +} + +/** + * Log thumbnail generation start. + */ +export function logThumbnailGenerationStart( + itemId: string, + fileName: string, + missingSizes: string[] +): void { + log( `Thumbnail generation started: ${ fileName }`, { + category: 'thumbnail', + data: { + itemId, + missingSizes, + count: missingSizes.length, + }, + } ); +} + +/** + * Log individual thumbnail creation. + */ +export function logThumbnailCreate( + itemId: string, + sizeName: string, + width: number, + height: number, + crop: boolean | string[] +): void { + log( `Creating thumbnail: ${ sizeName } (${ width }x${ height })`, { + category: 'thumbnail', + data: { + itemId, + sizeName, + width, + height, + crop, + }, + } ); +} + +/** + * Log item removal from queue. + */ +export function logQueueRemove( itemId: string, fileName?: string ): void { + log( `Item removed from queue${ fileName ? `: ${ fileName }` : '' }`, { + category: 'queue', + data: { itemId }, + } ); +} + +/** + * Log item cancellation. + */ +export function logCancel( + itemId: string, + fileName: string, + error: Error | string +): void { + const errorMessage = error instanceof Error ? error.message : error; + log( `Item cancelled: ${ fileName }`, { + category: 'error', + data: { + itemId, + error: errorMessage, + }, + } ); +} + +/** + * Log error. + */ +export function logError( + context: string, + error: Error | string, + itemId?: string +): void { + const errorMessage = error instanceof Error ? error.message : error; + log( `Error in ${ context }: ${ errorMessage }`, { + category: 'error', + data: { + itemId, + error: errorMessage, + stack: error instanceof Error ? error.stack : undefined, + }, + } ); +} + +/** + * Log VIPS worker initialization. + */ +export function logVipsInit(): void { + log( 'VIPS WebAssembly worker initialized', { + category: 'vips', + } ); +} + +/** + * Log VIPS operation start. + */ +export function logVipsOperationStart( + operation: string, + itemId: string, + inputType: string +): void { + log( `VIPS ${ operation } started`, { + category: 'vips', + data: { + itemId, + inputType, + }, + } ); +} + +/** + * Log VIPS operation complete. + */ +export function logVipsOperationComplete( + operation: string, + itemId: string, + outputType: string +): void { + log( `VIPS ${ operation } completed`, { + category: 'vips', + data: { + itemId, + outputType, + }, + } ); +} + +/** + * Log queue pause. + */ +export function logQueuePause( reason?: string ): void { + log( `Queue paused${ reason ? `: ${ reason }` : '' }`, { + category: 'queue', + } ); +} + +/** + * Log queue resume. + */ +export function logQueueResume(): void { + log( 'Queue resumed', { + category: 'queue', + } ); +} + +/** + * Log item pause (for sideload race condition avoidance). + */ +export function logItemPause( itemId: string, reason: string ): void { + log( `Item paused: ${ reason }`, { + category: 'queue', + data: { itemId }, + } ); +} + +/** + * Log item resume. + */ +export function logItemResume( itemId: string ): void { + log( 'Item resumed', { + category: 'queue', + data: { itemId }, + } ); +} + +/** + * Log concurrency limit hit. + */ +export function logConcurrencyLimit( + itemId: string, + activeCount: number, + maxConcurrent: number +): void { + log( `Concurrency limit reached, queuing upload`, { + category: 'queue', + data: { + itemId, + activeUploads: activeCount, + maxConcurrent, + }, + } ); +} + +/** + * Log batch completion. + */ +export function logBatchComplete( batchId: string ): void { + log( `Batch completed`, { + category: 'queue', + data: { batchId }, + } ); +} + +/** + * Log settings update. + */ +export function logSettingsUpdate( settings: Record< string, unknown > ): void { + log( 'Settings updated', { + category: 'info', + data: settings, + } ); +} + +/** + * Log general info message. + */ +export function logInfo( + message: string, + data?: Record< string, unknown > +): void { + log( message, { + category: 'info', + data, + } ); +} + +/** + * Create a timing helper to measure operation duration. + */ +export function createTimer(): { stop: () => number } { + const start = performance.now(); + return { + stop: () => Math.round( performance.now() - start ), + }; +} + +/* eslint-enable jsdoc/require-param */ diff --git a/packages/upload-media/src/store/utils/index.ts b/packages/upload-media/src/store/utils/index.ts new file mode 100644 index 00000000000000..d6f201b05a51aa --- /dev/null +++ b/packages/upload-media/src/store/utils/index.ts @@ -0,0 +1,10 @@ +export { + vipsConvertImageFormat, + vipsCompressImage, + vipsHasTransparency, + vipsResizeImage, + vipsRotateImage, + vipsCancelOperations, +} from './vips'; + +export { logTranscode, logTranscodeComplete } from './debug-logger'; diff --git a/packages/upload-media/src/store/utils/vips.ts b/packages/upload-media/src/store/utils/vips.ts new file mode 100644 index 00000000000000..91b17a837d75e0 --- /dev/null +++ b/packages/upload-media/src/store/utils/vips.ts @@ -0,0 +1,237 @@ +/** + * External dependencies + */ +import { + vipsConvertImageFormat as convertImageFormat, + vipsCompressImage as compressImage, + vipsHasTransparency as hasTransparency, + vipsResizeImage as resizeImage, + vipsRotateImage as rotateImage, + vipsCancelOperations as cancelOperations, +} from '@wordpress/vips/worker'; + +/** + * Internal dependencies + */ +import { ImageFile } from '../../image-file'; +import { getFileBasename } from '../../utils'; +import type { ImageSizeCrop, QueueItemId } from '../types'; + +/** + * Converts an image to a different format using vips in a web worker. + * + * @param id Queue item ID. + * @param file File object. + * @param type Output mime type. + * @param quality Desired quality (0-1). + * @param interlaced Whether to use interlaced/progressive mode. + * @return Converted file. + */ +export async function vipsConvertImageFormat( + id: QueueItemId, + file: File, + type: + | 'image/jpeg' + | 'image/png' + | 'image/webp' + | 'image/avif' + | 'image/gif', + quality: number, + interlaced?: boolean +) { + const buffer = await convertImageFormat( + id, + await file.arrayBuffer(), + file.type, + type, + quality, + interlaced + ); + const ext = type.split( '/' )[ 1 ]; + const fileName = `${ getFileBasename( file.name ) }.${ ext }`; + return new File( [ new Blob( [ buffer as ArrayBuffer ] ) ], fileName, { + type, + } ); +} + +/** + * Compresses an image using vips in a web worker. + * + * @param id Queue item ID. + * @param file File object. + * @param quality Desired quality (0-1). + * @param interlaced Whether to use interlaced/progressive mode. + * @return Compressed file. + */ +export async function vipsCompressImage( + id: QueueItemId, + file: File, + quality: number, + interlaced?: boolean +) { + const buffer = await compressImage( + id, + await file.arrayBuffer(), + file.type, + quality, + interlaced + ); + return new File( + [ new Blob( [ buffer as ArrayBuffer ], { type: file.type } ) ], + file.name, + { type: file.type } + ); +} + +/** + * Checks whether an image has transparency using vips in a web worker. + * + * @param url Image URL. + * @return Whether the image has transparency. + */ +export async function vipsHasTransparency( url: string ) { + try { + const response = await fetch( url ); + if ( ! response.ok ) { + throw new Error( `Failed to fetch image: ${ response.status }` ); + } + return hasTransparency( await response.arrayBuffer() ); + } catch ( error ) { + // eslint-disable-next-line no-console + console.error( 'Error checking transparency:', error ); + return false; // Safe fallback + } +} + +/** + * Resizes an image using vips in a web worker. + * + * @param id Queue item ID. + * @param file File object. + * @param resize Resize options (width, height, crop). + * @param smartCrop Whether to use smart cropping (saliency-aware). + * @param addSuffix Whether to add dimension suffix to filename. + * @param signal Optional abort signal to cancel the operation. + * @param scaledSuffix Whether to add '-scaled' suffix instead of dimensions (for big image threshold). + * @return Resized ImageFile with dimension metadata. + */ +export async function vipsResizeImage( + id: QueueItemId, + file: File, + resize: ImageSizeCrop, + smartCrop: boolean, + addSuffix: boolean, + signal?: AbortSignal, + scaledSuffix?: boolean +) { + if ( signal?.aborted ) { + throw new Error( 'Operation aborted' ); + } + + const { buffer, width, height, originalWidth, originalHeight } = + await resizeImage( + id, + await file.arrayBuffer(), + file.type, + resize, + smartCrop + ); + + let fileName = file.name; + const wasResized = originalWidth > width || originalHeight > height; + + if ( wasResized ) { + const basename = getFileBasename( file.name ); + if ( scaledSuffix ) { + // Add '-scaled' suffix for big image threshold resizing. + // This matches WordPress core's behavior in wp_create_image_subsizes(). + fileName = file.name.replace( basename, `${ basename }-scaled` ); + } else if ( addSuffix ) { + // Add dimension suffix for thumbnails. + fileName = file.name.replace( + basename, + `${ basename }-${ width }x${ height }` + ); + } + } + + const resultFile = new ImageFile( + new File( + [ new Blob( [ buffer as ArrayBuffer ], { type: file.type } ) ], + fileName, + { + type: file.type, + } + ), + width, + height, + originalWidth, + originalHeight + ); + + return resultFile; +} + +/** + * Rotates an image based on EXIF orientation using vips in a web worker. + * + * This applies the correct rotation/flip transformation based on the EXIF + * orientation value (1-8), and adds a '-rotated' suffix to the filename. + * This matches WordPress core's behavior when rotating images based on EXIF. + * + * @param id Queue item ID. + * @param file File object. + * @param orientation EXIF orientation value (1-8). + * @param signal Optional abort signal to cancel the operation. + * @return Rotated ImageFile with updated dimensions. + */ +export async function vipsRotateImage( + id: QueueItemId, + file: File, + orientation: number, + signal?: AbortSignal +) { + if ( signal?.aborted ) { + throw new Error( 'Operation aborted' ); + } + + // If orientation is 1 (normal), no rotation needed. + if ( orientation === 1 ) { + return file; + } + + const { buffer, width, height } = await rotateImage( + id, + await file.arrayBuffer(), + file.type, + orientation + ); + + // Add '-rotated' suffix to filename, matching WordPress core behavior. + const basename = getFileBasename( file.name ); + const fileName = file.name.replace( basename, `${ basename }-rotated` ); + + const resultFile = new ImageFile( + new File( + [ new Blob( [ buffer as ArrayBuffer ], { type: file.type } ) ], + fileName, + { + type: file.type, + } + ), + width, + height + ); + + return resultFile; +} + +/** + * Cancels all ongoing image operations for the given item. + * + * @param id Queue item ID to cancel operations for. + * @return Whether any operation was cancelled. + */ +export async function vipsCancelOperations( id: QueueItemId ) { + return cancelOperations( id ); +} diff --git a/packages/upload-media/tsconfig.json b/packages/upload-media/tsconfig.json index f78b74537d78fc..20ebdb1f6791a0 100644 --- a/packages/upload-media/tsconfig.json +++ b/packages/upload-media/tsconfig.json @@ -13,6 +13,7 @@ { "path": "../i18n" }, { "path": "../preferences" }, { "path": "../private-apis" }, - { "path": "../url" } + { "path": "../url" }, + { "path": "../vips" } ] } diff --git a/packages/vips/README.md b/packages/vips/README.md index 5f3bde6b521d1b..875890e2207148 100644 --- a/packages/vips/README.md +++ b/packages/vips/README.md @@ -85,4 +85,109 @@ _Returns_ - `Promise< { buffer: ArrayBuffer | ArrayBufferLike; width: number; height: number; originalWidth: number; originalHeight: number; } >`: Processed file data plus the old and new dimensions. +### rotateImage + +Rotates an image based on EXIF orientation value. + +EXIF orientation values: 1 = Normal (no rotation needed) 2 = Flipped horizontally 3 = Rotated 180° 4 = Flipped vertically 5 = Rotated 90° CCW and flipped horizontally 6 = Rotated 90° CW 7 = Rotated 90° CW and flipped horizontally 8 = Rotated 90° CCW + +_Parameters_ + +- _id_ `ItemId`: Item ID. +- _buffer_ `ArrayBuffer`: Original file buffer. +- _type_ `string`: Mime type. +- _orientation_ `number`: EXIF orientation value (1-8). + +_Returns_ + +- `Promise< { buffer: ArrayBuffer | ArrayBufferLike; width: number; height: number; } >`: Rotated file data plus the new dimensions. + +### vipsCancelOperations + +Cancels all ongoing image operations for a given item ID. + +The onProgress callbacks check for an IDs existence in this list, killing the process if it's absent. + +_Parameters_ + +- _id_ `ItemId`: Item ID. + +_Returns_ + +- boolean Whether any operation was cancelled. + +### vipsCompressImage + +Compresses an existing image using vips. + +_Parameters_ + +- _id_ `ItemId`: Item ID. +- _buffer_ `ArrayBuffer`: Original file buffer. +- _type_ `string`: Mime type. +- _quality_ Desired quality. +- _interlaced_ Whether to use interlaced/progressive mode. Only used if the outputType supports it. + +_Returns_ + +- `Promise< ArrayBuffer | ArrayBufferLike >`: Compressed file data. + +### vipsConvertImageFormat + +Converts an image to a different format using vips. + +_Parameters_ + +- _id_ `ItemId`: Item ID. +- _buffer_ `ArrayBuffer`: Original file buffer. +- _inputType_ `string`: Input mime type. +- _outputType_ `string`: Output mime type. +- _quality_ Desired quality. +- _interlaced_ Whether to use interlaced/progressive mode. Only used if the outputType supports it. + +### vipsHasTransparency + +Determines whether an image has an alpha channel. + +_Parameters_ + +- _buffer_ `ArrayBuffer`: Original file object. + +_Returns_ + +- `Promise< boolean >`: Whether the image has an alpha channel. + +### vipsResizeImage + +Resizes an image using vips. + +_Parameters_ + +- _id_ `ItemId`: Item ID. +- _buffer_ `ArrayBuffer`: Original file buffer. +- _type_ `string`: Mime type. +- _resize_ `ImageSizeCrop`: Resize options. +- _smartCrop_ Whether to use smart cropping (i.e. saliency-aware). + +_Returns_ + +- `Promise< { buffer: ArrayBuffer | ArrayBufferLike; width: number; height: number; originalWidth: number; originalHeight: number; } >`: Processed file data plus the old and new dimensions. + +### vipsRotateImage + +Rotates an image based on EXIF orientation value. + +EXIF orientation values: 1 = Normal (no rotation needed) 2 = Flipped horizontally 3 = Rotated 180° 4 = Flipped vertically 5 = Rotated 90° CCW and flipped horizontally 6 = Rotated 90° CW 7 = Rotated 90° CW and flipped horizontally 8 = Rotated 90° CCW + +_Parameters_ + +- _id_ `ItemId`: Item ID. +- _buffer_ `ArrayBuffer`: Original file buffer. +- _type_ `string`: Mime type. +- _orientation_ `number`: EXIF orientation value (1-8). + +_Returns_ + +- `Promise< { buffer: ArrayBuffer | ArrayBufferLike; width: number; height: number; } >`: Rotated file data plus the new dimensions. + diff --git a/packages/vips/package.json b/packages/vips/package.json index 66dcb8183de8d5..7c3bee68d98502 100644 --- a/packages/vips/package.json +++ b/packages/vips/package.json @@ -48,7 +48,7 @@ }, "dependencies": { "@wordpress/worker-threads": "file:../worker-threads", - "wasm-vips": "^0.0.10" + "wasm-vips": "^0.0.16" }, "publishConfig": { "access": "public" diff --git a/packages/vips/src/index.ts b/packages/vips/src/index.ts index 812cc19081038c..710c3a600b9131 100644 --- a/packages/vips/src/index.ts +++ b/packages/vips/src/index.ts @@ -21,6 +21,43 @@ import type { } from './types'; import { supportsAnimation, supportsInterlace, supportsQuality } from './utils'; +/** + * Debug logging for VIPS operations. + * Set to true to enable debug logging. + */ +const DEBUG_ENABLED = false; + +function vipsLog( message: string, data?: Record< string, unknown > ): void { + if ( ! DEBUG_ENABLED ) { + return; + } + const timestamp = new Date().toISOString().split( 'T' )[ 1 ].slice( 0, -1 ); + // eslint-disable-next-line no-console + console.log( + `%c${ timestamp } [VIPS]%c ${ message }`, + 'color: #9C27B0; font-weight: bold;', + 'color: inherit;' + ); + if ( data && Object.keys( data ).length > 0 ) { + // eslint-disable-next-line no-console + console.log( '%c └─ Details:', 'color: #888;', data ); + } +} + +function formatBytes( bytes: number ): string { + if ( bytes === 0 ) { + return '0 Bytes'; + } + const k = 1024; + const sizes = [ 'Bytes', 'KB', 'MB', 'GB' ]; + const i = Math.floor( Math.log( bytes ) / Math.log( k ) ); + return ( + parseFloat( ( bytes / Math.pow( k, i ) ).toFixed( 2 ) ) + + ' ' + + sizes[ i ] + ); +} + interface EmscriptenModule { setAutoDeleteLater: ( autoDelete: boolean ) => void; setDelayFunction: ( fn: ( fn: () => void ) => void ) => void; @@ -40,27 +77,41 @@ async function getVips(): Promise< typeof Vips > { return vipsInstance; } - vipsInstance = await Vips( { - locateFile: ( fileName: string ) => { - // WASM files are inlined as base64 data URLs at build time, - // eliminating the need for separate file downloads and avoiding - // issues with hosts not serving WASM files with correct MIME types. - if ( fileName.endsWith( 'vips.wasm' ) ) { - return VipsModule; - } else if ( fileName.endsWith( 'vips-jxl.wasm' ) ) { - return VipsJxlModule; - } - - return fileName; - }, - preRun: ( module: EmscriptenModule ) => { - // https://github.com/kleisauke/wasm-vips/issues/13#issuecomment-1073246828 - module.setAutoDeleteLater( true ); - module.setDelayFunction( ( fn: () => void ) => { - cleanup = fn; - } ); - }, - } ); + vipsLog( 'Initializing VIPS WebAssembly module...' ); + const startTime = performance.now(); + + try { + vipsInstance = await Vips( { + // Only load JXL module, skip HEIF due to trademark issues. + // wasm-vips defaults to ["vips-jxl.wasm", "vips-heif.wasm"]. + dynamicLibraries: [ 'vips-jxl.wasm' ], + locateFile: ( fileName: string ) => { + // WASM files are inlined as base64 data URLs at build time, + // eliminating the need for separate file downloads and avoiding + // issues with hosts not serving WASM files with correct MIME types. + if ( fileName.endsWith( 'vips.wasm' ) ) { + return VipsModule; + } else if ( fileName.endsWith( 'vips-jxl.wasm' ) ) { + return VipsJxlModule; + } + return fileName; + }, + preRun: ( module: EmscriptenModule ) => { + // https://github.com/kleisauke/wasm-vips/issues/13#issuecomment-1073246828 + module.setAutoDeleteLater( true ); + module.setDelayFunction( ( fn: () => void ) => { + cleanup = fn; + } ); + }, + } ); + } catch ( error ) { + // eslint-disable-next-line no-console + console.error( '[VIPS] Failed to initialize VIPS:', error ); + throw error; + } + + const duration = Math.round( performance.now() - startTime ); + vipsLog( `VIPS WebAssembly module initialized`, { durationMs: duration } ); return vipsInstance; } @@ -82,7 +133,12 @@ const inProgressOperations = new Set< ItemId >(); * @return boolean Whether any operation was cancelled. */ export async function cancelOperations( id: ItemId ) { - return inProgressOperations.delete( id ); + const hadOperation = inProgressOperations.has( id ); + const result = inProgressOperations.delete( id ); + if ( hadOperation ) { + vipsLog( `Cancelled operations`, { itemId: id } ); + } + return result; } /** @@ -106,6 +162,16 @@ export async function convertImageFormat( ): Promise< ArrayBuffer | ArrayBufferLike > { const ext = outputType.split( '/' )[ 1 ]; + vipsLog( `Converting image format`, { + itemId: id, + inputType, + outputType, + inputSize: formatBytes( buffer.byteLength ), + quality: Math.round( quality * 100 ) + '%', + interlaced, + } ); + const startTime = performance.now(); + inProgressOperations.add( id ); let strOptions = ''; @@ -142,9 +208,28 @@ export async function convertImageFormat( saveOptions.effort = 2; } + // Apply MozJPEG optimizations for JPEG output. + // optimize_coding enables optimal Huffman coding tables. + // quant_table 3 uses improved quantization tables similar to MozJPEG. + // These settings typically provide 10-15% smaller file sizes. + if ( 'image/jpeg' === outputType ) { + ( saveOptions as SaveOptions< 'image/jpeg' > ).optimize_coding = true; + ( saveOptions as SaveOptions< 'image/jpeg' > ).quant_table = 3; + } + const outBuffer = image.writeToBuffer( `.${ ext }`, saveOptions ); const result = outBuffer.buffer; + const duration = Math.round( performance.now() - startTime ); + vipsLog( `Image format conversion completed`, { + itemId: id, + inputType, + outputType, + inputSize: formatBytes( buffer.byteLength ), + outputSize: formatBytes( result.byteLength ), + durationMs: duration, + } ); + cleanup?.(); return result; @@ -196,6 +281,17 @@ export async function resizeImage( } > { const ext = type.split( '/' )[ 1 ]; + vipsLog( `Resizing image`, { + itemId: id, + type, + inputSize: formatBytes( buffer.byteLength ), + targetWidth: resize.width, + targetHeight: resize.height, + crop: resize.crop || false, + smartCrop, + } ); + const startTime = performance.now(); + inProgressOperations.add( id ); const vips = await getVips(); @@ -322,6 +418,117 @@ export async function resizeImage( originalHeight: pageHeight, }; + const duration = Math.round( performance.now() - startTime ); + vipsLog( `Image resize completed`, { + itemId: id, + originalDimensions: `${ width }x${ pageHeight }`, + newDimensions: `${ result.width }x${ result.height }`, + inputSize: formatBytes( buffer.byteLength ), + outputSize: formatBytes( result.buffer.byteLength ), + durationMs: duration, + } ); + + // Only call after `image` is no longer being used. + cleanup?.(); + + return result; +} + +/** + * Rotates an image based on EXIF orientation value. + * + * EXIF orientation values: + * 1 = Normal (no rotation needed) + * 2 = Flipped horizontally + * 3 = Rotated 180° + * 4 = Flipped vertically + * 5 = Rotated 90° CCW and flipped horizontally + * 6 = Rotated 90° CW + * 7 = Rotated 90° CW and flipped horizontally + * 8 = Rotated 90° CCW + * + * @param id Item ID. + * @param buffer Original file buffer. + * @param type Mime type. + * @param orientation EXIF orientation value (1-8). + * @return Rotated file data plus the new dimensions. + */ +export async function rotateImage( + id: ItemId, + buffer: ArrayBuffer, + type: string, + orientation: number +): Promise< { + buffer: ArrayBuffer | ArrayBufferLike; + width: number; + height: number; +} > { + const ext = type.split( '/' )[ 1 ]; + + inProgressOperations.add( id ); + + const vips = await getVips(); + + let strOptions = ''; + const loadOptions: LoadOptions< typeof type > = {}; + + // To ensure all frames are loaded in case the image is animated. + if ( supportsAnimation( type ) ) { + strOptions = '[n=-1]'; + ( loadOptions as LoadOptions< typeof type > ).n = -1; + } + + let image = vips.Image.newFromBuffer( buffer, strOptions, loadOptions ); + + image.onProgress = () => { + if ( ! inProgressOperations.has( id ) ) { + image.kill = true; + } + }; + + // Apply transformation based on EXIF orientation. + // See: https://exiftool.org/TagNames/EXIF.html#:~:text=0x0112,Orientation + switch ( orientation ) { + case 2: + // Flipped horizontally + image = image.flipHor(); + break; + case 3: + // Rotated 180° + image = image.rot180(); + break; + case 4: + // Flipped vertically + image = image.flipVer(); + break; + case 5: + // Rotated 90° CCW and flipped horizontally + image = image.rot270().flipHor(); + break; + case 6: + // Rotated 90° CW + image = image.rot90(); + break; + case 7: + // Rotated 90° CW and flipped horizontally + image = image.rot90().flipHor(); + break; + case 8: + // Rotated 90° CCW + image = image.rot270(); + break; + // case 1 and default: no transformation needed + } + + const saveOptions: SaveOptions< typeof type > = {}; + const outBuffer = image.writeToBuffer( `.${ ext }`, saveOptions ); + + const result = { + buffer: outBuffer.buffer, + width: image.width, + height: image.pageHeight, + }; + // Only call after `image` is no longer being used. cleanup?.(); @@ -345,3 +552,14 @@ export async function hasTransparency( return hasAlpha; } + +// Re-export with vips prefix for worker module compatibility. +// The worker loader expects these prefixed names. +export { + convertImageFormat as vipsConvertImageFormat, + compressImage as vipsCompressImage, + resizeImage as vipsResizeImage, + rotateImage as vipsRotateImage, + hasTransparency as vipsHasTransparency, + cancelOperations as vipsCancelOperations, +}; diff --git a/packages/vips/src/types.ts b/packages/vips/src/types.ts index d0978ff7979634..4b5b974d881d9e 100644 --- a/packages/vips/src/types.ts +++ b/packages/vips/src/types.ts @@ -123,6 +123,22 @@ export interface SaveOptions< T extends string > { * it is most relevant for AVIF, as it is slow by default. */ effort?: number; + /** + * Compute optimal Huffman coding tables (JPEG only). + * This is a MozJPEG optimization that typically improves compression. + */ + optimize_coding?: T extends 'image/jpeg' ? boolean : never; + /** + * Quantization table index (JPEG only). + * Use 3 for MozJPEG's improved quantization tables. + * 0 = JPEG Annex K (default) + * 1 = Flat + * 2 = Custom (from tune setting) + * 3 = ImageMagick tables (similar to MozJPEG) + * 4 = Custom (from tune setting) + * 5 = MS pattern + */ + quant_table?: T extends 'image/jpeg' ? number : never; } export interface ThumbnailOptions { diff --git a/packages/vips/src/vips-worker.ts b/packages/vips/src/vips-worker.ts index 559466e572c61d..e11a40ac4b961c 100644 --- a/packages/vips/src/vips-worker.ts +++ b/packages/vips/src/vips-worker.ts @@ -43,7 +43,7 @@ function getWorkerAPI(): Remote< WorkerAPI > { type: 'application/javascript', } ); workerBlobUrl = URL.createObjectURL( blob ); - worker = new Worker( workerBlobUrl ); + worker = new Worker( workerBlobUrl, { type: 'module' } ); workerAPI = wrap< WorkerAPI >( worker ); } return workerAPI; @@ -140,6 +140,29 @@ export async function vipsHasTransparency( return api.hasTransparency( buffer ); } +/** + * Rotates an image based on EXIF orientation using vips in a worker. + * + * @param id Item ID. + * @param buffer Original file buffer. + * @param type Mime type. + * @param orientation EXIF orientation value (1-8). + * @return Rotated file data plus the new dimensions. + */ +export async function vipsRotateImage( + id: ItemId, + buffer: ArrayBuffer, + type: string, + orientation: number +): Promise< { + buffer: ArrayBuffer | ArrayBufferLike; + width: number; + height: number; +} > { + const api = getWorkerAPI(); + return api.rotateImage( id, buffer, type, orientation ); +} + /** * Cancels all ongoing image operations for a given item ID. * diff --git a/packages/vips/src/worker.ts b/packages/vips/src/worker.ts index 15bf5f28a159c3..2fad366825604f 100644 --- a/packages/vips/src/worker.ts +++ b/packages/vips/src/worker.ts @@ -19,6 +19,7 @@ import { convertImageFormat, compressImage, resizeImage, + rotateImage, hasTransparency, } from './index'; @@ -30,6 +31,7 @@ const api = { convertImageFormat, compressImage, resizeImage, + rotateImage, hasTransparency, }; diff --git a/packages/worker-threads/package.json b/packages/worker-threads/package.json index a6fb0fba5dae51..165c75d9c4c2b0 100644 --- a/packages/worker-threads/package.json +++ b/packages/worker-threads/package.json @@ -1,7 +1,7 @@ { "name": "@wordpress/worker-threads", "version": "1.0.0-prerelease", - "private": true, + "private": false, "description": "Utilities for type-safe Web Worker communication with RPC.", "author": "The WordPress Contributors", "license": "GPL-2.0-or-later", diff --git a/packages/worker-threads/src/main-thread.ts b/packages/worker-threads/src/main-thread.ts index 42927165ef2881..b27d41b3cc4bfe 100644 --- a/packages/worker-threads/src/main-thread.ts +++ b/packages/worker-threads/src/main-thread.ts @@ -13,6 +13,29 @@ import { */ import { WORKER_SYMBOL, type Remote, type WithWorker } from './types'; +/** + * Debug logging for client side media. + * Set to true to enable debug logging. + */ +const DEBUG_ENABLED = false; + +function workerLog( message: string, data?: Record< string, unknown > ): void { + if ( ! DEBUG_ENABLED ) { + return; + } + const timestamp = new Date().toISOString().split( 'T' )[ 1 ].slice( 0, -1 ); + // eslint-disable-next-line no-console + console.log( + `%c${ timestamp } [WORKER-RPC]%c ${ message }`, + 'color: #FF5722; font-weight: bold;', + 'color: inherit;' + ); + if ( data && Object.keys( data ).length > 0 ) { + // eslint-disable-next-line no-console + console.log( '%c └─ Details:', 'color: #888;', data ); + } +} + /** * Adapter for injecting (main thread calling worker). */ @@ -59,6 +82,8 @@ const remoteWorkers = new WeakMap< object, Worker >(); * @return A proxy object with all exposed methods as async functions. */ export function wrap< T extends object >( worker: Worker ): Remote< T > { + workerLog( 'Wrapping worker for RPC communication' ); + // Create the inject function using defineProxy with an empty object // (the actual implementation is on the worker side). const [ , inject ] = defineProxy( () => ( {} ) as T, { @@ -115,6 +140,8 @@ export function terminate( remote: Remote< unknown > ): void { return; } + workerLog( 'Terminating worker' ); + // Clean up the worker reference. remoteWorkers.delete( remote as object ); diff --git a/packages/wp-build/lib/worker-build.mjs b/packages/wp-build/lib/worker-build.mjs index 3efff5db246e95..aaddd3135ac1b5 100644 --- a/packages/wp-build/lib/worker-build.mjs +++ b/packages/wp-build/lib/worker-build.mjs @@ -14,6 +14,40 @@ import { readFile, writeFile, access } from 'fs/promises'; import path from 'path'; import esbuild from 'esbuild'; +/** + * Creates an esbuild plugin to force wasm-vips to use its CommonJS version. + * + * The ES module version (vips-es6.js) uses import.meta.url which fails + * when loaded in a Blob URL Worker context. The CommonJS version (vips.js) + * doesn't have this issue. + * + * This plugin intercepts the resolved vips-es6.js path and redirects it + * to vips.js. It must run after esbuild's default resolution. + * + * @return {Object} The esbuild plugin. + */ +function createWasmVipsCommonJsPlugin() { + return { + name: 'wasm-vips-commonjs', + setup( build ) { + // Intercept vips-es6.js and redirect to vips.js + build.onLoad( { filter: /vips-es6\.js$/ }, ( args ) => { + // Replace the ES6 module with a re-export from the CommonJS version + const vipsJsPath = args.path.replace( + 'vips-es6.js', + 'vips.js' + ); + return { + contents: `export { default } from ${ JSON.stringify( + vipsJsPath + ) };`, + loader: 'js', + }; + } ); + }, + }; +} + /** * Generate placeholder worker-code.ts for packages with wpWorkers. * @@ -98,7 +132,12 @@ export async function buildWorkers( sourcemap: true, // Bundle everything - workers need to be self-contained. external: [], - plugins: [ wasmInlinePlugin ], + // Plugin redirects wasm-vips ES6 to CommonJS to avoid + // import.meta.url issues in Blob URL Worker context. + plugins: [ + wasmInlinePlugin, + createWasmVipsCommonJsPlugin(), + ], define: { 'process.env.NODE_ENV': JSON.stringify( process.env.NODE_ENV || 'production' diff --git a/packages/wp-build/templates/page-wp-admin.php.template b/packages/wp-build/templates/page-wp-admin.php.template index 558d57f7b79cd7..970954d34330af 100644 --- a/packages/wp-build/templates/page-wp-admin.php.template +++ b/packages/wp-build/templates/page-wp-admin.php.template @@ -96,8 +96,9 @@ if ( ! function_exists( '{{PREFIX}}_{{PAGE_SLUG_UNDERSCORE}}_wp_admin_preload_da */ function {{PREFIX}}_{{PAGE_SLUG_UNDERSCORE}}_wp_admin_preload_data() { // Define paths to preload - same for all pages + // Please also change packages/core-data/src/entities.js when changing this. $preload_paths = array( - '/?_fields=description,gmt_offset,home,name,site_icon,site_icon_url,site_logo,timezone_string,url,page_for_posts,page_on_front,show_on_front', + '/?_fields=description,gmt_offset,home,image_sizes,image_size_threshold,image_output_formats,jpeg_interlaced,png_interlaced,gif_interlaced,name,site_icon,site_icon_url,site_logo,timezone_string,url,page_for_posts,page_on_front,show_on_front', array( '/wp/v2/settings', 'OPTIONS' ), ); diff --git a/packages/wp-build/templates/page.php.template b/packages/wp-build/templates/page.php.template index 2231885cd700f5..af675f7f2e101a 100644 --- a/packages/wp-build/templates/page.php.template +++ b/packages/wp-build/templates/page.php.template @@ -97,8 +97,9 @@ if ( ! function_exists( '{{PREFIX}}_{{PAGE_SLUG_UNDERSCORE}}_preload_data' ) ) { */ function {{PREFIX}}_{{PAGE_SLUG_UNDERSCORE}}_preload_data() { // Define paths to preload - same for all pages + // Please also change packages/core-data/src/entities.js when changing this. $preload_paths = array( - '/?_fields=description,gmt_offset,home,name,site_icon,site_icon_url,site_logo,timezone_string,url,page_for_posts,page_on_front,show_on_front', + '/?_fields=description,gmt_offset,home,image_sizes,image_size_threshold,image_output_formats,jpeg_interlaced,png_interlaced,gif_interlaced,name,site_icon,site_icon_url,site_logo,timezone_string,url,page_for_posts,page_on_front,show_on_front', array( '/wp/v2/settings', 'OPTIONS' ), ); diff --git a/storybook/main.ts b/storybook/main.ts index 3d16f20948e056..a11f7b2fc5186a 100644 --- a/storybook/main.ts +++ b/storybook/main.ts @@ -95,6 +95,61 @@ const config: StorybookConfig = { } ); }, }, + // Stub the vips and wasm-vips packages for Storybook since they use WASM modules that Vite can't handle. + { + name: 'stub-vips', + enforce: 'pre', + resolveId( id: string ) { + // Stub @wordpress/vips imports. + if ( + id === '@wordpress/vips' || + id.startsWith( '@wordpress/vips/' ) + ) { + return '\0virtual:vips-stub'; + } + // Stub wasm-vips imports. + if ( + id === 'wasm-vips' || + id.startsWith( 'wasm-vips/' ) + ) { + return '\0virtual:wasm-vips-stub'; + } + // Stub WASM file imports. + if ( id.endsWith( '.wasm' ) ) { + return '\0virtual:wasm-stub'; + } + return null; + }, + load( id: string ) { + if ( id === '\0virtual:vips-stub' ) { + // Return a stub module with no-op exports for Storybook. + return ` + export const setLocation = () => {}; + export const cancelOperations = async () => false; + export const convertImageFormat = async () => new ArrayBuffer(0); + export const compressImage = async () => new ArrayBuffer(0); + export const resizeImage = async () => ({ buffer: new ArrayBuffer(0), width: 0, height: 0, originalWidth: 0, originalHeight: 0 }); + export const rotateImage = async () => ({ buffer: new ArrayBuffer(0), width: 0, height: 0 }); + export const hasTransparency = async () => false; + export const vipsConvertImageFormat = convertImageFormat; + export const vipsCompressImage = compressImage; + export const vipsResizeImage = resizeImage; + export const vipsRotateImage = rotateImage; + export const vipsHasTransparency = hasTransparency; + export const vipsCancelOperations = cancelOperations; + `; + } + if ( id === '\0virtual:wasm-vips-stub' ) { + // Return a stub for wasm-vips default export. + return `export default () => Promise.resolve({});`; + } + if ( id === '\0virtual:wasm-stub' ) { + // Return empty string for WASM files. + return `export default '';`; + } + return null; + }, + }, ], build: { /** 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 new file mode 100644 index 00000000000000..f54cae8bbcdd9b --- /dev/null +++ b/test/e2e/specs/editor/various/big-image-size-threshold.spec.js @@ -0,0 +1,258 @@ +/** + * External dependencies + */ +const path = require( 'path' ); +const fs = require( 'fs/promises' ); +const os = require( 'os' ); +const { v4: uuid } = require( 'uuid' ); + +/** + * WordPress dependencies + */ +const { test, expect } = require( '@wordpress/e2e-test-utils-playwright' ); + +/** + * @typedef {import('@playwright/test').Page} Page + */ + +test.use( { + imageBlockUtils: async ( { page }, use ) => { + await use( new ImageBlockUtils( { page } ) ); + }, +} ); + +test.describe( 'Big image size threshold', () => { + test.beforeAll( async ( { requestUtils } ) => { + await requestUtils.deleteAllMedia(); + } ); + + test.beforeEach( async ( { admin } ) => { + await admin.createNewPost(); + } ); + + test.afterEach( async ( { requestUtils } ) => { + await requestUtils.deleteAllMedia(); + } ); + + test( 'should scale down images larger than the threshold', 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 + ); + // eslint-disable-next-line playwright/no-skipped-test + test.skip( + ! isCrossOriginIsolated, + 'Cross-origin isolation headers not configured on server' + ); + + // Verify the big image size threshold setting is available. + const threshold = await page.evaluate( () => + window.wp.data + .select( 'core' ) + .getEntityRecord( 'root', '__unstableBase' ) + ); + expect( threshold?.image_size_threshold ).toBeDefined(); + + 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 (3200x2400) that exceeds the default threshold (2560). + await imageBlockUtils.upload( + imageBlock.locator( 'data-testid=form-file-upload-input' ), + '3200x2400_e2e_test_image_responsive_lightbox.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 }`, + } ); + + // When client-side thumbnail generation is enabled and cross-origin isolation + // is available, the image should be scaled down and have the -scaled suffix. + if ( media.source_url.includes( '-scaled' ) ) { + // Verify the image was scaled down. + expect( media.media_details.width ).toBeLessThanOrEqual( 2560 ); + expect( media.media_details.height ).toBeLessThanOrEqual( + 2560 + ); + expect( media.source_url ).toContain( '-scaled' ); + + // Verify original_image is preserved in metadata. + // WordPress core stores the original filename when scaling. + expect( media.media_details.original_image ).toBeDefined(); + + // Verify thumbnails were generated. + // WordPress core generates thumbnails from the original image for quality. + 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 ); + } + } else { + // If server-side processing happened, the image should still be + // scaled down to the threshold. + expect( media.media_details.width ).toBeLessThanOrEqual( 2560 ); + expect( media.media_details.height ).toBeLessThanOrEqual( + 2560 + ); + } + } + } ); + + test( 'should not scale images smaller than the threshold', 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 small image (1024x768) that is below the default threshold (2560). + await imageBlockUtils.upload( + imageBlock.locator( 'data-testid=form-file-upload-input' ), + '1024x768_e2e_test_image_size.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 ); + } + } ); +} ); + +class ImageBlockUtils { + constructor( { page } ) { + /** @type {Page} */ + this.page = page; + this.basePath = path.join( __dirname, '..', '..', '..', 'assets' ); + + this.TEST_IMAGE_FILE_PATH = path.join( + this.basePath, + '10x10_e2e_test_image_z9T8jK.png' + ); + } + + async upload( inputElement, customFile = null ) { + const tmpDirectory = await fs.mkdtemp( + path.join( os.tmpdir(), 'gutenberg-test-image-' ) + ); + const fileName = uuid(); + const extension = customFile ? path.extname( customFile ) : '.png'; + const tmpFileName = path.join( tmpDirectory, fileName + extension ); + const filePath = customFile + ? path.join( this.basePath, customFile ) + : this.TEST_IMAGE_FILE_PATH; + await fs.copyFile( filePath, tmpFileName ); + + await inputElement.setInputFiles( tmpFileName ); + + return fileName; + } +} diff --git a/test/unit/config/vips-worker-code-stub.js b/test/unit/config/vips-worker-code-stub.js new file mode 100644 index 00000000000000..c737b632aac215 --- /dev/null +++ b/test/unit/config/vips-worker-code-stub.js @@ -0,0 +1,28 @@ +/** + * Stub for the @wordpress/vips/worker module. + * + * The real vips-worker.ts imports from worker-code.ts, which is auto-generated + * during the full build process and is gitignored. Since unit tests don't run + * a full build, we provide this stub with mock implementations. + * + * Tests that need to customize the mock behavior can use jest.mock() in their + * test files to override these defaults. + */ + +const vipsConvertImageFormat = jest.fn(); +const vipsCompressImage = jest.fn(); +const vipsHasTransparency = jest.fn(); +const vipsResizeImage = jest.fn(); +const vipsRotateImage = jest.fn(); +const vipsCancelOperations = jest.fn(); +const terminateVipsWorker = jest.fn(); + +module.exports = { + vipsConvertImageFormat, + vipsCompressImage, + vipsHasTransparency, + vipsResizeImage, + vipsRotateImage, + vipsCancelOperations, + terminateVipsWorker, +}; diff --git a/test/unit/jest.config.js b/test/unit/jest.config.js index 3ea5aa3cc83b88..da23dc791722ee 100644 --- a/test/unit/jest.config.js +++ b/test/unit/jest.config.js @@ -14,9 +14,12 @@ process.env.TZ = 'UTC'; module.exports = { rootDir: '../../', moduleNameMapper: { + // Mock @wordpress/vips/worker before the general pattern so it doesn't try to load the real file. + // The worker-code.ts file is auto-generated during full builds and is gitignored. + '@wordpress/vips/worker': + '/test/unit/config/vips-worker-code-stub.js', [ `@wordpress\\/(${ transpiledPackageNames.join( '|' ) })$` ]: 'packages/$1/src', - '@wordpress/vips/worker': '/packages/vips/src/vips-worker.ts', '@wordpress/theme/design-tokens.js': '/packages/theme/src/prebuilt/js/design-tokens.mjs', '.+\\.wasm$': '/test/unit/config/wasm-stub.js',