diff --git a/src/js/media/views/frame/post.js b/src/js/media/views/frame/post.js
index 08b32bb0cccd2..fdd2d4b8d96f5 100644
--- a/src/js/media/views/frame/post.js
+++ b/src/js/media/views/frame/post.js
@@ -179,6 +179,7 @@ Post = Select.extend(/** @lends wp.media.view.MediaFrame.Post.prototype */{
Select.prototype.bindHandlers.apply( this, arguments );
this.on( 'activate', this.activate, this );
+ this.on( 'close', this.resetCreateGalleryState, this );
// Only bother checking media type counts if one of the counts is zero.
checkCounts = _.find( this.counts, function( type ) {
@@ -234,6 +235,30 @@ Post = Select.extend(/** @lends wp.media.view.MediaFrame.Post.prototype */{
}, this );
},
+ /**
+ * Clears transient gallery state when a new gallery is abandoned.
+ *
+ * @since 7.1.0
+ *
+ * @return {void}
+ */
+ resetCreateGalleryState: function() {
+ var state = this.state(),
+ edit;
+
+ if ( ! state || ! _.contains( [ 'gallery', 'gallery-edit', 'gallery-library' ], state.get( 'id' ) ) ) {
+ return;
+ }
+
+ edit = this.state( 'gallery-edit' );
+
+ if ( edit && ! edit.get( 'editing' ) ) {
+ edit.get( 'library' ).reset();
+ this.state( 'gallery' ).get( 'selection' ).reset();
+ this.state( 'gallery-library' ).get( 'selection' ).reset();
+ }
+ },
+
activate: function() {
// Hide menu items for states tied to particular media types if there are no items.
_.each( this.counts, function( type ) {
diff --git a/tests/qunit/index.html b/tests/qunit/index.html
index 9fd35f0c1ffc2..326c8694d5c3e 100644
--- a/tests/qunit/index.html
+++ b/tests/qunit/index.html
@@ -162,6 +162,7 @@
+
diff --git a/tests/qunit/wp-admin/js/media/post-frame.js b/tests/qunit/wp-admin/js/media/post-frame.js
new file mode 100644
index 0000000000000..54cb03afb46d2
--- /dev/null
+++ b/tests/qunit/wp-admin/js/media/post-frame.js
@@ -0,0 +1,37 @@
+/* global wp */
+/* jshint qunit: true */
+/* eslint-env qunit */
+
+( function() {
+ 'use strict';
+
+ QUnit.module( 'Media Frame Post' );
+
+ QUnit.test( 'closing an abandoned gallery clears transient gallery state', function( assert ) {
+ var frame = wp.media({
+ frame: 'post',
+ state: 'gallery',
+ multiple: true
+ }),
+ gallery = frame.state( 'gallery' ),
+ add = frame.state( 'gallery-library' ),
+ edit = frame.state( 'gallery-edit' ),
+ attachments = [
+ wp.media.model.Attachment.create( { id: 5748901, type: 'image' } ),
+ wp.media.model.Attachment.create( { id: 5748902, type: 'image' } )
+ ];
+
+ gallery.get( 'selection' ).add( attachments );
+ add.get( 'selection' ).add( attachments );
+ edit.get( 'library' ).add( attachments );
+
+ frame.setState( 'gallery-edit' );
+ frame.trigger( 'close' );
+
+ assert.equal( edit.get( 'library' ).length, 0, 'The abandoned gallery selection is cleared.' );
+ assert.equal( gallery.get( 'selection' ).length, 0, 'The create-gallery selection is cleared.' );
+ assert.equal( add.get( 'selection' ).length, 0, 'The add-to-gallery selection is cleared.' );
+
+ frame.dispose();
+ } );
+}() );