From 4e57fb30061d0824b0b4aca0e7264ce092513fd0 Mon Sep 17 00:00:00 2001 From: Glen Davies Date: Tue, 23 Mar 2021 08:19:51 +1300 Subject: [PATCH] Respect sort order from Media Library (#30070) Co-authored-by: Glen Davies --- packages/block-library/src/gallery/edit.js | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/packages/block-library/src/gallery/edit.js b/packages/block-library/src/gallery/edit.js index 6c3ac09dd79842..7d51e64d22e349 100644 --- a/packages/block-library/src/gallery/edit.js +++ b/packages/block-library/src/gallery/edit.js @@ -231,6 +231,16 @@ function GalleryEdit( props ) { return file; } ); + // Because we are reusing existing innerImage blocks any reordering + // done in the media libary will be lost so we need to reapply that ordering + // once the new image blocks are merged in with existing. + const newOrderMap = processedImages.reduce( + ( result, image, index ) => ( + ( result[ image.id ] = index ), result + ), + {} + ); + const existingImageBlocks = ! newFileUploads ? innerBlockImages.filter( ( block ) => processedImages.find( @@ -255,7 +265,11 @@ function GalleryEdit( props ) { replaceInnerBlocks( clientId, - concat( existingImageBlocks, newBlocks ) + concat( existingImageBlocks, newBlocks ).sort( + ( a, b ) => + newOrderMap[ a.attributes.id ] - + newOrderMap[ b.attributes.id ] + ) ); }