1 /* global _wpMediaModelsL10n:false */
2 window.wp = window.wp || {};
5 var Attachment, Attachments, Query, PostImage, compare, l10n, media;
8 * wp.media( attributes )
10 * Handles the default media experience. Automatically creates
11 * and opens a media frame, and returns the result.
12 * Does nothing if the controllers do not exist.
14 * @param {object} attributes The properties passed to the main media controller.
15 * @return {wp.media.view.MediaFrame} A media workflow.
17 media = wp.media = function( attributes ) {
18 var MediaFrame = media.view.MediaFrame,
25 attributes = _.defaults( attributes || {}, {
29 if ( 'select' === attributes.frame && MediaFrame.Select ) {
30 frame = new MediaFrame.Select( attributes );
31 } else if ( 'post' === attributes.frame && MediaFrame.Post ) {
32 frame = new MediaFrame.Post( attributes );
33 } else if ( 'image' === attributes.frame && MediaFrame.ImageDetails ) {
34 frame = new MediaFrame.ImageDetails( attributes );
35 } else if ( 'audio' === attributes.frame && MediaFrame.AudioDetails ) {
36 frame = new MediaFrame.AudioDetails( attributes );
37 } else if ( 'video' === attributes.frame && MediaFrame.VideoDetails ) {
38 frame = new MediaFrame.VideoDetails( attributes );
41 delete attributes.frame;
48 _.extend( media, { model: {}, view: {}, controller: {}, frames: {} });
50 // Link any localized strings.
51 l10n = media.model.l10n = typeof _wpMediaModelsL10n === 'undefined' ? {} : _wpMediaModelsL10n;
54 media.model.settings = l10n.settings || {};
58 * ========================================================================
60 * ========================================================================
66 * @param {mixed} a The primary parameter to compare.
67 * @param {mixed} b The primary parameter to compare.
68 * @param {string} ac The fallback parameter to compare, a's cid.
69 * @param {string} bc The fallback parameter to compare, b's cid.
70 * @return {number} -1: a should come before b.
71 * 0: a and b are of the same rank.
72 * 1: b should come before a.
74 compare = function( a, b, ac, bc ) {
75 if ( _.isEqual( a, b ) ) {
76 return ac === bc ? 0 : (ac > bc ? -1 : 1);
78 return a > b ? -1 : 1;
84 * media.template( id )
86 * Fetches a template by id.
87 * See wp.template() in `wp-includes/js/wp-util.js`.
89 * @borrows wp.template as template
91 template: wp.template,
94 * media.post( [action], [data] )
96 * Sends a POST request to WordPress.
97 * See wp.ajax.post() in `wp-includes/js/wp-util.js`.
99 * @borrows wp.ajax.post as post
104 * media.ajax( [action], [options] )
106 * Sends an XHR request to WordPress.
107 * See wp.ajax.send() in `wp-includes/js/wp-util.js`.
109 * @borrows wp.ajax.send as ajax
114 * Scales a set of dimensions to fit within bounding dimensions.
116 * @param {Object} dimensions
119 fit: function( dimensions ) {
120 var width = dimensions.width,
121 height = dimensions.height,
122 maxWidth = dimensions.maxWidth,
123 maxHeight = dimensions.maxHeight,
126 // Compare ratios between the two values to determine which
127 // max to constrain by. If a max value doesn't exist, then the
128 // opposite side is the constraint.
129 if ( ! _.isUndefined( maxWidth ) && ! _.isUndefined( maxHeight ) ) {
130 constraint = ( width / height > maxWidth / maxHeight ) ? 'width' : 'height';
131 } else if ( _.isUndefined( maxHeight ) ) {
132 constraint = 'width';
133 } else if ( _.isUndefined( maxWidth ) && height > maxHeight ) {
134 constraint = 'height';
137 // If the value of the constrained side is larger than the max,
138 // then scale the values. Otherwise return the originals; they fit.
139 if ( 'width' === constraint && width > maxWidth ) {
142 height: Math.round( maxWidth * height / width )
144 } else if ( 'height' === constraint && height > maxHeight ) {
146 width : Math.round( maxHeight * width / height ),
157 * Truncates a string by injecting an ellipsis into the middle.
158 * Useful for filenames.
160 * @param {String} string
161 * @param {Number} [length=30]
162 * @param {String} [replacement=…]
163 * @returns {String} The string, unless length is greater than string.length.
165 truncate: function( string, length, replacement ) {
166 length = length || 30;
167 replacement = replacement || '…';
169 if ( string.length <= length ) {
173 return string.substr( 0, length / 2 ) + replacement + string.substr( -1 * length / 2 );
178 * ========================================================================
180 * ========================================================================
183 * wp.media.attachment
186 * @param {String} id A string used to identify a model.
187 * @returns {wp.media.model.Attachment}
189 media.attachment = function( id ) {
190 return Attachment.get( id );
194 * wp.media.model.Attachment
197 * @augments Backbone.Model
199 Attachment = media.model.Attachment = Backbone.Model.extend({
201 * Triggered when attachment details change
202 * Overrides Backbone.Model.sync
204 * @param {string} method
205 * @param {wp.media.model.Attachment} model
206 * @param {Object} [options={}]
210 sync: function( method, model, options ) {
211 // If the attachment does not yet have an `id`, return an instantly
212 // rejected promise. Otherwise, all of our requests will fail.
213 if ( _.isUndefined( this.id ) ) {
214 return $.Deferred().rejectWith( this ).promise();
217 // Overload the `read` request so Attachment.fetch() functions correctly.
218 if ( 'read' === method ) {
219 options = options || {};
220 options.context = this;
221 options.data = _.extend( options.data || {}, {
222 action: 'get-attachment',
225 return media.ajax( options );
227 // Overload the `update` request so properties can be saved.
228 } else if ( 'update' === method ) {
229 // If we do not have the necessary nonce, fail immeditately.
230 if ( ! this.get('nonces') || ! this.get('nonces').update ) {
231 return $.Deferred().rejectWith( this ).promise();
234 options = options || {};
235 options.context = this;
237 // Set the action and ID.
238 options.data = _.extend( options.data || {}, {
239 action: 'save-attachment',
241 nonce: this.get('nonces').update,
242 post_id: media.model.settings.post.id
245 // Record the values of the changed attributes.
246 if ( model.hasChanged() ) {
247 options.data.changes = {};
249 _.each( model.changed, function( value, key ) {
250 options.data.changes[ key ] = this.get( key );
254 return media.ajax( options );
256 // Overload the `delete` request so attachments can be removed.
257 // This will permanently delete an attachment.
258 } else if ( 'delete' === method ) {
259 options = options || {};
261 if ( ! options.wait ) {
262 this.destroyed = true;
265 options.context = this;
266 options.data = _.extend( options.data || {}, {
267 action: 'delete-post',
269 _wpnonce: this.get('nonces')['delete']
272 return media.ajax( options ).done( function() {
273 this.destroyed = true;
274 }).fail( function() {
275 this.destroyed = false;
278 // Otherwise, fall back to `Backbone.sync()`.
281 * Call `sync` directly on Backbone.Model
283 return Backbone.Model.prototype.sync.apply( this, arguments );
287 * Convert date strings into Date objects.
289 * @param {Object} resp The raw response object, typically returned by fetch()
290 * @returns {Object} The modified response object, which is the attributes hash
291 * to be set on the model.
293 parse: function( resp ) {
298 resp.date = new Date( resp.date );
299 resp.modified = new Date( resp.modified );
303 * @param {Object} data The properties to be saved.
304 * @param {Object} options Sync options. e.g. patch, wait, success, error.
306 * @this Backbone.Model
310 saveCompat: function( data, options ) {
313 // If we do not have the necessary nonce, fail immeditately.
314 if ( ! this.get('nonces') || ! this.get('nonces').update ) {
315 return $.Deferred().rejectWith( this ).promise();
318 return media.post( 'save-attachment-compat', _.defaults({
320 nonce: this.get('nonces').update,
321 post_id: media.model.settings.post.id
322 }, data ) ).done( function( resp, status, xhr ) {
323 model.set( model.parse( resp, xhr ), options );
328 * Add a model to the end of the static 'all' collection and return it.
331 * @param {Object} attrs
332 * @returns {wp.media.model.Attachment}
334 create: function( attrs ) {
335 return Attachments.all.push( attrs );
338 * Retrieve a model, or add it to the end of the static 'all' collection before returning it.
341 * @param {string} id A string used to identify a model.
342 * @param {Backbone.Model|undefined} attachment
343 * @returns {wp.media.model.Attachment}
345 get: _.memoize( function( id, attachment ) {
346 return Attachments.all.push( attachment || { id: id } );
351 * wp.media.model.PostImage
354 * @augments Backbone.Model
356 PostImage = media.model.PostImage = Backbone.Model.extend({
358 initialize: function( attributes ) {
359 this.attachment = false;
361 if ( attributes.attachment_id ) {
362 this.attachment = Attachment.get( attributes.attachment_id );
363 if ( this.attachment.get( 'url' ) ) {
364 this.dfd = $.Deferred();
367 this.dfd = this.attachment.fetch();
369 this.bindAttachmentListeners();
372 // keep url in sync with changes to the type of link
373 this.on( 'change:link', this.updateLinkUrl, this );
374 this.on( 'change:size', this.updateSize, this );
376 this.setLinkTypeFromUrl();
377 this.setAspectRatio();
379 this.set( 'originalUrl', attributes.url );
382 bindAttachmentListeners: function() {
383 this.listenTo( this.attachment, 'sync', this.setLinkTypeFromUrl );
384 this.listenTo( this.attachment, 'sync', this.setAspectRatio );
385 this.listenTo( this.attachment, 'change', this.updateSize );
388 changeAttachment: function( attachment, props ) {
389 this.stopListening( this.attachment );
390 this.attachment = attachment;
391 this.bindAttachmentListeners();
393 this.set( 'attachment_id', this.attachment.get( 'id' ) );
394 this.set( 'caption', this.attachment.get( 'caption' ) );
395 this.set( 'alt', this.attachment.get( 'alt' ) );
396 this.set( 'size', props.get( 'size' ) );
397 this.set( 'align', props.get( 'align' ) );
398 this.set( 'link', props.get( 'link' ) );
399 this.updateLinkUrl();
403 setLinkTypeFromUrl: function() {
404 var linkUrl = this.get( 'linkUrl' ),
408 this.set( 'link', 'none' );
412 // default to custom if there is a linkUrl
415 if ( this.attachment ) {
416 if ( this.attachment.get( 'url' ) === linkUrl ) {
418 } else if ( this.attachment.get( 'link' ) === linkUrl ) {
422 if ( this.get( 'url' ) === linkUrl ) {
427 this.set( 'link', type );
430 updateLinkUrl: function() {
431 var link = this.get( 'link' ),
436 if ( this.attachment ) {
437 url = this.attachment.get( 'url' );
439 url = this.get( 'url' );
441 this.set( 'linkUrl', url );
444 this.set( 'linkUrl', this.attachment.get( 'link' ) );
447 this.set( 'linkUrl', '' );
452 updateSize: function() {
455 if ( ! this.attachment ) {
459 if ( this.get( 'size' ) === 'custom' ) {
460 this.set( 'width', this.get( 'customWidth' ) );
461 this.set( 'height', this.get( 'customHeight' ) );
462 this.set( 'url', this.get( 'originalUrl' ) );
466 size = this.attachment.get( 'sizes' )[ this.get( 'size' ) ];
472 this.set( 'url', size.url );
473 this.set( 'width', size.width );
474 this.set( 'height', size.height );
477 setAspectRatio: function() {
480 if ( this.attachment && this.attachment.get( 'sizes' ) ) {
481 full = this.attachment.get( 'sizes' ).full;
484 this.set( 'aspectRatio', full.width / full.height );
489 this.set( 'aspectRatio', this.get( 'customWidth' ) / this.get( 'customHeight' ) );
494 * wp.media.model.Attachments
497 * @augments Backbone.Collection
499 Attachments = media.model.Attachments = Backbone.Collection.extend({
501 * @type {wp.media.model.Attachment}
505 * @param {Array} [models=[]] Array of models used to populate the collection.
506 * @param {Object} [options={}]
508 initialize: function( models, options ) {
509 options = options || {};
511 this.props = new Backbone.Model();
512 this.filters = options.filters || {};
514 // Bind default `change` events to the `props` model.
515 this.props.on( 'change', this._changeFilteredProps, this );
517 this.props.on( 'change:order', this._changeOrder, this );
518 this.props.on( 'change:orderby', this._changeOrderby, this );
519 this.props.on( 'change:query', this._changeQuery, this );
521 // Set the `props` model and fill the default property values.
522 this.props.set( _.defaults( options.props || {} ) );
524 // Observe another `Attachments` collection if one is provided.
525 if ( options.observe ) {
526 this.observe( options.observe );
530 * Automatically sort the collection when the order changes.
534 _changeOrder: function() {
535 if ( this.comparator ) {
540 * Set the default comparator only when the `orderby` property is set.
544 * @param {Backbone.Model} model
545 * @param {string} orderby
547 _changeOrderby: function( model, orderby ) {
548 // If a different comparator is defined, bail.
549 if ( this.comparator && this.comparator !== Attachments.comparator ) {
553 if ( orderby && 'post__in' !== orderby ) {
554 this.comparator = Attachments.comparator;
556 delete this.comparator;
560 * If the `query` property is set to true, query the server using
561 * the `props` values, and sync the results to this collection.
565 * @param {Backbone.Model} model
566 * @param {Boolean} query
568 _changeQuery: function( model, query ) {
570 this.props.on( 'change', this._requery, this );
573 this.props.off( 'change', this._requery, this );
579 * @param {Backbone.Model} model
581 _changeFilteredProps: function( model ) {
582 // If this is a query, updating the collection will be handled by
583 // `this._requery()`.
584 if ( this.props.get('query') ) {
588 var changed = _.chain( model.changed ).map( function( t, prop ) {
589 var filter = Attachments.filters[ prop ],
590 term = model.get( prop );
596 if ( term && ! this.filters[ prop ] ) {
597 this.filters[ prop ] = filter;
598 } else if ( ! term && this.filters[ prop ] === filter ) {
599 delete this.filters[ prop ];
604 // Record the change.
606 }, this ).any().value();
612 // If no `Attachments` model is provided to source the searches
613 // from, then automatically generate a source from the existing
615 if ( ! this._source ) {
616 this._source = new Attachments( this.models );
619 this.reset( this._source.filter( this.validator, this ) );
622 validateDestroyed: false,
624 * @param {wp.media.model.Attachment} attachment
627 validator: function( attachment ) {
628 if ( ! this.validateDestroyed && attachment.destroyed ) {
631 return _.all( this.filters, function( filter ) {
632 return !! filter.call( this, attachment );
636 * @param {wp.media.model.Attachment} attachment
637 * @param {Object} options
638 * @returns {wp.media.model.Attachments} Returns itself to allow chaining
640 validate: function( attachment, options ) {
641 var valid = this.validator( attachment ),
642 hasAttachment = !! this.get( attachment.cid );
644 if ( ! valid && hasAttachment ) {
645 this.remove( attachment, options );
646 } else if ( valid && ! hasAttachment ) {
647 this.add( attachment, options );
654 * @param {wp.media.model.Attachments} attachments
655 * @param {object} [options={}]
657 * @fires wp.media.model.Attachments#reset
659 * @returns {wp.media.model.Attachments} Returns itself to allow chaining
661 validateAll: function( attachments, options ) {
662 options = options || {};
664 _.each( attachments.models, function( attachment ) {
665 this.validate( attachment, { silent: true });
668 if ( ! options.silent ) {
669 this.trigger( 'reset', this, options );
674 * @param {wp.media.model.Attachments} attachments
675 * @returns {wp.media.model.Attachments} Returns itself to allow chaining
677 observe: function( attachments ) {
678 this.observers = this.observers || [];
679 this.observers.push( attachments );
681 attachments.on( 'add change remove', this._validateHandler, this );
682 attachments.on( 'reset', this._validateAllHandler, this );
683 this.validateAll( attachments );
687 * @param {wp.media.model.Attachments} attachments
688 * @returns {wp.media.model.Attachments} Returns itself to allow chaining
690 unobserve: function( attachments ) {
692 attachments.off( null, null, this );
693 this.observers = _.without( this.observers, attachments );
696 _.each( this.observers, function( attachments ) {
697 attachments.off( null, null, this );
699 delete this.observers;
707 * @param {wp.media.model.Attachments} attachment
708 * @param {wp.media.model.Attachments} attachments
709 * @param {Object} options
711 * @returns {wp.media.model.Attachments} Returns itself to allow chaining
713 _validateHandler: function( attachment, attachments, options ) {
714 // If we're not mirroring this `attachments` collection,
715 // only retain the `silent` option.
716 options = attachments === this.mirroring ? options : {
717 silent: options && options.silent
720 return this.validate( attachment, options );
725 * @param {wp.media.model.Attachments} attachments
726 * @param {Object} options
727 * @returns {wp.media.model.Attachments} Returns itself to allow chaining
729 _validateAllHandler: function( attachments, options ) {
730 return this.validateAll( attachments, options );
733 * @param {wp.media.model.Attachments} attachments
734 * @returns {wp.media.model.Attachments} Returns itself to allow chaining
736 mirror: function( attachments ) {
737 if ( this.mirroring && this.mirroring === attachments ) {
742 this.mirroring = attachments;
744 // Clear the collection silently. A `reset` event will be fired
745 // when `observe()` calls `validateAll()`.
746 this.reset( [], { silent: true } );
747 this.observe( attachments );
751 unmirror: function() {
752 if ( ! this.mirroring ) {
756 this.unobserve( this.mirroring );
757 delete this.mirroring;
760 * @param {Object} options
763 more: function( options ) {
764 var deferred = $.Deferred(),
765 mirroring = this.mirroring,
768 if ( ! mirroring || ! mirroring.more ) {
769 return deferred.resolveWith( this ).promise();
771 // If we're mirroring another collection, forward `more` to
772 // the mirrored collection. Account for a race condition by
773 // checking if we're still mirroring that collection when
774 // the request resolves.
775 mirroring.more( options ).done( function() {
776 if ( this === attachments.mirroring )
777 deferred.resolveWith( this );
780 return deferred.promise();
785 hasMore: function() {
786 return this.mirroring ? this.mirroring.hasMore() : false;
789 * Overrides Backbone.Collection.parse
791 * @param {Object|Array} resp The raw response Object/Array.
792 * @param {Object} xhr
793 * @returns {Array} The array of model attributes to be added to the collection
795 parse: function( resp, xhr ) {
796 if ( ! _.isArray( resp ) ) {
800 return _.map( resp, function( attrs ) {
801 var id, attachment, newAttributes;
803 if ( attrs instanceof Backbone.Model ) {
804 id = attrs.get( 'id' );
805 attrs = attrs.attributes;
810 attachment = Attachment.get( id );
811 newAttributes = attachment.parse( attrs, xhr );
813 if ( ! _.isEqual( attachment.attributes, newAttributes ) ) {
814 attachment.set( newAttributes );
823 _requery: function() {
824 if ( this.props.get('query') ) {
825 this.mirror( Query.get( this.props.toJSON() ) );
829 * If this collection is sorted by `menuOrder`, recalculates and saves
830 * the menu order to the database.
832 * @returns {undefined|Promise}
834 saveMenuOrder: function() {
835 if ( 'menuOrder' !== this.props.get('orderby') ) {
839 // Removes any uploading attachments, updates each attachment's
840 // menu order, and returns an object with an { id: menuOrder }
841 // mapping to pass to the request.
842 var attachments = this.chain().filter( function( attachment ) {
843 return ! _.isUndefined( attachment.id );
844 }).map( function( attachment, index ) {
845 // Indices start at 1.
847 attachment.set( 'menuOrder', index );
848 return [ attachment.id, index ];
851 if ( _.isEmpty( attachments ) ) {
855 return media.post( 'save-attachment-order', {
856 nonce: media.model.settings.post.nonce,
857 post_id: media.model.settings.post.id,
858 attachments: attachments
864 * Overrides Backbone.Collection.comparator
866 * @param {Backbone.Model} a
867 * @param {Backbone.Model} b
868 * @param {Object} options
869 * @returns {Number} -1 if the first model should come before the second,
870 * 0 if they are of the same rank and
871 * 1 if the first model should come after.
873 comparator: function( a, b, options ) {
874 var key = this.props.get('orderby'),
875 order = this.props.get('order') || 'DESC',
882 if ( 'date' === key || 'modified' === key ) {
887 // If `options.ties` is set, don't enforce the `cid` tiebreaker.
888 if ( options && options.ties ) {
892 return ( 'DESC' === order ) ? compare( a, b, ac, bc ) : compare( b, a, bc, ac );
900 * Note that this client-side searching is *not* equivalent
901 * to our server-side searching.
903 * @param {wp.media.model.Attachment} attachment
905 * @this wp.media.model.Attachments
909 search: function( attachment ) {
910 if ( ! this.props.get('search') ) {
914 return _.any(['title','filename','description','caption','name'], function( key ) {
915 var value = attachment.get( key );
916 return value && -1 !== value.search( this.props.get('search') );
921 * @param {wp.media.model.Attachment} attachment
923 * @this wp.media.model.Attachments
927 type: function( attachment ) {
928 var type = this.props.get('type');
929 return ! type || -1 !== type.indexOf( attachment.get('type') );
933 * @param {wp.media.model.Attachment} attachment
935 * @this wp.media.model.Attachments
939 uploadedTo: function( attachment ) {
940 var uploadedTo = this.props.get('uploadedTo');
941 if ( _.isUndefined( uploadedTo ) ) {
945 return uploadedTo === attachment.get('uploadedTo');
952 * @member {wp.media.model.Attachments}
954 Attachments.all = new Attachments();
960 * @returns {wp.media.model.Attachments}
962 media.query = function( props ) {
963 return new Attachments( null, {
964 props: _.extend( _.defaults( props || {}, { orderby: 'date' } ), { query: true } )
969 * wp.media.model.Query
971 * A set of attachments that corresponds to a set of consecutively paged
972 * queries on the server.
974 * Note: Do NOT change this.args after the query has been initialized.
978 * @augments wp.media.model.Attachments
979 * @augments Backbone.Collection
981 Query = media.model.Query = Attachments.extend({
983 * @global wp.Uploader
985 * @param {Array} [models=[]] Array of models used to populate the collection.
986 * @param {Object} [options={}]
988 initialize: function( models, options ) {
991 options = options || {};
992 Attachments.prototype.initialize.apply( this, arguments );
994 this.args = options.args;
995 this._hasMore = true;
996 this.created = new Date();
998 this.filters.order = function( attachment ) {
999 var orderby = this.props.get('orderby'),
1000 order = this.props.get('order');
1002 if ( ! this.comparator ) {
1006 // We want any items that can be placed before the last
1007 // item in the set. If we add any items after the last
1008 // item, then we can't guarantee the set is complete.
1009 if ( this.length ) {
1010 return 1 !== this.comparator( attachment, this.last(), { ties: true });
1012 // Handle the case where there are no items yet and
1013 // we're sorting for recent items. In that case, we want
1014 // changes that occurred after we created the query.
1015 } else if ( 'DESC' === order && ( 'date' === orderby || 'modified' === orderby ) ) {
1016 return attachment.get( orderby ) >= this.created;
1018 // If we're sorting by menu order and we have no items,
1019 // accept any items that have the default menu order (0).
1020 } else if ( 'ASC' === order && 'menuOrder' === orderby ) {
1021 return attachment.get( orderby ) === 0;
1024 // Otherwise, we don't want any items yet.
1028 // Observe the central `wp.Uploader.queue` collection to watch for
1029 // new matches for the query.
1031 // Only observe when a limited number of query args are set. There
1032 // are no filters for other properties, so observing will result in
1033 // false positives in those queries.
1034 allowed = [ 's', 'order', 'orderby', 'posts_per_page', 'post_mime_type', 'post_parent' ];
1035 if ( wp.Uploader && _( this.args ).chain().keys().difference( allowed ).isEmpty().value() ) {
1036 this.observe( wp.Uploader.queue );
1040 * @returns {Boolean}
1042 hasMore: function() {
1043 return this._hasMore;
1046 * @param {Object} [options={}]
1047 * @returns {Promise}
1049 more: function( options ) {
1052 if ( this._more && 'pending' === this._more.state() ) {
1056 if ( ! this.hasMore() ) {
1057 return $.Deferred().resolveWith( this ).promise();
1060 options = options || {};
1061 options.remove = false;
1063 return this._more = this.fetch( options ).done( function( resp ) {
1064 if ( _.isEmpty( resp ) || -1 === this.args.posts_per_page || resp.length < this.args.posts_per_page ) {
1065 query._hasMore = false;
1070 * Overrides Backbone.Collection.sync
1071 * Overrides wp.media.model.Attachments.sync
1073 * @param {String} method
1074 * @param {Backbone.Model} model
1075 * @param {Object} [options={}]
1076 * @returns {Promise}
1078 sync: function( method, model, options ) {
1081 // Overload the read method so Attachment.fetch() functions correctly.
1082 if ( 'read' === method ) {
1083 options = options || {};
1084 options.context = this;
1085 options.data = _.extend( options.data || {}, {
1086 action: 'query-attachments',
1087 post_id: media.model.settings.post.id
1090 // Clone the args so manipulation is non-destructive.
1091 args = _.clone( this.args );
1093 // Determine which page to query.
1094 if ( -1 !== args.posts_per_page ) {
1095 args.paged = Math.floor( this.length / args.posts_per_page ) + 1;
1098 options.data.query = args;
1099 return media.ajax( options );
1101 // Otherwise, fall back to Backbone.sync()
1104 * Call wp.media.model.Attachments.sync or Backbone.sync
1106 fallback = Attachments.prototype.sync ? Attachments.prototype : Backbone;
1107 return fallback.sync.apply( this, arguments );
1128 allowed: [ 'name', 'author', 'date', 'title', 'modified', 'uploadedTo', 'id', 'post__in', 'menuOrder' ],
1131 'uploadedTo': 'parent',
1132 'menuOrder': 'menu_order ID'
1140 'type': 'post_mime_type',
1141 'perPage': 'posts_per_page',
1142 'menuOrder': 'menu_order',
1143 'uploadedTo': 'post_parent'
1149 * @returns {wp.media.model.Query} A new query.
1151 // Caches query objects so queries can be easily reused.
1160 * @param {Object} props
1161 * @param {Object} options
1164 return function( props, options ) {
1166 orderby = Query.orderby,
1167 defaults = Query.defaultProps,
1170 // Remove the `query` property. This isn't linked to a query,
1171 // this *is* the query.
1174 // Fill default args.
1175 _.defaults( props, defaults );
1177 // Normalize the order.
1178 props.order = props.order.toUpperCase();
1179 if ( 'DESC' !== props.order && 'ASC' !== props.order ) {
1180 props.order = defaults.order.toUpperCase();
1183 // Ensure we have a valid orderby value.
1184 if ( ! _.contains( orderby.allowed, props.orderby ) ) {
1185 props.orderby = defaults.orderby;
1188 // Generate the query `args` object.
1189 // Correct any differing property names.
1190 _.each( props, function( value, prop ) {
1191 if ( _.isNull( value ) ) {
1195 args[ Query.propmap[ prop ] || prop ] = value;
1198 // Fill any other default query args.
1199 _.defaults( args, Query.defaultArgs );
1201 // `props.orderby` does not always map directly to `args.orderby`.
1202 // Substitute exceptions specified in orderby.keymap.
1203 args.orderby = orderby.valuemap[ props.orderby ] || props.orderby;
1205 // Search the query cache for matches.
1206 query = _.find( queries, function( query ) {
1207 return _.isEqual( query.args, args );
1210 // Otherwise, create a new query and add it to the cache.
1212 query = new Query( [], _.extend( options || {}, {
1216 queries.push( query );
1225 * wp.media.model.Selection
1227 * Used to manage a selection of attachments in the views.
1230 * @augments wp.media.model.Attachments
1231 * @augments Backbone.Collection
1233 media.model.Selection = Attachments.extend({
1235 * Refresh the `single` model whenever the selection changes.
1236 * Binds `single` instead of using the context argument to ensure
1237 * it receives no parameters.
1239 * @param {Array} [models=[]] Array of models used to populate the collection.
1240 * @param {Object} [options={}]
1242 initialize: function( models, options ) {
1244 * call 'initialize' directly on the parent class
1246 Attachments.prototype.initialize.apply( this, arguments );
1247 this.multiple = options && options.multiple;
1249 this.on( 'add remove reset', _.bind( this.single, this, false ) );
1253 * Override the selection's add method.
1254 * If the workflow does not support multiple
1255 * selected attachments, reset the selection.
1257 * Overrides Backbone.Collection.add
1258 * Overrides wp.media.model.Attachments.add
1260 * @param {Array} models
1261 * @param {Object} options
1262 * @returns {wp.media.model.Attachment[]}
1264 add: function( models, options ) {
1265 if ( ! this.multiple ) {
1266 this.remove( this.models );
1269 * call 'add' directly on the parent class
1271 return Attachments.prototype.add.call( this, models, options );
1275 * Triggered when toggling (clicking on) an attachment in the modal
1277 * @param {undefined|boolean|wp.media.model.Attachment} model
1279 * @fires wp.media.model.Selection#selection:single
1280 * @fires wp.media.model.Selection#selection:unsingle
1282 * @returns {Backbone.Model}
1284 single: function( model ) {
1285 var previous = this._single;
1287 // If a `model` is provided, use it as the single model.
1289 this._single = model;
1291 // If the single model isn't in the selection, remove it.
1292 if ( this._single && ! this.get( this._single.cid ) ) {
1293 delete this._single;
1296 this._single = this._single || this.last();
1298 // If single has changed, fire an event.
1299 if ( this._single !== previous ) {
1301 previous.trigger( 'selection:unsingle', previous, this );
1303 // If the model was already removed, trigger the collection
1305 if ( ! this.get( previous.cid ) ) {
1306 this.trigger( 'selection:unsingle', previous, this );
1309 if ( this._single ) {
1310 this._single.trigger( 'selection:single', this._single, this );
1314 // Return the single model, or the last model as a fallback.
1315 return this._single;
1319 // Clean up. Prevents mobile browsers caching
1320 $(window).on('unload', function(){