1 window.wp = window.wp || {};
4 var Attachment, Attachments, Query, compare, l10n, media;
7 * wp.media( attributes )
9 * Handles the default media experience. Automatically creates
10 * and opens a media frame, and returns the result.
11 * Does nothing if the controllers do not exist.
13 * @param {object} attributes The properties passed to the main media controller.
14 * @return {object} A media workflow.
16 media = wp.media = function( attributes ) {
17 var MediaFrame = media.view.MediaFrame,
23 attributes = _.defaults( attributes || {}, {
27 if ( 'select' === attributes.frame && MediaFrame.Select )
28 frame = new MediaFrame.Select( attributes );
29 else if ( 'post' === attributes.frame && MediaFrame.Post )
30 frame = new MediaFrame.Post( attributes );
32 delete attributes.frame;
37 _.extend( media, { model: {}, view: {}, controller: {}, frames: {} });
39 // Link any localized strings.
40 l10n = media.model.l10n = typeof _wpMediaModelsL10n === 'undefined' ? {} : _wpMediaModelsL10n;
43 media.model.settings = l10n.settings || {};
47 * ========================================================================
49 * ========================================================================
55 * @param {mixed} a The primary parameter to compare.
56 * @param {mixed} b The primary parameter to compare.
57 * @param {string} ac The fallback parameter to compare, a's cid.
58 * @param {string} bc The fallback parameter to compare, b's cid.
59 * @return {number} -1: a should come before b.
60 * 0: a and b are of the same rank.
61 * 1: b should come before a.
63 compare = function( a, b, ac, bc ) {
64 if ( _.isEqual( a, b ) )
65 return ac === bc ? 0 : (ac > bc ? -1 : 1);
67 return a > b ? -1 : 1;
72 * media.template( id )
74 * Fetches a template by id.
75 * See wp.template() in `wp-includes/js/wp-util.js`.
77 template: wp.template,
80 * media.post( [action], [data] )
82 * Sends a POST request to WordPress.
83 * See wp.ajax.post() in `wp-includes/js/wp-util.js`.
88 * media.ajax( [action], [options] )
90 * Sends an XHR request to WordPress.
91 * See wp.ajax.send() in `wp-includes/js/wp-util.js`.
95 // Scales a set of dimensions to fit within bounding dimensions.
96 fit: function( dimensions ) {
97 var width = dimensions.width,
98 height = dimensions.height,
99 maxWidth = dimensions.maxWidth,
100 maxHeight = dimensions.maxHeight,
103 // Compare ratios between the two values to determine which
104 // max to constrain by. If a max value doesn't exist, then the
105 // opposite side is the constraint.
106 if ( ! _.isUndefined( maxWidth ) && ! _.isUndefined( maxHeight ) ) {
107 constraint = ( width / height > maxWidth / maxHeight ) ? 'width' : 'height';
108 } else if ( _.isUndefined( maxHeight ) ) {
109 constraint = 'width';
110 } else if ( _.isUndefined( maxWidth ) && height > maxHeight ) {
111 constraint = 'height';
114 // If the value of the constrained side is larger than the max,
115 // then scale the values. Otherwise return the originals; they fit.
116 if ( 'width' === constraint && width > maxWidth ) {
119 height: Math.round( maxWidth * height / width )
121 } else if ( 'height' === constraint && height > maxHeight ) {
123 width : Math.round( maxHeight * width / height ),
134 // Truncates a string by injecting an ellipsis into the middle.
135 // Useful for filenames.
136 truncate: function( string, length, replacement ) {
137 length = length || 30;
138 replacement = replacement || '…';
140 if ( string.length <= length )
143 return string.substr( 0, length / 2 ) + replacement + string.substr( -1 * length / 2 );
149 * ========================================================================
151 * ========================================================================
155 * wp.media.attachment
157 media.attachment = function( id ) {
158 return Attachment.get( id );
162 * wp.media.model.Attachment
164 Attachment = media.model.Attachment = Backbone.Model.extend({
165 sync: function( method, model, options ) {
166 // If the attachment does not yet have an `id`, return an instantly
167 // rejected promise. Otherwise, all of our requests will fail.
168 if ( _.isUndefined( this.id ) )
169 return $.Deferred().rejectWith( this ).promise();
171 // Overload the `read` request so Attachment.fetch() functions correctly.
172 if ( 'read' === method ) {
173 options = options || {};
174 options.context = this;
175 options.data = _.extend( options.data || {}, {
176 action: 'get-attachment',
179 return media.ajax( options );
181 // Overload the `update` request so properties can be saved.
182 } else if ( 'update' === method ) {
183 // If we do not have the necessary nonce, fail immeditately.
184 if ( ! this.get('nonces') || ! this.get('nonces').update )
185 return $.Deferred().rejectWith( this ).promise();
187 options = options || {};
188 options.context = this;
190 // Set the action and ID.
191 options.data = _.extend( options.data || {}, {
192 action: 'save-attachment',
194 nonce: this.get('nonces').update,
195 post_id: media.model.settings.post.id
198 // Record the values of the changed attributes.
199 if ( model.hasChanged() ) {
200 options.data.changes = {};
202 _.each( model.changed, function( value, key ) {
203 options.data.changes[ key ] = this.get( key );
207 return media.ajax( options );
209 // Overload the `delete` request so attachments can be removed.
210 // This will permanently delete an attachment.
211 } else if ( 'delete' === method ) {
212 options = options || {};
214 if ( ! options.wait )
215 this.destroyed = true;
217 options.context = this;
218 options.data = _.extend( options.data || {}, {
219 action: 'delete-post',
221 _wpnonce: this.get('nonces')['delete']
224 return media.ajax( options ).done( function() {
225 this.destroyed = true;
226 }).fail( function() {
227 this.destroyed = false;
230 // Otherwise, fall back to `Backbone.sync()`.
232 return Backbone.Model.prototype.sync.apply( this, arguments );
236 parse: function( resp, xhr ) {
240 // Convert date strings into Date objects.
241 resp.date = new Date( resp.date );
242 resp.modified = new Date( resp.modified );
246 saveCompat: function( data, options ) {
249 // If we do not have the necessary nonce, fail immeditately.
250 if ( ! this.get('nonces') || ! this.get('nonces').update )
251 return $.Deferred().rejectWith( this ).promise();
253 return media.post( 'save-attachment-compat', _.defaults({
255 nonce: this.get('nonces').update,
256 post_id: media.model.settings.post.id
257 }, data ) ).done( function( resp, status, xhr ) {
258 model.set( model.parse( resp, xhr ), options );
262 create: function( attrs ) {
263 return Attachments.all.push( attrs );
266 get: _.memoize( function( id, attachment ) {
267 return Attachments.all.push( attachment || { id: id } );
272 * wp.media.model.Attachments
274 Attachments = media.model.Attachments = Backbone.Collection.extend({
277 initialize: function( models, options ) {
278 options = options || {};
280 this.props = new Backbone.Model();
281 this.filters = options.filters || {};
283 // Bind default `change` events to the `props` model.
284 this.props.on( 'change', this._changeFilteredProps, this );
286 this.props.on( 'change:order', this._changeOrder, this );
287 this.props.on( 'change:orderby', this._changeOrderby, this );
288 this.props.on( 'change:query', this._changeQuery, this );
290 // Set the `props` model and fill the default property values.
291 this.props.set( _.defaults( options.props || {} ) );
293 // Observe another `Attachments` collection if one is provided.
294 if ( options.observe )
295 this.observe( options.observe );
298 // Automatically sort the collection when the order changes.
299 _changeOrder: function( model, order ) {
300 if ( this.comparator )
304 // Set the default comparator only when the `orderby` property is set.
305 _changeOrderby: function( model, orderby ) {
306 // If a different comparator is defined, bail.
307 if ( this.comparator && this.comparator !== Attachments.comparator )
310 if ( orderby && 'post__in' !== orderby )
311 this.comparator = Attachments.comparator;
313 delete this.comparator;
316 // If the `query` property is set to true, query the server using
317 // the `props` values, and sync the results to this collection.
318 _changeQuery: function( model, query ) {
320 this.props.on( 'change', this._requery, this );
323 this.props.off( 'change', this._requery, this );
327 _changeFilteredProps: function( model, options ) {
328 // If this is a query, updating the collection will be handled by
329 // `this._requery()`.
330 if ( this.props.get('query') )
333 var changed = _.chain( model.changed ).map( function( t, prop ) {
334 var filter = Attachments.filters[ prop ],
335 term = model.get( prop );
340 if ( term && ! this.filters[ prop ] )
341 this.filters[ prop ] = filter;
342 else if ( ! term && this.filters[ prop ] === filter )
343 delete this.filters[ prop ];
347 // Record the change.
349 }, this ).any().value();
354 // If no `Attachments` model is provided to source the searches
355 // from, then automatically generate a source from the existing
357 if ( ! this._source )
358 this._source = new Attachments( this.models );
360 this.reset( this._source.filter( this.validator, this ) );
363 validateDestroyed: false,
365 validator: function( attachment ) {
366 if ( ! this.validateDestroyed && attachment.destroyed )
368 return _.all( this.filters, function( filter, key ) {
369 return !! filter.call( this, attachment );
373 validate: function( attachment, options ) {
374 var valid = this.validator( attachment ),
375 hasAttachment = !! this.get( attachment.cid );
377 if ( ! valid && hasAttachment )
378 this.remove( attachment, options );
379 else if ( valid && ! hasAttachment )
380 this.add( attachment, options );
385 validateAll: function( attachments, options ) {
386 options = options || {};
388 _.each( attachments.models, function( attachment ) {
389 this.validate( attachment, { silent: true });
392 if ( ! options.silent )
393 this.trigger( 'reset', this, options );
398 observe: function( attachments ) {
399 this.observers = this.observers || [];
400 this.observers.push( attachments );
402 attachments.on( 'add change remove', this._validateHandler, this );
403 attachments.on( 'reset', this._validateAllHandler, this );
404 this.validateAll( attachments );
408 unobserve: function( attachments ) {
410 attachments.off( null, null, this );
411 this.observers = _.without( this.observers, attachments );
414 _.each( this.observers, function( attachments ) {
415 attachments.off( null, null, this );
417 delete this.observers;
423 _validateHandler: function( attachment, attachments, options ) {
424 // If we're not mirroring this `attachments` collection,
425 // only retain the `silent` option.
426 options = attachments === this.mirroring ? options : {
427 silent: options && options.silent
430 return this.validate( attachment, options );
433 _validateAllHandler: function( attachments, options ) {
434 return this.validateAll( attachments, options );
437 mirror: function( attachments ) {
438 if ( this.mirroring && this.mirroring === attachments )
442 this.mirroring = attachments;
444 // Clear the collection silently. A `reset` event will be fired
445 // when `observe()` calls `validateAll()`.
446 this.reset( [], { silent: true } );
447 this.observe( attachments );
452 unmirror: function() {
453 if ( ! this.mirroring )
456 this.unobserve( this.mirroring );
457 delete this.mirroring;
460 more: function( options ) {
461 var deferred = $.Deferred(),
462 mirroring = this.mirroring,
465 if ( ! mirroring || ! mirroring.more )
466 return deferred.resolveWith( this ).promise();
468 // If we're mirroring another collection, forward `more` to
469 // the mirrored collection. Account for a race condition by
470 // checking if we're still mirroring that collection when
471 // the request resolves.
472 mirroring.more( options ).done( function() {
473 if ( this === attachments.mirroring )
474 deferred.resolveWith( this );
477 return deferred.promise();
480 hasMore: function() {
481 return this.mirroring ? this.mirroring.hasMore() : false;
484 parse: function( resp, xhr ) {
485 if ( ! _.isArray( resp ) )
488 return _.map( resp, function( attrs ) {
489 var id, attachment, newAttributes;
491 if ( attrs instanceof Backbone.Model ) {
492 id = attrs.get( 'id' );
493 attrs = attrs.attributes;
498 attachment = Attachment.get( id );
499 newAttributes = attachment.parse( attrs, xhr );
501 if ( ! _.isEqual( attachment.attributes, newAttributes ) )
502 attachment.set( newAttributes );
508 _requery: function() {
509 if ( this.props.get('query') )
510 this.mirror( Query.get( this.props.toJSON() ) );
513 // If this collection is sorted by `menuOrder`, recalculates and saves
514 // the menu order to the database.
515 saveMenuOrder: function() {
516 if ( 'menuOrder' !== this.props.get('orderby') )
519 // Removes any uploading attachments, updates each attachment's
520 // menu order, and returns an object with an { id: menuOrder }
521 // mapping to pass to the request.
522 var attachments = this.chain().filter( function( attachment ) {
523 return ! _.isUndefined( attachment.id );
524 }).map( function( attachment, index ) {
525 // Indices start at 1.
527 attachment.set( 'menuOrder', index );
528 return [ attachment.id, index ];
531 if ( _.isEmpty( attachments ) )
534 return media.post( 'save-attachment-order', {
535 nonce: media.model.settings.post.nonce,
536 post_id: media.model.settings.post.id,
537 attachments: attachments
541 comparator: function( a, b, options ) {
542 var key = this.props.get('orderby'),
543 order = this.props.get('order') || 'DESC',
550 if ( 'date' === key || 'modified' === key ) {
555 // If `options.ties` is set, don't enforce the `cid` tiebreaker.
556 if ( options && options.ties )
559 return ( 'DESC' === order ) ? compare( a, b, ac, bc ) : compare( b, a, bc, ac );
563 // Note that this client-side searching is *not* equivalent
564 // to our server-side searching.
565 search: function( attachment ) {
566 if ( ! this.props.get('search') )
569 return _.any(['title','filename','description','caption','name'], function( key ) {
570 var value = attachment.get( key );
571 return value && -1 !== value.search( this.props.get('search') );
575 type: function( attachment ) {
576 var type = this.props.get('type');
577 return ! type || -1 !== type.indexOf( attachment.get('type') );
580 uploadedTo: function( attachment ) {
581 var uploadedTo = this.props.get('uploadedTo');
582 if ( _.isUndefined( uploadedTo ) )
585 return uploadedTo === attachment.get('uploadedTo');
590 Attachments.all = new Attachments();
595 media.query = function( props ) {
596 return new Attachments( null, {
597 props: _.extend( _.defaults( props || {}, { orderby: 'date' } ), { query: true } )
602 * wp.media.model.Query
604 * A set of attachments that corresponds to a set of consecutively paged
605 * queries on the server.
607 * Note: Do NOT change this.args after the query has been initialized.
610 Query = media.model.Query = Attachments.extend({
611 initialize: function( models, options ) {
614 options = options || {};
615 Attachments.prototype.initialize.apply( this, arguments );
617 this.args = options.args;
618 this._hasMore = true;
619 this.created = new Date();
621 this.filters.order = function( attachment ) {
622 var orderby = this.props.get('orderby'),
623 order = this.props.get('order');
625 if ( ! this.comparator )
628 // We want any items that can be placed before the last
629 // item in the set. If we add any items after the last
630 // item, then we can't guarantee the set is complete.
632 return 1 !== this.comparator( attachment, this.last(), { ties: true });
634 // Handle the case where there are no items yet and
635 // we're sorting for recent items. In that case, we want
636 // changes that occurred after we created the query.
637 } else if ( 'DESC' === order && ( 'date' === orderby || 'modified' === orderby ) ) {
638 return attachment.get( orderby ) >= this.created;
640 // If we're sorting by menu order and we have no items,
641 // accept any items that have the default menu order (0).
642 } else if ( 'ASC' === order && 'menuOrder' === orderby ) {
643 return attachment.get( orderby ) === 0;
646 // Otherwise, we don't want any items yet.
650 // Observe the central `wp.Uploader.queue` collection to watch for
651 // new matches for the query.
653 // Only observe when a limited number of query args are set. There
654 // are no filters for other properties, so observing will result in
655 // false positives in those queries.
656 allowed = [ 's', 'order', 'orderby', 'posts_per_page', 'post_mime_type', 'post_parent' ];
657 if ( wp.Uploader && _( this.args ).chain().keys().difference( allowed ).isEmpty().value() )
658 this.observe( wp.Uploader.queue );
661 hasMore: function() {
662 return this._hasMore;
665 more: function( options ) {
668 if ( this._more && 'pending' === this._more.state() )
671 if ( ! this.hasMore() )
672 return $.Deferred().resolveWith( this ).promise();
674 options = options || {};
675 options.remove = false;
677 return this._more = this.fetch( options ).done( function( resp ) {
678 if ( _.isEmpty( resp ) || -1 === this.args.posts_per_page || resp.length < this.args.posts_per_page )
679 query._hasMore = false;
683 sync: function( method, model, options ) {
686 // Overload the read method so Attachment.fetch() functions correctly.
687 if ( 'read' === method ) {
688 options = options || {};
689 options.context = this;
690 options.data = _.extend( options.data || {}, {
691 action: 'query-attachments',
692 post_id: media.model.settings.post.id
695 // Clone the args so manipulation is non-destructive.
696 args = _.clone( this.args );
698 // Determine which page to query.
699 if ( -1 !== args.posts_per_page )
700 args.paged = Math.floor( this.length / args.posts_per_page ) + 1;
702 options.data.query = args;
703 return media.ajax( options );
705 // Otherwise, fall back to Backbone.sync()
707 fallback = Attachments.prototype.sync ? Attachments.prototype : Backbone;
708 return fallback.sync.apply( this, arguments );
722 allowed: [ 'name', 'author', 'date', 'title', 'modified', 'uploadedTo', 'id', 'post__in', 'menuOrder' ],
725 'uploadedTo': 'parent',
726 'menuOrder': 'menu_order ID'
732 'type': 'post_mime_type',
733 'perPage': 'posts_per_page',
734 'menuOrder': 'menu_order',
735 'uploadedTo': 'post_parent'
738 // Caches query objects so queries can be easily reused.
742 return function( props, options ) {
744 orderby = Query.orderby,
745 defaults = Query.defaultProps,
748 // Remove the `query` property. This isn't linked to a query,
749 // this *is* the query.
752 // Fill default args.
753 _.defaults( props, defaults );
755 // Normalize the order.
756 props.order = props.order.toUpperCase();
757 if ( 'DESC' !== props.order && 'ASC' !== props.order )
758 props.order = defaults.order.toUpperCase();
760 // Ensure we have a valid orderby value.
761 if ( ! _.contains( orderby.allowed, props.orderby ) )
762 props.orderby = defaults.orderby;
764 // Generate the query `args` object.
765 // Correct any differing property names.
766 _.each( props, function( value, prop ) {
767 if ( _.isNull( value ) )
770 args[ Query.propmap[ prop ] || prop ] = value;
773 // Fill any other default query args.
774 _.defaults( args, Query.defaultArgs );
776 // `props.orderby` does not always map directly to `args.orderby`.
777 // Substitute exceptions specified in orderby.keymap.
778 args.orderby = orderby.valuemap[ props.orderby ] || props.orderby;
780 // Search the query cache for matches.
781 query = _.find( queries, function( query ) {
782 return _.isEqual( query.args, args );
785 // Otherwise, create a new query and add it to the cache.
787 query = new Query( [], _.extend( options || {}, {
791 queries.push( query );
800 * wp.media.model.Selection
802 * Used to manage a selection of attachments in the views.
804 media.model.Selection = Attachments.extend({
805 initialize: function( models, options ) {
806 Attachments.prototype.initialize.apply( this, arguments );
807 this.multiple = options && options.multiple;
809 // Refresh the `single` model whenever the selection changes.
810 // Binds `single` instead of using the context argument to ensure
811 // it receives no parameters.
812 this.on( 'add remove reset', _.bind( this.single, this, false ) );
815 // Override the selection's add method.
816 // If the workflow does not support multiple
817 // selected attachments, reset the selection.
818 add: function( models, options ) {
819 if ( ! this.multiple )
820 this.remove( this.models );
822 return Attachments.prototype.add.call( this, models, options );
825 single: function( model ) {
826 var previous = this._single;
828 // If a `model` is provided, use it as the single model.
830 this._single = model;
832 // If the single model isn't in the selection, remove it.
833 if ( this._single && ! this.get( this._single.cid ) )
836 this._single = this._single || this.last();
838 // If single has changed, fire an event.
839 if ( this._single !== previous ) {
841 previous.trigger( 'selection:unsingle', previous, this );
843 // If the model was already removed, trigger the collection
845 if ( ! this.get( previous.cid ) )
846 this.trigger( 'selection:unsingle', previous, this );
849 this._single.trigger( 'selection:single', this._single, this );
852 // Return the single model, or the last model as a fallback.
857 // Clean up. Prevents mobile browsers caching
858 $(window).on('unload', function(){