diff --git a/package-lock.json b/package-lock.json
index 706ceaa6987a52..4ea4170f45c63b 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -59804,6 +59804,7 @@
"version": "0.31.0",
"license": "GPL-2.0-or-later",
"dependencies": {
+ "@react-spring/web": "^9.4.5",
"@wordpress/api-fetch": "file:../api-fetch",
"@wordpress/base-styles": "file:../base-styles",
"@wordpress/blob": "file:../blob",
diff --git a/packages/fields/package.json b/packages/fields/package.json
index d37ed3de2997c9..722520d6085789 100644
--- a/packages/fields/package.json
+++ b/packages/fields/package.json
@@ -47,6 +47,7 @@
"src/**/*.scss"
],
"dependencies": {
+ "@react-spring/web": "^9.4.5",
"@wordpress/api-fetch": "file:../api-fetch",
"@wordpress/base-styles": "file:../base-styles",
"@wordpress/blob": "file:../blob",
diff --git a/packages/fields/src/components/media-edit/index.tsx b/packages/fields/src/components/media-edit/index.tsx
index 862eac92b74407..e73e8788df4397 100644
--- a/packages/fields/src/components/media-edit/index.tsx
+++ b/packages/fields/src/components/media-edit/index.tsx
@@ -14,6 +14,7 @@ import {
__experimentalText as Text,
__experimentalTruncate as Truncate,
__experimentalVStack as VStack,
+ __experimentalHStack as HStack,
BaseControl,
Tooltip,
VisuallyHidden,
@@ -28,7 +29,7 @@ import {
useRef,
useState,
} from '@wordpress/element';
-import { __ } from '@wordpress/i18n';
+import { __, sprintf } from '@wordpress/i18n';
import {
archive,
audio,
@@ -36,6 +37,10 @@ import {
file,
closeSmall,
error as errorIcon,
+ chevronUp,
+ chevronDown,
+ chevronLeft,
+ chevronRight,
} from '@wordpress/icons';
import {
MediaUpload,
@@ -49,9 +54,27 @@ import { store as noticesStore } from '@wordpress/notices';
*/
import { unlock } from '../../lock-unlock';
import type { MediaEditProps } from '../../types';
+import useMovingAnimation from './use-moving-animation';
const { MediaUploadModal } = unlock( mediaUtilsPrivateApis );
+function AnimatedMediaItem( {
+ children,
+ index,
+ className,
+}: {
+ children: React.ReactNode;
+ index: number;
+ className?: string;
+} ) {
+ const ref = useMovingAnimation( index );
+ return (
+
+ { children }
+
+ );
+}
+
type BlobItem = {
id: string;
source_url: string;
@@ -59,6 +82,13 @@ type BlobItem = {
alt_text?: string;
};
+function normalizeValue( value: number | number[] | undefined ): number[] {
+ if ( Array.isArray( value ) ) {
+ return value;
+ }
+ return value ? [ value ] : [];
+}
+
/**
* Conditional Media component that uses MediaUploadModal when experiment is enabled,
* otherwise falls back to media-utils MediaUpload.
@@ -122,7 +152,9 @@ function MediaPickerButton( {
const isBlob = attachment && isBlobURL( attachment.source_url );
const mediaPickerButton = (
{
@@ -160,7 +192,11 @@ function MediaPickerButton( {
if ( ! showTooltip ) {
return mediaPickerButton;
}
- return
{ mediaPickerButton };
+ return (
+
+ { mediaPickerButton }
+
+ );
}
const archiveMimeTypes = [
@@ -195,6 +231,54 @@ function MediaEditPlaceholder( props: {
);
}
+function MoveButtons( {
+ itemId,
+ index,
+ totalItems,
+ isUploading,
+ moveItem,
+ orientation = 'vertical',
+}: {
+ itemId: number;
+ index: number;
+ totalItems: number;
+ isUploading: boolean;
+ moveItem: ( id: number, direction: 'up' | 'down' ) => void;
+ orientation?: 'vertical' | 'horizontal';
+} ) {
+ const isHorizontal = orientation === 'horizontal';
+ return (
+ <>
+
) }
{ ( multiple || ! allItems?.length ) && (
{
+ setTargetItemId( undefined );
+ open();
+ } }
label={ addButtonLabel }
onFilesDrop={ onFilesDrop }
isUploading={ isUploading }
@@ -477,18 +624,68 @@ export default function MediaEdit< Item >( {
if ( ! value ) {
return null;
}
- const normalizedValue = Array.isArray( value ) ? value : [ value ];
+ const normalizedValue = normalizeValue( value );
+ // Sorted IDs ensure stable cache key, avoiding
+ // unnecessary new requests on reorder.
+ const sortedIds = [ ...normalizedValue ].sort( ( a, b ) => a - b );
const { getEntityRecords } = select( coreStore );
return getEntityRecords( 'postType', 'attachment', {
- include: normalizedValue,
+ include: sortedIds,
} ) as Attachment< 'view' >[] | null;
},
[ value ]
);
+ // Keep previous attachments during null transitions. When value changes,
+ // useSelect briefly returns null while the new query resolves. For pure
+ // reorders (same IDs), we fall back to the cached list to avoid a visual
+ // flash in compact mode. For replacements/uploads (new IDs not in cache),
+ // we let attachments be null as normal.
+ const stableAttachmentsRef = useRef< Attachment< 'view' >[] | null >(
+ null
+ );
+ if ( attachments !== null ) {
+ stableAttachmentsRef.current = attachments;
+ }
+ let stableAttachments = attachments;
+ if ( attachments === null && stableAttachmentsRef.current && value ) {
+ const stableIds = new Set(
+ stableAttachmentsRef.current.map( ( a ) => a.id )
+ );
+ if ( normalizeValue( value ).every( ( id ) => stableIds.has( id ) ) ) {
+ stableAttachments = stableAttachmentsRef.current;
+ }
+ }
+ // Reorder attachments to match value order.
+ const orderedAttachments = useMemo( () => {
+ if ( ! stableAttachments ) {
+ return null;
+ }
+ const normalizedValue = normalizeValue( value );
+ const attachmentMap = new Map(
+ stableAttachments.map( ( a ) => [ a.id, a ] )
+ );
+ return normalizedValue
+ .map( ( id ) => attachmentMap.get( id ) )
+ .filter( ( a ): a is Attachment< 'view' > => a !== undefined );
+ }, [ stableAttachments, value ] );
const { createErrorNotice } = useDispatch( noticesStore );
+ const { receiveEntityRecords } = useDispatch( coreStore );
// Support one upload action at a time for now.
- const [ replacementId, setReplacementId ] = useState< number >();
+ const [ targetItemId, setTargetItemId ] = useState< number >();
+ // Deferred open: the legacy class-based MediaUpload reads props
+ // imperatively when `open()` is called, so calling it in the same
+ // handler as `setTargetItemId()` would open the modal with stale
+ // `value`/`multiple` props. Setting a pending flag defers the open
+ // until after the next render when props are up to date.
+ const openModalRef = useRef< ( () => void ) | null >( null );
+ const [ pendingOpen, setPendingOpen ] = useState( false );
const [ blobs, setBlobs ] = useState< string[] >( [] );
+ useEffect( () => {
+ if ( pendingOpen ) {
+ setPendingOpen( false );
+ openModalRef.current?.();
+ }
+ }, [ pendingOpen ] );
const onChangeControl = useCallback(
( newValue: number | number[] | undefined ) =>
onChange( field.setValue( { item: data, value: newValue } ) ),
@@ -496,7 +693,7 @@ export default function MediaEdit< Item >( {
);
const removeItem = useCallback(
( itemId: number ) => {
- const currentIds = Array.isArray( value ) ? value : [ value ];
+ const currentIds = normalizeValue( value );
const newIds = currentIds.filter( ( id ) => id !== itemId );
// Mark as touched to immediately show any validation error.
setIsTouched( true );
@@ -504,65 +701,88 @@ export default function MediaEdit< Item >( {
},
[ value, onChangeControl ]
);
+ const moveItem = useCallback(
+ ( itemId: number, direction: 'up' | 'down' ) => {
+ if ( ! orderedAttachments ) {
+ return;
+ }
+ const currentIds = orderedAttachments.map( ( a ) => a.id );
+ const index = currentIds.indexOf( itemId );
+ const newIndex = direction === 'up' ? index - 1 : index + 1;
+ [ currentIds[ index ], currentIds[ newIndex ] ] = [
+ currentIds[ newIndex ],
+ currentIds[ index ],
+ ];
+ onChangeControl( currentIds );
+ },
+ [ orderedAttachments, onChangeControl ]
+ );
const onFilesDrop = useCallback(
- ( files: File[], _replacementId?: number ) => {
+ ( files: File[], _targetItemId?: number ) => {
+ setTargetItemId( _targetItemId );
uploadMedia( {
allowedTypes: allowedTypes?.length ? allowedTypes : undefined,
filesList: files,
onFileChange( uploadedMedia: any[] ) {
- setReplacementId( _replacementId );
- const { blobItems, uploadedItems } = uploadedMedia.reduce(
- ( accumulator, item ) => {
- if ( isBlobURL( item.url ) ) {
- accumulator.blobItems.push( item.url );
- } else {
- accumulator.uploadedItems.push( item.id );
- }
- return accumulator;
- },
- {
- blobItems: [] as string[],
- uploadedItems: [] as number[],
- }
- );
- setBlobs( blobItems );
- // If all uploads are complete reset the replacementId.
- if ( uploadedItems.length === uploadedMedia.length ) {
- setReplacementId( undefined );
- }
- if ( ! uploadedItems.length ) {
+ const blobUrls = uploadedMedia
+ .filter( ( item ) => isBlobURL( item.url ) )
+ .map( ( item ) => item.url );
+ setBlobs( blobUrls );
+ // Wait for all uploads to complete before updating value.
+ if ( !! blobUrls.length ) {
return;
}
+ // `uploadMedia` creates attachments via `apiFetch`
+ // outside the core-data store, so invalidate
+ // all attachment queries to keep them fresh for
+ // other components that rely on core-data.
+ receiveEntityRecords(
+ 'postType',
+ 'attachment',
+ [],
+ undefined,
+ true
+ );
+ const uploadedIds = uploadedMedia.map(
+ ( item ) => item.id
+ );
if ( ! multiple ) {
- onChangeControl( uploadedItems[ 0 ] );
+ onChangeControl( uploadedIds[ 0 ] );
+ setTargetItemId( undefined );
return;
}
- if ( ! value ) {
- onChangeControl( uploadedItems );
- return;
+ const currentValue = normalizeValue( value );
+ // Dropped on placeholder: append new items.
+ if ( _targetItemId === undefined ) {
+ onChangeControl( [ ...currentValue, ...uploadedIds ] );
+ } else {
+ // Dropped on existing item: insert at that position.
+ const newValue = [ ...currentValue ];
+ newValue.splice(
+ currentValue.indexOf( _targetItemId ),
+ 1,
+ ...uploadedIds
+ );
+ onChangeControl( newValue );
}
- const normalizedValue = Array.isArray( value )
- ? value
- : [ value ];
- const newIds = [
- ...( _replacementId
- ? normalizedValue.filter(
- ( id: any ) => id !== _replacementId
- )
- : normalizedValue ),
- ...uploadedItems,
- ];
- onChangeControl( newIds );
+ setTargetItemId( undefined );
},
onError( error: Error ) {
- setReplacementId( undefined );
+ setTargetItemId( undefined );
setBlobs( [] );
createErrorNotice( error.message, { type: 'snackbar' } );
},
multiple: !! multiple,
} );
},
- [ allowedTypes, value, multiple, createErrorNotice, onChangeControl ]
+ [
+ allowedTypes,
+ value,
+ multiple,
+ createErrorNotice,
+ onChangeControl,
+ receiveEntityRecords,
+ ]
);
const addButtonLabel =
field.placeholder ||
@@ -570,31 +790,27 @@ export default function MediaEdit< Item >( {
// Merge real attachments with any existing blob items that are being uploaded.
const allItems: Array< MediaEditAttachment > | null = useMemo( () => {
if ( ! blobs.length ) {
- return attachments;
+ return orderedAttachments;
}
const items: Array< MediaEditAttachment > = [
- ...( attachments || [] ),
+ ...( orderedAttachments || [] ),
];
const blobItems = blobs.map( ( url ) => ( {
id: url,
source_url: url,
mime_type: getBlobTypeByURL( url ),
} ) );
- const replacementIndex = items.findIndex(
- ( a ) => a.id === replacementId
- );
- // Place blobs at the replacement index, when files
- // dropped in existing media item.
- if ( replacementIndex !== -1 ) {
- return [
- ...items.slice( 0, replacementIndex ),
- ...blobItems,
- ...items.slice( replacementIndex + 1 ),
- ];
+ if ( targetItemId !== undefined ) {
+ // When files are dropped in existing media item, place the blobs at that item.
+ const targetIndex = items.findIndex(
+ ( a ) => a.id === targetItemId
+ );
+ items.splice( targetIndex, 1, ...blobItems );
+ } else {
+ items.push( ...blobItems );
}
- items.push( ...blobItems );
return items;
- }, [ attachments, replacementId, blobs ] );
+ }, [ orderedAttachments, targetItemId, blobs ] );
useEffect( () => {
if ( ! isTouched ) {
return;
@@ -614,7 +830,7 @@ export default function MediaEdit< Item >( {
customValidityResult.message || __( 'Invalid' )
);
} else {
- input.setCustomValidity( '' ); // Clear validity
+ input.setCustomValidity( '' ); // Clear validity.
}
} else {
// Clear any previous validation.
@@ -641,20 +857,56 @@ export default function MediaEdit< Item >( {