From 66c5bb39272549c2d20efeac1d8a52deeefd6191 Mon Sep 17 00:00:00 2001 From: Andrei Draganescu Date: Fri, 19 Apr 2019 17:25:24 +0300 Subject: [PATCH] adds caption updating if changed in gallery, refactores some code --- packages/block-library/src/gallery/block.json | 3 ++ packages/block-library/src/gallery/edit.js | 32 ++++++++++++------- 2 files changed, 23 insertions(+), 12 deletions(-) diff --git a/packages/block-library/src/gallery/block.json b/packages/block-library/src/gallery/block.json index c089b6c9ffe92b..8f5ddaade60ec5 100644 --- a/packages/block-library/src/gallery/block.json +++ b/packages/block-library/src/gallery/block.json @@ -33,6 +33,9 @@ "type": "string", "source": "html", "selector": "figcaption" + }, + "attachmentCaption": { + "type": "string" } } }, diff --git a/packages/block-library/src/gallery/edit.js b/packages/block-library/src/gallery/edit.js index bdd7822ab91835..3997d8fee0cb68 100644 --- a/packages/block-library/src/gallery/edit.js +++ b/packages/block-library/src/gallery/edit.js @@ -2,7 +2,7 @@ * External dependencies */ import classnames from 'classnames'; -import { filter, map } from 'lodash'; +import { filter, map, get, groupBy } from 'lodash'; /** * WordPress dependencies @@ -96,21 +96,29 @@ class GalleryEdit extends Component { }; } + selectCaption( gallery, attachment ) { + const savedAttachmentCaption = get( + gallery, [ attachment.id, 0, 'attachmentCaption' ], '' + ); + if ( savedAttachmentCaption !== attachment.caption ) { + return attachment.caption; + } + return get( + gallery, [ attachment.id, 0, 'caption' ], attachment.caption + ); + } + onSelectImages( newImages ) { const { columns, images } = this.props.attributes; + const galleryImages = groupBy( images, 'id' ); + this.setAttributes( { - images: newImages.map( ( image ) => { - const newImage = pickRelevantMediaFiles( image ); - let oldImage = filter( images, { id: newImage.id } ); - if ( oldImage.length > 0 ) { - oldImage = oldImage.reduce( ( img ) => img ); - if ( oldImage.caption !== '' ) { - newImage.caption = oldImage.caption; - } - } - return newImage; - } ), + images: newImages.map( ( attachment ) => ( { + ...pickRelevantMediaFiles( attachment ), + caption: this.selectCaption( galleryImages, attachment ), + attachmentCaption: attachment.caption, + } ) ), columns: columns ? Math.min( newImages.length, columns ) : columns, } ); }