1 /* global _wpMediaViewsL10n, confirm, getUserSetting, setUserSetting */
3 var media = wp.media, l10n;
5 // Link any localized strings.
6 l10n = media.view.l10n = typeof _wpMediaViewsL10n === 'undefined' ? {} : _wpMediaViewsL10n;
9 media.view.settings = l10n.settings || {};
12 // Copy the `post` setting over to the model settings.
13 media.model.settings.post = media.view.settings.post;
15 // Check if the browser supports CSS 3.0 transitions
16 $.support.transition = (function(){
17 var style = document.documentElement.style,
19 WebkitTransition: 'webkitTransitionEnd',
20 MozTransition: 'transitionend',
21 OTransition: 'oTransitionEnd otransitionend',
22 transition: 'transitionend'
25 transition = _.find( _.keys( transitions ), function( transition ) {
26 return ! _.isUndefined( style[ transition ] );
29 return transition && {
30 end: transitions[ transition ]
35 * A shared event bus used to provide events into
36 * the media workflows that 3rd-party devs can use to hook
39 media.events = _.extend( {}, Backbone.Events );
42 * Makes it easier to bind events using transitions.
44 * @param {string} selector
45 * @param {Number} sensitivity
48 media.transition = function( selector, sensitivity ) {
49 var deferred = $.Deferred();
51 sensitivity = sensitivity || 2000;
53 if ( $.support.transition ) {
54 if ( ! (selector instanceof $) ) {
55 selector = $( selector );
58 // Resolve the deferred when the first element finishes animating.
59 selector.first().one( $.support.transition.end, deferred.resolve );
61 // Just in case the event doesn't trigger, fire a callback.
62 _.delay( deferred.resolve, sensitivity );
64 // Otherwise, execute on the spot.
69 return deferred.promise();
73 * ========================================================================
75 * ========================================================================
79 * wp.media.controller.Region
82 * @augments Backbone.Model
84 * @param {Object} [options={}]
86 media.controller.Region = function( options ) {
87 _.extend( this, _.pick( options || {}, 'id', 'view', 'selector' ) );
90 // Use Backbone's self-propagating `extend` inheritance method.
91 media.controller.Region.extend = Backbone.Model.extend;
93 _.extend( media.controller.Region.prototype, {
97 * @param {string} mode
99 * @fires wp.media.controller.Region#{id}:activate:{mode}
100 * @fires wp.media.controller.Region#{id}:deactivate:{mode}
102 * @returns {wp.media.controller.Region} Returns itself to allow chaining
104 mode: function( mode ) {
108 // Bail if we're trying to change to the current mode.
109 if ( mode === this._mode ) {
113 this.trigger('deactivate');
116 this.trigger('activate');
120 * Render a new mode, the view is set in the `create` callback method
121 * of the extending class
123 * If no mode is provided, just re-render the current mode.
124 * If the provided mode isn't active, perform a full switch.
126 * @param {string} mode
128 * @fires wp.media.controller.Region#{id}:create:{mode}
129 * @fires wp.media.controller.Region#{id}:render:{mode}
131 * @returns {wp.media.controller.Region} Returns itself to allow chaining
133 render: function( mode ) {
134 if ( mode && mode !== this._mode ) {
135 return this.mode( mode );
138 var set = { view: null },
141 this.trigger( 'create', set );
143 this.trigger( 'render', view );
151 * @returns {wp.media.View} Returns the selector's first subview
154 return this.view.views.first( this.selector );
158 * @param {Array|Object} views
159 * @param {Object} [options={}]
160 * @returns {wp.Backbone.Subviews} Subviews is returned to allow chaining
162 set: function( views, options ) {
166 return this.view.views.set( this.selector, views, options );
170 * Helper function to trigger view events based on {id}:{event}:{mode}
172 * @param {string} event
173 * @returns {undefined|wp.media.controller.Region} Returns itself to allow chaining
175 trigger: function( event ) {
178 if ( ! this._mode ) {
182 args = _.toArray( arguments );
183 base = this.id + ':' + event;
185 // Trigger `region:action:mode` event.
186 args[0] = base + ':' + this._mode;
187 this.view.trigger.apply( this.view, args );
189 // Trigger `region:action` event.
191 this.view.trigger.apply( this.view, args );
197 * wp.media.controller.StateMachine
200 * @augments Backbone.Model
202 * @mixes Backbone.Events
204 * @param {Array} states
206 media.controller.StateMachine = function( states ) {
207 this.states = new Backbone.Collection( states );
210 // Use Backbone's self-propagating `extend` inheritance method.
211 media.controller.StateMachine.extend = Backbone.Model.extend;
213 // Add events to the `StateMachine`.
214 _.extend( media.controller.StateMachine.prototype, Backbone.Events, {
218 * If no `id` is provided, returns the active state.
220 * Implicitly creates states.
222 * Ensure that the `states` collection exists so the `StateMachine`
223 * can be used as a mixin.
226 * @returns {wp.media.controller.State} Returns a State model
227 * from the StateMachine collection
229 state: function( id ) {
230 this.states = this.states || new Backbone.Collection();
232 // Default to the active state.
233 id = id || this._state;
235 if ( id && ! this.states.get( id ) ) {
236 this.states.add({ id: id });
238 return this.states.get( id );
242 * Sets the active state.
244 * Bail if we're trying to select the current state, if we haven't
245 * created the `states` collection, or are trying to select a state
246 * that does not exist.
250 * @fires wp.media.controller.State#deactivate
251 * @fires wp.media.controller.State#activate
253 * @returns {wp.media.controller.StateMachine} Returns itself to allow chaining
255 setState: function( id ) {
256 var previous = this.state();
258 if ( ( previous && id === previous.id ) || ! this.states || ! this.states.get( id ) ) {
263 previous.trigger('deactivate');
264 this._lastState = previous.id;
268 this.state().trigger('activate');
274 * Returns the previous active state.
276 * Call the `state()` method with no parameters to retrieve the current
279 * @returns {wp.media.controller.State} Returns a State model
280 * from the StateMachine collection
282 lastState: function() {
283 if ( this._lastState ) {
284 return this.state( this._lastState );
289 // Map methods from the `states` collection to the `StateMachine` itself.
290 _.each([ 'on', 'off', 'trigger' ], function( method ) {
292 * @returns {wp.media.controller.StateMachine} Returns itself to allow chaining
294 media.controller.StateMachine.prototype[ method ] = function() {
295 // Ensure that the `states` collection exists so the `StateMachine`
296 // can be used as a mixin.
297 this.states = this.states || new Backbone.Collection();
298 // Forward the method to the `states` collection.
299 this.states[ method ].apply( this.states, arguments );
305 * wp.media.controller.State
307 * A state is a step in a workflow that when set will trigger
308 * the controllers for the regions to be updated as specified. This
309 * class is the base class that the various states used in the media
313 * @augments Backbone.Model
315 media.controller.State = Backbone.Model.extend({
316 constructor: function() {
317 this.on( 'activate', this._preActivate, this );
318 this.on( 'activate', this.activate, this );
319 this.on( 'activate', this._postActivate, this );
320 this.on( 'deactivate', this._deactivate, this );
321 this.on( 'deactivate', this.deactivate, this );
322 this.on( 'reset', this.reset, this );
323 this.on( 'ready', this._ready, this );
324 this.on( 'ready', this.ready, this );
326 * Call parent constructor with passed arguments
328 Backbone.Model.apply( this, arguments );
329 this.on( 'change:menu', this._updateMenu, this );
335 ready: function() {},
339 activate: function() {},
343 deactivate: function() {},
347 reset: function() {},
357 _preActivate: function() {
363 _postActivate: function() {
364 this.on( 'change:menu', this._menu, this );
365 this.on( 'change:titleMode', this._title, this );
366 this.on( 'change:content', this._content, this );
367 this.on( 'change:toolbar', this._toolbar, this );
369 this.frame.on( 'title:render:default', this._renderTitle, this );
380 _deactivate: function() {
383 this.frame.off( 'title:render:default', this._renderTitle, this );
385 this.off( 'change:menu', this._menu, this );
386 this.off( 'change:titleMode', this._title, this );
387 this.off( 'change:content', this._content, this );
388 this.off( 'change:toolbar', this._toolbar, this );
394 this.frame.title.render( this.get('titleMode') || 'default' );
399 _renderTitle: function( view ) {
400 view.$el.text( this.get('title') || '' );
405 _router: function() {
406 var router = this.frame.router,
407 mode = this.get('router'),
410 this.frame.$el.toggleClass( 'hide-router', ! mode );
415 this.frame.router.render( mode );
418 if ( view && view.select ) {
419 view.select( this.frame.content.mode() );
426 var menu = this.frame.menu,
427 mode = this.get('menu'),
437 if ( view && view.select ) {
438 view.select( this.id );
444 _updateMenu: function() {
445 var previous = this.previous('menu'),
446 menu = this.get('menu');
449 this.frame.off( 'menu:render:' + previous, this._renderMenu, this );
453 this.frame.on( 'menu:render:' + menu, this._renderMenu, this );
459 _renderMenu: function( view ) {
460 var menuItem = this.get('menuItem'),
461 title = this.get('title'),
462 priority = this.get('priority');
464 if ( ! menuItem && title ) {
465 menuItem = { text: title };
468 menuItem.priority = priority;
476 view.set( this.id, menuItem );
480 _.each(['toolbar','content'], function( region ) {
484 media.controller.State.prototype[ '_' + region ] = function() {
485 var mode = this.get( region );
487 this.frame[ region ].render( mode );
492 media.selectionSync = {
493 syncSelection: function() {
494 var selection = this.get('selection'),
495 manager = this.frame._selection;
497 if ( ! this.get('syncSelection') || ! manager || ! selection ) {
501 // If the selection supports multiple items, validate the stored
502 // attachments based on the new selection's conditions. Record
503 // the attachments that are not included; we'll maintain a
504 // reference to those. Other attachments are considered in flux.
505 if ( selection.multiple ) {
506 selection.reset( [], { silent: true });
507 selection.validateAll( manager.attachments );
508 manager.difference = _.difference( manager.attachments.models, selection.models );
511 // Sync the selection's single item with the master.
512 selection.single( manager.single );
516 * Record the currently active attachments, which is a combination
517 * of the selection's attachments and the set of selected
518 * attachments that this specific selection considered invalid.
519 * Reset the difference and record the single attachment.
521 recordSelection: function() {
522 var selection = this.get('selection'),
523 manager = this.frame._selection;
525 if ( ! this.get('syncSelection') || ! manager || ! selection ) {
529 if ( selection.multiple ) {
530 manager.attachments.reset( selection.toArray().concat( manager.difference ) );
531 manager.difference = [];
533 manager.attachments.add( selection.toArray() );
536 manager.single = selection._single;
541 * wp.media.controller.Library
544 * @augments wp.media.controller.State
545 * @augments Backbone.Model
547 media.controller.Library = media.controller.State.extend({
550 multiple: false, // false, 'add', 'reset'
560 title: l10n.mediaLibraryTitle,
562 // Uses a user setting to override the content mode.
563 contentUserSetting: true,
565 // Sync the selection from the last state when 'multiple' matches.
570 * If a library isn't provided, query all media items.
571 * If a selection instance isn't provided, create one.
573 initialize: function() {
574 var selection = this.get('selection'),
577 if ( ! this.get('library') ) {
578 this.set( 'library', media.query() );
581 if ( ! (selection instanceof media.model.Selection) ) {
585 props = this.get('library').props.toJSON();
586 props = _.omit( props, 'orderby', 'query' );
589 // If the `selection` attribute is set to an object,
590 // it will use those values as the selection instance's
591 // `props` model. Otherwise, it will copy the library's
593 this.set( 'selection', new media.model.Selection( null, {
594 multiple: this.get('multiple'),
599 if ( ! this.get('edge') ) {
600 this.set( 'edge', 120 );
603 if ( ! this.get('gutter') ) {
604 this.set( 'gutter', 8 );
607 this.resetDisplays();
610 activate: function() {
611 this.syncSelection();
613 wp.Uploader.queue.on( 'add', this.uploading, this );
615 this.get('selection').on( 'add remove reset', this.refreshContent, this );
617 if ( this.get('contentUserSetting') ) {
618 this.frame.on( 'content:activate', this.saveContentMode, this );
619 this.set( 'content', getUserSetting( 'libraryContent', this.get('content') ) );
623 deactivate: function() {
624 this.recordSelection();
626 this.frame.off( 'content:activate', this.saveContentMode, this );
628 // Unbind all event handlers that use this state as the context
629 // from the selection.
630 this.get('selection').off( null, null, this );
632 wp.Uploader.queue.off( null, null, this );
636 this.get('selection').reset();
637 this.resetDisplays();
638 this.refreshContent();
641 resetDisplays: function() {
642 var defaultProps = media.view.settings.defaultProps;
644 this._defaultDisplaySettings = {
645 align: defaultProps.align || getUserSetting( 'align', 'none' ),
646 size: defaultProps.size || getUserSetting( 'imgsize', 'medium' ),
647 link: defaultProps.link || getUserSetting( 'urlbutton', 'file' )
652 * @param {wp.media.model.Attachment} attachment
653 * @returns {Backbone.Model}
655 display: function( attachment ) {
656 var displays = this._displays;
658 if ( ! displays[ attachment.cid ] ) {
659 displays[ attachment.cid ] = new Backbone.Model( this.defaultDisplaySettings( attachment ) );
661 return displays[ attachment.cid ];
665 * @param {wp.media.model.Attachment} attachment
668 defaultDisplaySettings: function( attachment ) {
669 var settings = this._defaultDisplaySettings;
670 if ( settings.canEmbed = this.canEmbed( attachment ) ) {
671 settings.link = 'embed';
677 * @param {wp.media.model.Attachment} attachment
680 canEmbed: function( attachment ) {
681 // If uploading, we know the filename but not the mime type.
682 if ( ! attachment.get('uploading') ) {
683 var type = attachment.get('type');
684 if ( type !== 'audio' && type !== 'video' ) {
689 return _.contains( media.view.settings.embedExts, attachment.get('filename').split('.').pop() );
694 * If the state is active, no items are selected, and the current
695 * content mode is not an option in the state's router (provided
696 * the state has a router), reset the content mode to the default.
698 refreshContent: function() {
699 var selection = this.get('selection'),
701 router = frame.router.get(),
702 mode = frame.content.mode();
704 if ( this.active && ! selection.length && router && ! router.get( mode ) ) {
705 this.frame.content.render( this.get('content') );
710 * If the uploader was selected, navigate to the browser.
712 * Automatically select any uploading attachments.
714 * Selections that don't support multiple attachments automatically
715 * limit themselves to one attachment (in this case, the last
716 * attachment in the upload queue).
718 * @param {wp.media.model.Attachment} attachment
720 uploading: function( attachment ) {
721 var content = this.frame.content;
723 if ( 'upload' === content.mode() ) {
724 this.frame.content.mode('browse');
726 this.get('selection').add( attachment );
730 * Only track the browse router on library states.
732 saveContentMode: function() {
733 if ( 'browse' !== this.get('router') ) {
737 var mode = this.frame.content.mode(),
738 view = this.frame.router.get();
740 if ( view && view.get( mode ) ) {
741 setUserSetting( 'libraryContent', mode );
746 _.extend( media.controller.Library.prototype, media.selectionSync );
749 * wp.media.controller.ImageDetails
752 * @augments wp.media.controller.State
753 * @augments Backbone.Model
755 media.controller.ImageDetails = media.controller.State.extend({
756 defaults: _.defaults({
758 toolbar: 'image-details',
759 title: l10n.imageDetailsTitle,
760 content: 'image-details',
761 menu: 'image-details',
766 }, media.controller.Library.prototype.defaults ),
768 initialize: function( options ) {
769 this.image = options.image;
770 media.controller.State.prototype.initialize.apply( this, arguments );
773 activate: function() {
774 this.frame.modal.$el.addClass('image-details');
779 * wp.media.controller.GalleryEdit
782 * @augments wp.media.controller.Library
783 * @augments wp.media.controller.State
784 * @augments Backbone.Model
786 media.controller.GalleryEdit = media.controller.Library.extend({
795 toolbar: 'gallery-edit',
797 title: l10n.editGalleryTitle,
801 // Don't sync the selection, as the Edit Gallery library
802 // *is* the selection.
806 initialize: function() {
807 // If we haven't been provided a `library`, create a `Selection`.
808 if ( ! this.get('library') )
809 this.set( 'library', new media.model.Selection() );
811 // The single `Attachment` view to be used in the `Attachments` view.
812 if ( ! this.get('AttachmentView') )
813 this.set( 'AttachmentView', media.view.Attachment.EditLibrary );
814 media.controller.Library.prototype.initialize.apply( this, arguments );
817 activate: function() {
818 var library = this.get('library');
820 // Limit the library to images only.
821 library.props.set( 'type', 'image' );
823 // Watch for uploaded attachments.
824 this.get('library').observe( wp.Uploader.queue );
826 this.frame.on( 'content:render:browse', this.gallerySettings, this );
828 media.controller.Library.prototype.activate.apply( this, arguments );
831 deactivate: function() {
832 // Stop watching for uploaded attachments.
833 this.get('library').unobserve( wp.Uploader.queue );
835 this.frame.off( 'content:render:browse', this.gallerySettings, this );
837 media.controller.Library.prototype.deactivate.apply( this, arguments );
840 gallerySettings: function( browser ) {
841 var library = this.get('library');
843 if ( ! library || ! browser )
846 library.gallery = library.gallery || new Backbone.Model();
848 browser.sidebar.set({
849 gallery: new media.view.Settings.Gallery({
851 model: library.gallery,
856 browser.toolbar.set( 'reverse', {
857 text: l10n.reverseOrder,
861 library.reset( library.toArray().reverse() );
868 * wp.media.controller.GalleryAdd
871 * @augments wp.media.controller.Library
872 * @augments wp.media.controller.State
873 * @augments Backbone.Model
875 media.controller.GalleryAdd = media.controller.Library.extend({
876 defaults: _.defaults({
877 id: 'gallery-library',
878 filterable: 'uploaded',
881 toolbar: 'gallery-add',
882 title: l10n.addToGalleryTitle,
885 // Don't sync the selection, as the Edit Gallery library
886 // *is* the selection.
888 }, media.controller.Library.prototype.defaults ),
890 initialize: function() {
891 // If we haven't been provided a `library`, create a `Selection`.
892 if ( ! this.get('library') )
893 this.set( 'library', media.query({ type: 'image' }) );
895 media.controller.Library.prototype.initialize.apply( this, arguments );
898 activate: function() {
899 var library = this.get('library'),
900 edit = this.frame.state('gallery-edit').get('library');
902 if ( this.editLibrary && this.editLibrary !== edit )
903 library.unobserve( this.editLibrary );
905 // Accepts attachments that exist in the original library and
906 // that do not exist in gallery's library.
907 library.validator = function( attachment ) {
908 return !! this.mirroring.get( attachment.cid ) && ! edit.get( attachment.cid ) && media.model.Selection.prototype.validator.apply( this, arguments );
911 // Reset the library to ensure that all attachments are re-added
912 // to the collection. Do so silently, as calling `observe` will
913 // trigger the `reset` event.
914 library.reset( library.mirroring.models, { silent: true });
915 library.observe( edit );
916 this.editLibrary = edit;
918 media.controller.Library.prototype.activate.apply( this, arguments );
923 * wp.media.controller.CollectionEdit
926 * @augments wp.media.controller.Library
927 * @augments wp.media.controller.State
928 * @augments Backbone.Model
930 media.controller.CollectionEdit = media.controller.Library.extend({
943 // Don't sync the selection, as the Edit {Collection} library
944 // *is* the selection.
948 initialize: function() {
949 var collectionType = this.get('collectionType');
951 if ( 'video' === this.get( 'type' ) ) {
952 collectionType = 'video-' + collectionType;
955 this.set( 'id', collectionType + '-edit' );
956 this.set( 'toolbar', collectionType + '-edit' );
958 // If we haven't been provided a `library`, create a `Selection`.
959 if ( ! this.get('library') ) {
960 this.set( 'library', new media.model.Selection() );
962 // The single `Attachment` view to be used in the `Attachments` view.
963 if ( ! this.get('AttachmentView') ) {
964 this.set( 'AttachmentView', media.view.Attachment.EditLibrary );
966 media.controller.Library.prototype.initialize.apply( this, arguments );
969 activate: function() {
970 var library = this.get('library');
972 // Limit the library to images only.
973 library.props.set( 'type', this.get( 'type' ) );
975 // Watch for uploaded attachments.
976 this.get('library').observe( wp.Uploader.queue );
978 this.frame.on( 'content:render:browse', this.renderSettings, this );
980 media.controller.Library.prototype.activate.apply( this, arguments );
983 deactivate: function() {
984 // Stop watching for uploaded attachments.
985 this.get('library').unobserve( wp.Uploader.queue );
987 this.frame.off( 'content:render:browse', this.renderSettings, this );
989 media.controller.Library.prototype.deactivate.apply( this, arguments );
992 renderSettings: function( browser ) {
993 var library = this.get('library'),
994 collectionType = this.get('collectionType'),
995 dragInfoText = this.get('dragInfoText'),
996 SettingsView = this.get('SettingsView'),
999 if ( ! library || ! browser ) {
1003 library[ collectionType ] = library[ collectionType ] || new Backbone.Model();
1005 obj[ collectionType ] = new SettingsView({
1007 model: library[ collectionType ],
1011 browser.sidebar.set( obj );
1013 if ( dragInfoText ) {
1014 browser.toolbar.set( 'dragInfo', new media.View({
1015 el: $( '<div class="instructions">' + dragInfoText + '</div>' )[0],
1020 browser.toolbar.set( 'reverse', {
1021 text: l10n.reverseOrder,
1025 library.reset( library.toArray().reverse() );
1032 * wp.media.controller.CollectionAdd
1035 * @augments wp.media.controller.Library
1036 * @augments wp.media.controller.State
1037 * @augments Backbone.Model
1039 media.controller.CollectionAdd = media.controller.Library.extend({
1040 defaults: _.defaults( {
1041 filterable: 'uploaded',
1044 syncSelection: false
1045 }, media.controller.Library.prototype.defaults ),
1047 initialize: function() {
1048 var collectionType = this.get('collectionType');
1050 if ( 'video' === this.get( 'type' ) ) {
1051 collectionType = 'video-' + collectionType;
1054 this.set( 'id', collectionType + '-library' );
1055 this.set( 'toolbar', collectionType + '-add' );
1056 this.set( 'menu', collectionType );
1058 // If we haven't been provided a `library`, create a `Selection`.
1059 if ( ! this.get('library') ) {
1060 this.set( 'library', media.query({ type: this.get('type') }) );
1062 media.controller.Library.prototype.initialize.apply( this, arguments );
1065 activate: function() {
1066 var library = this.get('library'),
1067 editLibrary = this.get('editLibrary'),
1068 edit = this.frame.state( this.get('collectionType') + '-edit' ).get('library');
1070 if ( editLibrary && editLibrary !== edit ) {
1071 library.unobserve( editLibrary );
1074 // Accepts attachments that exist in the original library and
1075 // that do not exist in gallery's library.
1076 library.validator = function( attachment ) {
1077 return !! this.mirroring.get( attachment.cid ) && ! edit.get( attachment.cid ) && media.model.Selection.prototype.validator.apply( this, arguments );
1080 // Reset the library to ensure that all attachments are re-added
1081 // to the collection. Do so silently, as calling `observe` will
1082 // trigger the `reset` event.
1083 library.reset( library.mirroring.models, { silent: true });
1084 library.observe( edit );
1085 this.set('editLibrary', edit);
1087 media.controller.Library.prototype.activate.apply( this, arguments );
1092 * wp.media.controller.FeaturedImage
1095 * @augments wp.media.controller.Library
1096 * @augments wp.media.controller.State
1097 * @augments Backbone.Model
1099 media.controller.FeaturedImage = media.controller.Library.extend({
1100 defaults: _.defaults({
1101 id: 'featured-image',
1102 filterable: 'uploaded',
1104 toolbar: 'featured-image',
1105 title: l10n.setFeaturedImageTitle,
1108 }, media.controller.Library.prototype.defaults ),
1110 initialize: function() {
1111 var library, comparator;
1113 // If we haven't been provided a `library`, create a `Selection`.
1114 if ( ! this.get('library') ) {
1115 this.set( 'library', media.query({ type: 'image' }) );
1118 media.controller.Library.prototype.initialize.apply( this, arguments );
1120 library = this.get('library');
1121 comparator = library.comparator;
1123 // Overload the library's comparator to push items that are not in
1124 // the mirrored query to the front of the aggregate collection.
1125 library.comparator = function( a, b ) {
1126 var aInQuery = !! this.mirroring.get( a.cid ),
1127 bInQuery = !! this.mirroring.get( b.cid );
1129 if ( ! aInQuery && bInQuery ) {
1131 } else if ( aInQuery && ! bInQuery ) {
1134 return comparator.apply( this, arguments );
1138 // Add all items in the selection to the library, so any featured
1139 // images that are not initially loaded still appear.
1140 library.observe( this.get('selection') );
1143 activate: function() {
1144 this.updateSelection();
1145 this.frame.on( 'open', this.updateSelection, this );
1147 media.controller.Library.prototype.activate.apply( this, arguments );
1150 deactivate: function() {
1151 this.frame.off( 'open', this.updateSelection, this );
1153 media.controller.Library.prototype.deactivate.apply( this, arguments );
1156 updateSelection: function() {
1157 var selection = this.get('selection'),
1158 id = media.view.settings.post.featuredImageId,
1161 if ( '' !== id && -1 !== id ) {
1162 attachment = media.model.Attachment.get( id );
1166 selection.reset( attachment ? [ attachment ] : [] );
1171 * wp.media.controller.ReplaceImage
1173 * Replace a selected single image
1176 * @augments wp.media.controller.Library
1177 * @augments wp.media.controller.State
1178 * @augments Backbone.Model
1180 media.controller.ReplaceImage = media.controller.Library.extend({
1181 defaults: _.defaults({
1182 id: 'replace-image',
1183 filterable: 'uploaded',
1186 title: l10n.replaceImageTitle,
1189 }, media.controller.Library.prototype.defaults ),
1191 initialize: function( options ) {
1192 var library, comparator;
1194 this.image = options.image;
1195 // If we haven't been provided a `library`, create a `Selection`.
1196 if ( ! this.get('library') ) {
1197 this.set( 'library', media.query({ type: 'image' }) );
1200 media.controller.Library.prototype.initialize.apply( this, arguments );
1202 library = this.get('library');
1203 comparator = library.comparator;
1205 // Overload the library's comparator to push items that are not in
1206 // the mirrored query to the front of the aggregate collection.
1207 library.comparator = function( a, b ) {
1208 var aInQuery = !! this.mirroring.get( a.cid ),
1209 bInQuery = !! this.mirroring.get( b.cid );
1211 if ( ! aInQuery && bInQuery ) {
1213 } else if ( aInQuery && ! bInQuery ) {
1216 return comparator.apply( this, arguments );
1220 // Add all items in the selection to the library, so any featured
1221 // images that are not initially loaded still appear.
1222 library.observe( this.get('selection') );
1225 activate: function() {
1226 this.updateSelection();
1227 media.controller.Library.prototype.activate.apply( this, arguments );
1230 updateSelection: function() {
1231 var selection = this.get('selection'),
1232 attachment = this.image.attachment;
1234 selection.reset( attachment ? [ attachment ] : [] );
1239 * wp.media.controller.EditImage
1242 * @augments wp.media.controller.State
1243 * @augments Backbone.Model
1245 media.controller.EditImage = media.controller.State.extend({
1250 toolbar: 'edit-image',
1251 title: l10n.editImage,
1252 content: 'edit-image'
1255 activate: function() {
1256 this.listenTo( this.frame, 'toolbar:render:edit-image', this.toolbar );
1259 deactivate: function() {
1260 this.stopListening( this.frame );
1263 toolbar: function() {
1264 var frame = this.frame,
1265 lastState = frame.lastState(),
1266 previous = lastState && lastState.id;
1268 frame.toolbar.set( new media.view.Toolbar({
1277 frame.setState( previous );
1289 * wp.media.controller.MediaLibrary
1292 * @augments wp.media.controller.Library
1293 * @augments wp.media.controller.State
1294 * @augments Backbone.Model
1296 media.controller.MediaLibrary = media.controller.Library.extend({
1297 defaults: _.defaults({
1298 filterable: 'uploaded',
1300 syncSelection: false,
1301 displaySettings: false
1302 }, media.controller.Library.prototype.defaults ),
1304 initialize: function( options ) {
1305 this.media = options.media;
1306 this.type = options.type;
1307 this.set( 'library', media.query({ type: this.type }) );
1309 media.controller.Library.prototype.initialize.apply( this, arguments );
1312 activate: function() {
1313 if ( media.frame.lastMime ) {
1314 this.set( 'library', media.query({ type: media.frame.lastMime }) );
1315 delete media.frame.lastMime;
1317 media.controller.Library.prototype.activate.apply( this, arguments );
1322 * wp.media.controller.Embed
1325 * @augments wp.media.controller.State
1326 * @augments Backbone.Model
1328 media.controller.Embed = media.controller.State.extend({
1334 toolbar: 'main-embed',
1337 title: l10n.insertFromUrlTitle,
1341 // The amount of time used when debouncing the scan.
1344 initialize: function() {
1345 this.debouncedScan = _.debounce( _.bind( this.scan, this ), this.sensitivity );
1346 this.props = new Backbone.Model({ url: '' });
1347 this.props.on( 'change:url', this.debouncedScan, this );
1348 this.props.on( 'change:url', this.refresh, this );
1349 this.on( 'scan', this.scanImage, this );
1353 * @fires wp.media.controller.Embed#scan
1363 // Scan is triggered with the list of `attributes` to set on the
1364 // state, useful for the 'type' attribute and 'scanners' attribute,
1365 // an array of promise objects for asynchronous scan operations.
1366 if ( this.props.get('url') ) {
1367 this.trigger( 'scan', attributes );
1370 if ( attributes.scanners.length ) {
1371 scanners = attributes.scanners = $.when.apply( $, attributes.scanners );
1372 scanners.always( function() {
1373 if ( embed.get('scanners') === scanners ) {
1374 embed.set( 'loading', false );
1378 attributes.scanners = null;
1381 attributes.loading = !! attributes.scanners;
1382 this.set( attributes );
1385 * @param {Object} attributes
1387 scanImage: function( attributes ) {
1388 var frame = this.frame,
1390 url = this.props.get('url'),
1391 image = new Image(),
1392 deferred = $.Deferred();
1394 attributes.scanners.push( deferred.promise() );
1396 // Try to load the image and find its width/height.
1397 image.onload = function() {
1400 if ( state !== frame.state() || url !== state.props.get('url') ) {
1410 height: image.height
1414 image.onerror = deferred.reject;
1418 refresh: function() {
1419 this.frame.toolbar.get().refresh();
1423 this.props.clear().set({ url: '' });
1425 if ( this.active ) {
1432 * wp.media.controller.Cropper
1434 * Allows for a cropping step.
1437 * @augments wp.media.controller.State
1438 * @augments Backbone.Model
1440 media.controller.Cropper = media.controller.State.extend({
1443 title: l10n.cropImage,
1450 activate: function() {
1451 this.frame.on( 'content:create:crop', this.createCropContent, this );
1452 this.frame.on( 'close', this.removeCropper, this );
1453 this.set('selection', new Backbone.Collection(this.frame._selection.single));
1456 deactivate: function() {
1457 this.frame.toolbar.mode('browse');
1460 createCropContent: function() {
1461 this.cropperView = new wp.media.view.Cropper({controller: this,
1462 attachment: this.get('selection').first() });
1463 this.cropperView.on('image-loaded', this.createCropToolbar, this);
1464 this.frame.content.set(this.cropperView);
1467 removeCropper: function() {
1468 this.imgSelect.cancelSelection();
1469 this.imgSelect.setOptions({remove: true});
1470 this.imgSelect.update();
1471 this.cropperView.remove();
1473 createCropToolbar: function() {
1474 var canSkipCrop, toolbarOptions;
1476 canSkipCrop = this.get('canSkipCrop') || false;
1479 controller: this.frame,
1483 text: l10n.cropImage,
1485 requires: { library: false, selection: false },
1489 selection = this.controller.state().get('selection').first();
1491 selection.set({cropDetails: this.controller.state().imgSelect.getSelection()});
1493 this.$el.text(l10n.cropping);
1494 this.$el.attr('disabled', true);
1495 this.controller.state().doCrop( selection ).done( function( croppedImage ) {
1496 self.controller.trigger('cropped', croppedImage );
1497 self.controller.close();
1498 }).fail( function() {
1499 self.controller.trigger('content:error:crop');
1506 if ( canSkipCrop ) {
1507 _.extend( toolbarOptions.items, {
1510 text: l10n.skipCropping,
1512 requires: { library: false, selection: false },
1514 var selection = this.controller.state().get('selection').first();
1515 this.controller.state().cropperView.remove();
1516 this.controller.trigger('skippedcrop', selection);
1517 this.controller.close();
1523 this.frame.toolbar.set( new wp.media.view.Toolbar(toolbarOptions) );
1526 doCrop: function( attachment ) {
1527 return wp.ajax.post( 'custom-header-crop', {
1528 nonce: attachment.get('nonces').edit,
1529 id: attachment.get('id'),
1530 cropDetails: attachment.get('cropDetails')
1536 * ========================================================================
1538 * ========================================================================
1545 * The base view class.
1547 * Undelegating events, removing events from the model, and
1548 * removing events from the controller mirror the code for
1549 * `Backbone.View.dispose` in Backbone 0.9.8 development.
1551 * This behavior has since been removed, and should not be used
1552 * outside of the media manager.
1555 * @augments wp.Backbone.View
1556 * @augments Backbone.View
1558 media.View = wp.Backbone.View.extend({
1559 constructor: function( options ) {
1560 if ( options && options.controller ) {
1561 this.controller = options.controller;
1563 wp.Backbone.View.apply( this, arguments );
1566 * @returns {wp.media.View} Returns itself to allow chaining
1568 dispose: function() {
1569 // Undelegating events, removing events from the model, and
1570 // removing events from the controller mirror the code for
1571 // `Backbone.View.dispose` in Backbone 0.9.8 development.
1572 this.undelegateEvents();
1574 if ( this.model && this.model.off ) {
1575 this.model.off( null, null, this );
1578 if ( this.collection && this.collection.off ) {
1579 this.collection.off( null, null, this );
1582 // Unbind controller events.
1583 if ( this.controller && this.controller.off ) {
1584 this.controller.off( null, null, this );
1590 * @returns {wp.media.View} Returns itself to allow chaining
1592 remove: function() {
1595 * call 'remove' directly on the parent class
1597 return wp.Backbone.View.prototype.remove.apply( this, arguments );
1602 * wp.media.view.Frame
1604 * A frame is a composite view consisting of one or more regions and one or more
1605 * states. Only one state can be active at any given moment.
1608 * @augments wp.media.View
1609 * @augments wp.Backbone.View
1610 * @augments Backbone.View
1611 * @mixes wp.media.controller.StateMachine
1613 media.view.Frame = media.View.extend({
1614 initialize: function() {
1615 this._createRegions();
1616 this._createStates();
1619 _createRegions: function() {
1620 // Clone the regions array.
1621 this.regions = this.regions ? this.regions.slice() : [];
1623 // Initialize regions.
1624 _.each( this.regions, function( region ) {
1625 this[ region ] = new media.controller.Region({
1628 selector: '.media-frame-' + region
1633 * @fires wp.media.controller.State#ready
1635 _createStates: function() {
1636 // Create the default `states` collection.
1637 this.states = new Backbone.Collection( null, {
1638 model: media.controller.State
1641 // Ensure states have a reference to the frame.
1642 this.states.on( 'add', function( model ) {
1644 model.trigger('ready');
1647 if ( this.options.states ) {
1648 this.states.add( this.options.states );
1652 * @returns {wp.media.view.Frame} Returns itself to allow chaining
1655 this.states.invoke( 'trigger', 'reset' );
1660 // Make the `Frame` a `StateMachine`.
1661 _.extend( media.view.Frame.prototype, media.controller.StateMachine.prototype );
1664 * wp.media.view.MediaFrame
1666 * Type of frame used to create the media modal.
1669 * @augments wp.media.view.Frame
1670 * @augments wp.media.View
1671 * @augments wp.Backbone.View
1672 * @augments Backbone.View
1673 * @mixes wp.media.controller.StateMachine
1675 media.view.MediaFrame = media.view.Frame.extend({
1676 className: 'media-frame',
1677 template: media.template('media-frame'),
1678 regions: ['menu','title','content','toolbar','router'],
1681 * @global wp.Uploader
1683 initialize: function() {
1685 media.view.Frame.prototype.initialize.apply( this, arguments );
1687 _.defaults( this.options, {
1693 // Ensure core UI is enabled.
1694 this.$el.addClass('wp-core-ui');
1696 // Initialize modal container view.
1697 if ( this.options.modal ) {
1698 this.modal = new media.view.Modal({
1700 title: this.options.title
1703 this.modal.content( this );
1706 // Force the uploader off if the upload limit has been exceeded or
1707 // if the browser isn't supported.
1708 if ( wp.Uploader.limitExceeded || ! wp.Uploader.browser.supported ) {
1709 this.options.uploader = false;
1712 // Initialize window-wide uploader.
1713 if ( this.options.uploader ) {
1714 this.uploader = new media.view.UploaderWindow({
1717 dropzone: this.modal ? this.modal.$el : this.$el,
1721 this.views.set( '.media-frame-uploader', this.uploader );
1724 this.on( 'attach', _.bind( this.views.ready, this.views ), this );
1726 // Bind default title creation.
1727 this.on( 'title:create:default', this.createTitle, this );
1728 this.title.mode('default');
1730 // Bind default menu.
1731 this.on( 'menu:create:default', this.createMenu, this );
1734 * @returns {wp.media.view.MediaFrame} Returns itself to allow chaining
1736 render: function() {
1737 // Activate the default state if no active state exists.
1738 if ( ! this.state() && this.options.state ) {
1739 this.setState( this.options.state );
1742 * call 'render' directly on the parent class
1744 return media.view.Frame.prototype.render.apply( this, arguments );
1747 * @param {Object} title
1748 * @this wp.media.controller.Region
1750 createTitle: function( title ) {
1751 title.view = new media.View({
1757 * @param {Object} menu
1758 * @this wp.media.controller.Region
1760 createMenu: function( menu ) {
1761 menu.view = new media.view.Menu({
1766 * @param {Object} toolbar
1767 * @this wp.media.controller.Region
1769 createToolbar: function( toolbar ) {
1770 toolbar.view = new media.view.Toolbar({
1775 * @param {Object} router
1776 * @this wp.media.controller.Region
1778 createRouter: function( router ) {
1779 router.view = new media.view.Router({
1784 * @param {Object} options
1786 createIframeStates: function( options ) {
1787 var settings = media.view.settings,
1788 tabs = settings.tabs,
1789 tabUrl = settings.tabUrl,
1792 if ( ! tabs || ! tabUrl ) {
1796 // Add the post ID to the tab URL if it exists.
1797 $postId = $('#post_ID');
1798 if ( $postId.length ) {
1799 tabUrl += '&post_id=' + $postId.val();
1802 // Generate the tab states.
1803 _.each( tabs, function( title, id ) {
1804 this.state( 'iframe:' + id ).set( _.defaults({
1806 src: tabUrl + '&tab=' + id,
1813 this.on( 'content:create:iframe', this.iframeContent, this );
1814 this.on( 'menu:render:default', this.iframeMenu, this );
1815 this.on( 'open', this.hijackThickbox, this );
1816 this.on( 'close', this.restoreThickbox, this );
1820 * @param {Object} content
1821 * @this wp.media.controller.Region
1823 iframeContent: function( content ) {
1824 this.$el.addClass('hide-toolbar');
1825 content.view = new media.view.Iframe({
1830 iframeMenu: function( view ) {
1837 _.each( media.view.settings.tabs, function( title, id ) {
1838 views[ 'iframe:' + id ] = {
1839 text: this.state( 'iframe:' + id ).get('title'),
1847 hijackThickbox: function() {
1850 if ( ! window.tb_remove || this._tb_remove ) {
1854 this._tb_remove = window.tb_remove;
1855 window.tb_remove = function() {
1858 frame.setState( frame.options.state );
1859 frame._tb_remove.call( window );
1863 restoreThickbox: function() {
1864 if ( ! this._tb_remove ) {
1868 window.tb_remove = this._tb_remove;
1869 delete this._tb_remove;
1873 // Map some of the modal's methods to the frame.
1874 _.each(['open','close','attach','detach','escape'], function( method ) {
1876 * @returns {wp.media.view.MediaFrame} Returns itself to allow chaining
1878 media.view.MediaFrame.prototype[ method ] = function() {
1880 this.modal[ method ].apply( this.modal, arguments );
1887 * wp.media.view.MediaFrame.Select
1889 * Type of media frame that is used to select an item or items from the media library
1892 * @augments wp.media.view.MediaFrame
1893 * @augments wp.media.view.Frame
1894 * @augments wp.media.View
1895 * @augments wp.Backbone.View
1896 * @augments Backbone.View
1897 * @mixes wp.media.controller.StateMachine
1899 media.view.MediaFrame.Select = media.view.MediaFrame.extend({
1900 initialize: function() {
1902 * call 'initialize' directly on the parent class
1904 media.view.MediaFrame.prototype.initialize.apply( this, arguments );
1906 _.defaults( this.options, {
1913 this.createSelection();
1914 this.createStates();
1915 this.bindHandlers();
1918 createSelection: function() {
1919 var selection = this.options.selection;
1921 if ( ! (selection instanceof media.model.Selection) ) {
1922 this.options.selection = new media.model.Selection( selection, {
1923 multiple: this.options.multiple
1928 attachments: new media.model.Attachments(),
1933 createStates: function() {
1934 var options = this.options;
1936 if ( this.options.states ) {
1940 // Add the default states.
1943 new media.controller.Library({
1944 library: media.query( options.library ),
1945 multiple: options.multiple,
1946 title: options.title,
1952 bindHandlers: function() {
1953 this.on( 'router:create:browse', this.createRouter, this );
1954 this.on( 'router:render:browse', this.browseRouter, this );
1955 this.on( 'content:create:browse', this.browseContent, this );
1956 this.on( 'content:render:upload', this.uploadContent, this );
1957 this.on( 'toolbar:create:select', this.createSelectToolbar, this );
1961 browseRouter: function( view ) {
1964 text: l10n.uploadFilesTitle,
1968 text: l10n.mediaLibraryTitle,
1977 * @param {Object} content
1978 * @this wp.media.controller.Region
1980 browseContent: function( content ) {
1981 var state = this.state();
1983 this.$el.removeClass('hide-toolbar');
1985 // Browse our library of attachments.
1986 content.view = new media.view.AttachmentsBrowser({
1988 collection: state.get('library'),
1989 selection: state.get('selection'),
1991 sortable: state.get('sortable'),
1992 search: state.get('searchable'),
1993 filters: state.get('filterable'),
1994 display: state.get('displaySettings'),
1995 dragInfo: state.get('dragInfo'),
1997 suggestedWidth: state.get('suggestedWidth'),
1998 suggestedHeight: state.get('suggestedHeight'),
2000 AttachmentView: state.get('AttachmentView')
2006 * @this wp.media.controller.Region
2008 uploadContent: function() {
2009 this.$el.removeClass('hide-toolbar');
2010 this.content.set( new media.view.UploaderInline({
2018 * @param {Object} toolbar
2019 * @param {Object} [options={}]
2020 * @this wp.media.controller.Region
2022 createSelectToolbar: function( toolbar, options ) {
2023 options = options || this.options.button || {};
2024 options.controller = this;
2026 toolbar.view = new media.view.Toolbar.Select( options );
2031 * wp.media.view.MediaFrame.Post
2034 * @augments wp.media.view.MediaFrame.Select
2035 * @augments wp.media.view.MediaFrame
2036 * @augments wp.media.view.Frame
2037 * @augments wp.media.View
2038 * @augments wp.Backbone.View
2039 * @augments Backbone.View
2040 * @mixes wp.media.controller.StateMachine
2042 media.view.MediaFrame.Post = media.view.MediaFrame.Select.extend({
2043 initialize: function() {
2046 count: media.view.settings.attachmentCounts.audio,
2050 count: media.view.settings.attachmentCounts.video,
2051 state: 'video-playlist'
2055 _.defaults( this.options, {
2061 * call 'initialize' directly on the parent class
2063 media.view.MediaFrame.Select.prototype.initialize.apply( this, arguments );
2064 this.createIframeStates();
2068 createStates: function() {
2069 var options = this.options;
2071 // Add the default states.
2074 new media.controller.Library({
2076 title: l10n.insertMediaTitle,
2078 toolbar: 'main-insert',
2080 library: media.query( options.library ),
2081 multiple: options.multiple ? 'reset' : false,
2084 // If the user isn't allowed to edit fields,
2085 // can they still edit it locally?
2086 allowLocalEdits: true,
2088 // Show the attachment display settings.
2089 displaySettings: true,
2090 // Update user settings when users adjust the
2091 // attachment display settings.
2092 displayUserSettings: true
2095 new media.controller.Library({
2097 title: l10n.createGalleryTitle,
2099 toolbar: 'main-gallery',
2100 filterable: 'uploaded',
2104 library: media.query( _.defaults({
2106 }, options.library ) )
2110 new media.controller.Embed(),
2112 new media.controller.EditImage( { model: options.editImage } ),
2115 new media.controller.GalleryEdit({
2116 library: options.selection,
2117 editing: options.editing,
2121 new media.controller.GalleryAdd(),
2123 new media.controller.Library({
2125 title: l10n.createPlaylistTitle,
2127 toolbar: 'main-playlist',
2128 filterable: 'uploaded',
2132 library: media.query( _.defaults({
2134 }, options.library ) )
2138 new media.controller.CollectionEdit({
2140 collectionType: 'playlist',
2141 title: l10n.editPlaylistTitle,
2142 SettingsView: media.view.Settings.Playlist,
2143 library: options.selection,
2144 editing: options.editing,
2146 dragInfoText: l10n.playlistDragInfo,
2150 new media.controller.CollectionAdd({
2152 collectionType: 'playlist',
2153 title: l10n.addToPlaylistTitle
2156 new media.controller.Library({
2157 id: 'video-playlist',
2158 title: l10n.createVideoPlaylistTitle,
2160 toolbar: 'main-video-playlist',
2161 filterable: 'uploaded',
2165 library: media.query( _.defaults({
2167 }, options.library ) )
2170 new media.controller.CollectionEdit({
2172 collectionType: 'playlist',
2173 title: l10n.editVideoPlaylistTitle,
2174 SettingsView: media.view.Settings.Playlist,
2175 library: options.selection,
2176 editing: options.editing,
2177 menu: 'video-playlist',
2178 dragInfoText: l10n.playlistDragInfo,
2182 new media.controller.CollectionAdd({
2184 collectionType: 'playlist',
2185 title: l10n.addToVideoPlaylistTitle
2189 if ( media.view.settings.post.featuredImageId ) {
2190 this.states.add( new media.controller.FeaturedImage() );
2194 bindHandlers: function() {
2195 var handlers, checkCounts;
2197 media.view.MediaFrame.Select.prototype.bindHandlers.apply( this, arguments );
2199 this.on( 'activate', this.activate, this );
2201 // Only bother checking media type counts if one of the counts is zero
2202 checkCounts = _.find( this.counts, function( type ) {
2203 return type.count === 0;
2206 if ( typeof checkCounts !== 'undefined' ) {
2207 this.listenTo( media.model.Attachments.all, 'change:type', this.mediaTypeCounts );
2210 this.on( 'menu:create:gallery', this.createMenu, this );
2211 this.on( 'menu:create:playlist', this.createMenu, this );
2212 this.on( 'menu:create:video-playlist', this.createMenu, this );
2213 this.on( 'toolbar:create:main-insert', this.createToolbar, this );
2214 this.on( 'toolbar:create:main-gallery', this.createToolbar, this );
2215 this.on( 'toolbar:create:main-playlist', this.createToolbar, this );
2216 this.on( 'toolbar:create:main-video-playlist', this.createToolbar, this );
2217 this.on( 'toolbar:create:featured-image', this.featuredImageToolbar, this );
2218 this.on( 'toolbar:create:main-embed', this.mainEmbedToolbar, this );
2222 'default': 'mainMenu',
2223 'gallery': 'galleryMenu',
2224 'playlist': 'playlistMenu',
2225 'video-playlist': 'videoPlaylistMenu'
2229 'embed': 'embedContent',
2230 'edit-image': 'editImageContent',
2231 'edit-selection': 'editSelectionContent'
2235 'main-insert': 'mainInsertToolbar',
2236 'main-gallery': 'mainGalleryToolbar',
2237 'gallery-edit': 'galleryEditToolbar',
2238 'gallery-add': 'galleryAddToolbar',
2239 'main-playlist': 'mainPlaylistToolbar',
2240 'playlist-edit': 'playlistEditToolbar',
2241 'playlist-add': 'playlistAddToolbar',
2242 'main-video-playlist': 'mainVideoPlaylistToolbar',
2243 'video-playlist-edit': 'videoPlaylistEditToolbar',
2244 'video-playlist-add': 'videoPlaylistAddToolbar'
2248 _.each( handlers, function( regionHandlers, region ) {
2249 _.each( regionHandlers, function( callback, handler ) {
2250 this.on( region + ':render:' + handler, this[ callback ], this );
2255 activate: function() {
2256 // Hide menu items for states tied to particular media types if there are no items
2257 _.each( this.counts, function( type ) {
2258 if ( type.count < 1 ) {
2259 this.menuItemVisibility( type.state, 'hide' );
2264 mediaTypeCounts: function( model, attr ) {
2265 if ( typeof this.counts[ attr ] !== 'undefined' && this.counts[ attr ].count < 1 ) {
2266 this.counts[ attr ].count++;
2267 this.menuItemVisibility( this.counts[ attr ].state, 'show' );
2273 * @param {wp.Backbone.View} view
2275 mainMenu: function( view ) {
2277 'library-separator': new media.View({
2278 className: 'separator',
2284 menuItemVisibility: function( state, visibility ) {
2285 var menu = this.menu.get();
2286 if ( visibility === 'hide' ) {
2288 } else if ( visibility === 'show' ) {
2293 * @param {wp.Backbone.View} view
2295 galleryMenu: function( view ) {
2296 var lastState = this.lastState(),
2297 previous = lastState && lastState.id,
2302 text: l10n.cancelGalleryTitle,
2306 frame.setState( previous );
2312 separateCancel: new media.View({
2313 className: 'separator',
2319 playlistMenu: function( view ) {
2320 var lastState = this.lastState(),
2321 previous = lastState && lastState.id,
2326 text: l10n.cancelPlaylistTitle,
2330 frame.setState( previous );
2336 separateCancel: new media.View({
2337 className: 'separator',
2343 videoPlaylistMenu: function( view ) {
2344 var lastState = this.lastState(),
2345 previous = lastState && lastState.id,
2350 text: l10n.cancelVideoPlaylistTitle,
2354 frame.setState( previous );
2360 separateCancel: new media.View({
2361 className: 'separator',
2368 embedContent: function() {
2369 var view = new media.view.Embed({
2374 this.content.set( view );
2378 editSelectionContent: function() {
2379 var state = this.state(),
2380 selection = state.get('selection'),
2383 view = new media.view.AttachmentsBrowser({
2385 collection: selection,
2386 selection: selection,
2392 AttachmentView: media.view.Attachment.EditSelection
2395 view.toolbar.set( 'backToLibrary', {
2396 text: l10n.returnToLibrary,
2400 this.controller.content.mode('browse');
2404 // Browse our library of attachments.
2405 this.content.set( view );
2408 editImageContent: function() {
2409 var image = this.state().get('image'),
2410 view = new media.view.EditImage( { model: image, controller: this } ).render();
2412 this.content.set( view );
2414 // after creating the wrapper view, load the actual editor via an ajax call
2422 * @param {wp.Backbone.View} view
2424 selectionStatusToolbar: function( view ) {
2425 var editable = this.state().get('editable');
2427 view.set( 'selection', new media.view.Selection({
2429 collection: this.state().get('selection'),
2432 // If the selection is editable, pass the callback to
2433 // switch the content mode.
2434 editable: editable && function() {
2435 this.controller.content.mode('edit-selection');
2441 * @param {wp.Backbone.View} view
2443 mainInsertToolbar: function( view ) {
2444 var controller = this;
2446 this.selectionStatusToolbar( view );
2448 view.set( 'insert', {
2451 text: l10n.insertIntoPost,
2452 requires: { selection: true },
2455 * @fires wp.media.controller.State#insert
2458 var state = controller.state(),
2459 selection = state.get('selection');
2462 state.trigger( 'insert', selection ).reset();
2468 * @param {wp.Backbone.View} view
2470 mainGalleryToolbar: function( view ) {
2471 var controller = this;
2473 this.selectionStatusToolbar( view );
2475 view.set( 'gallery', {
2477 text: l10n.createNewGallery,
2479 requires: { selection: true },
2482 var selection = controller.state().get('selection'),
2483 edit = controller.state('gallery-edit'),
2484 models = selection.where({ type: 'image' });
2486 edit.set( 'library', new media.model.Selection( models, {
2487 props: selection.props.toJSON(),
2491 this.controller.setState('gallery-edit');
2496 mainPlaylistToolbar: function( view ) {
2497 var controller = this;
2499 this.selectionStatusToolbar( view );
2501 view.set( 'playlist', {
2503 text: l10n.createNewPlaylist,
2505 requires: { selection: true },
2508 var selection = controller.state().get('selection'),
2509 edit = controller.state('playlist-edit'),
2510 models = selection.where({ type: 'audio' });
2512 edit.set( 'library', new media.model.Selection( models, {
2513 props: selection.props.toJSON(),
2517 this.controller.setState('playlist-edit');
2522 mainVideoPlaylistToolbar: function( view ) {
2523 var controller = this;
2525 this.selectionStatusToolbar( view );
2527 view.set( 'video-playlist', {
2529 text: l10n.createNewVideoPlaylist,
2531 requires: { selection: true },
2534 var selection = controller.state().get('selection'),
2535 edit = controller.state('video-playlist-edit'),
2536 models = selection.where({ type: 'video' });
2538 edit.set( 'library', new media.model.Selection( models, {
2539 props: selection.props.toJSON(),
2543 this.controller.setState('video-playlist-edit');
2548 featuredImageToolbar: function( toolbar ) {
2549 this.createSelectToolbar( toolbar, {
2550 text: l10n.setFeaturedImage,
2551 state: this.options.state
2555 mainEmbedToolbar: function( toolbar ) {
2556 toolbar.view = new media.view.Toolbar.Embed({
2561 galleryEditToolbar: function() {
2562 var editing = this.state().get('editing');
2563 this.toolbar.set( new media.view.Toolbar({
2568 text: editing ? l10n.updateGallery : l10n.insertGallery,
2570 requires: { library: true },
2573 * @fires wp.media.controller.State#update
2576 var controller = this.controller,
2577 state = controller.state();
2580 state.trigger( 'update', state.get('library') );
2582 // Restore and reset the default state.
2583 controller.setState( controller.options.state );
2591 galleryAddToolbar: function() {
2592 this.toolbar.set( new media.view.Toolbar({
2597 text: l10n.addToGallery,
2599 requires: { selection: true },
2602 * @fires wp.media.controller.State#reset
2605 var controller = this.controller,
2606 state = controller.state(),
2607 edit = controller.state('gallery-edit');
2609 edit.get('library').add( state.get('selection').models );
2610 state.trigger('reset');
2611 controller.setState('gallery-edit');
2618 playlistEditToolbar: function() {
2619 var editing = this.state().get('editing');
2620 this.toolbar.set( new media.view.Toolbar({
2625 text: editing ? l10n.updatePlaylist : l10n.insertPlaylist,
2627 requires: { library: true },
2630 * @fires wp.media.controller.State#update
2633 var controller = this.controller,
2634 state = controller.state();
2637 state.trigger( 'update', state.get('library') );
2639 // Restore and reset the default state.
2640 controller.setState( controller.options.state );
2648 playlistAddToolbar: function() {
2649 this.toolbar.set( new media.view.Toolbar({
2654 text: l10n.addToPlaylist,
2656 requires: { selection: true },
2659 * @fires wp.media.controller.State#reset
2662 var controller = this.controller,
2663 state = controller.state(),
2664 edit = controller.state('playlist-edit');
2666 edit.get('library').add( state.get('selection').models );
2667 state.trigger('reset');
2668 controller.setState('playlist-edit');
2675 videoPlaylistEditToolbar: function() {
2676 var editing = this.state().get('editing');
2677 this.toolbar.set( new media.view.Toolbar({
2682 text: editing ? l10n.updateVideoPlaylist : l10n.insertVideoPlaylist,
2684 requires: { library: true },
2687 var controller = this.controller,
2688 state = controller.state(),
2689 library = state.get('library');
2691 library.type = 'video';
2694 state.trigger( 'update', library );
2696 // Restore and reset the default state.
2697 controller.setState( controller.options.state );
2705 videoPlaylistAddToolbar: function() {
2706 this.toolbar.set( new media.view.Toolbar({
2711 text: l10n.addToVideoPlaylist,
2713 requires: { selection: true },
2716 var controller = this.controller,
2717 state = controller.state(),
2718 edit = controller.state('video-playlist-edit');
2720 edit.get('library').add( state.get('selection').models );
2721 state.trigger('reset');
2722 controller.setState('video-playlist-edit');
2731 * wp.media.view.MediaFrame.ImageDetails
2734 * @augments wp.media.view.MediaFrame.Select
2735 * @augments wp.media.view.MediaFrame
2736 * @augments wp.media.view.Frame
2737 * @augments wp.media.View
2738 * @augments wp.Backbone.View
2739 * @augments Backbone.View
2740 * @mixes wp.media.controller.StateMachine
2742 media.view.MediaFrame.ImageDetails = media.view.MediaFrame.Select.extend({
2746 menu: 'image-details',
2747 content: 'image-details',
2748 toolbar: 'image-details',
2750 title: l10n.imageDetailsTitle,
2754 initialize: function( options ) {
2755 this.image = new media.model.PostImage( options.metadata );
2756 this.options.selection = new media.model.Selection( this.image.attachment, { multiple: false } );
2757 media.view.MediaFrame.Select.prototype.initialize.apply( this, arguments );
2760 bindHandlers: function() {
2761 media.view.MediaFrame.Select.prototype.bindHandlers.apply( this, arguments );
2762 this.on( 'menu:create:image-details', this.createMenu, this );
2763 this.on( 'content:create:image-details', this.imageDetailsContent, this );
2764 this.on( 'content:render:edit-image', this.editImageContent, this );
2765 this.on( 'menu:render:image-details', this.renderMenu, this );
2766 this.on( 'toolbar:render:image-details', this.renderImageDetailsToolbar, this );
2767 // override the select toolbar
2768 this.on( 'toolbar:render:replace', this.renderReplaceImageToolbar, this );
2771 createStates: function() {
2773 new media.controller.ImageDetails({
2776 menu: 'image-details'
2778 new media.controller.ReplaceImage({
2779 id: 'replace-image',
2780 library: media.query( { type: 'image' } ),
2783 title: l10n.imageReplaceTitle,
2784 menu: 'image-details',
2787 displaySettings: true
2789 new media.controller.EditImage( {
2791 selection: this.options.selection
2796 imageDetailsContent: function( options ) {
2797 options.view = new media.view.ImageDetails({
2799 model: this.state().image,
2800 attachment: this.state().image.attachment
2804 editImageContent: function() {
2805 var state = this.state(),
2806 model = state.get('image'),
2813 view = new media.view.EditImage( { model: model, controller: this } ).render();
2815 this.content.set( view );
2817 // after bringing in the frame, load the actual editor via an ajax call
2822 renderMenu: function( view ) {
2823 var lastState = this.lastState(),
2824 previous = lastState && lastState.id,
2829 text: l10n.imageDetailsCancel,
2833 frame.setState( previous );
2839 separateCancel: new media.View({
2840 className: 'separator',
2847 renderImageDetailsToolbar: function() {
2848 this.toolbar.set( new media.view.Toolbar({
2857 var controller = this.controller,
2858 state = controller.state();
2862 // not sure if we want to use wp.media.string.image which will create a shortcode or
2863 // perhaps wp.html.string to at least to build the <img />
2864 state.trigger( 'update', controller.image.toJSON() );
2866 // Restore and reset the default state.
2867 controller.setState( controller.options.state );
2875 renderReplaceImageToolbar: function() {
2877 lastState = frame.lastState(),
2878 previous = lastState && lastState.id;
2880 this.toolbar.set( new media.view.Toolbar({
2888 frame.setState( previous );
2901 var controller = this.controller,
2902 state = controller.state(),
2903 selection = state.get( 'selection' ),
2904 attachment = selection.single();
2908 controller.image.changeAttachment( attachment, state.display( attachment ) );
2910 // not sure if we want to use wp.media.string.image which will create a shortcode or
2911 // perhaps wp.html.string to at least to build the <img />
2912 state.trigger( 'replace', controller.image.toJSON() );
2914 // Restore and reset the default state.
2915 controller.setState( controller.options.state );
2926 * wp.media.view.Modal
2929 * @augments wp.media.View
2930 * @augments wp.Backbone.View
2931 * @augments Backbone.View
2933 media.view.Modal = media.View.extend({
2935 template: media.template('media-modal'),
2942 'click .media-modal-backdrop, .media-modal-close': 'escapeHandler',
2943 'keydown': 'keydown'
2946 initialize: function() {
2947 _.defaults( this.options, {
2948 container: document.body,
2957 prepare: function() {
2959 title: this.options.title
2964 * @returns {wp.media.view.Modal} Returns itself to allow chaining
2966 attach: function() {
2967 if ( this.views.attached ) {
2971 if ( ! this.views.rendered ) {
2975 this.$el.appendTo( this.options.container );
2977 // Manually mark the view as attached and trigger ready.
2978 this.views.attached = true;
2981 return this.propagate('attach');
2985 * @returns {wp.media.view.Modal} Returns itself to allow chaining
2987 detach: function() {
2988 if ( this.$el.is(':visible') ) {
2993 this.views.attached = false;
2994 return this.propagate('detach');
2998 * @returns {wp.media.view.Modal} Returns itself to allow chaining
3002 options = this.options;
3004 if ( $el.is(':visible') ) {
3008 if ( ! this.views.attached ) {
3012 // If the `freeze` option is set, record the window's scroll position.
3013 if ( options.freeze ) {
3015 scrollTop: $( window ).scrollTop()
3020 return this.propagate('open');
3024 * @param {Object} options
3025 * @returns {wp.media.view.Modal} Returns itself to allow chaining
3027 close: function( options ) {
3028 var freeze = this._freeze;
3030 if ( ! this.views.attached || ! this.$el.is(':visible') ) {
3035 this.propagate('close');
3037 // If the `freeze` option is set, restore the container's scroll position.
3039 $( window ).scrollTop( freeze.scrollTop );
3042 if ( options && options.escape ) {
3043 this.propagate('escape');
3049 * @returns {wp.media.view.Modal} Returns itself to allow chaining
3051 escape: function() {
3052 return this.close({ escape: true });
3055 * @param {Object} event
3057 escapeHandler: function( event ) {
3058 event.preventDefault();
3063 * @param {Array|Object} content Views to register to '.media-modal-content'
3064 * @returns {wp.media.view.Modal} Returns itself to allow chaining
3066 content: function( content ) {
3067 this.views.set( '.media-modal-content', content );
3072 * Triggers a modal event and if the `propagate` option is set,
3073 * forwards events to the modal's controller.
3075 * @param {string} id
3076 * @returns {wp.media.view.Modal} Returns itself to allow chaining
3078 propagate: function( id ) {
3081 if ( this.options.propagate ) {
3082 this.controller.trigger( id );
3088 * @param {Object} event
3090 keydown: function( event ) {
3091 // Close the modal when escape is pressed.
3092 if ( 27 === event.which && this.$el.is(':visible') ) {
3094 event.stopImmediatePropagation();
3100 * wp.media.view.FocusManager
3103 * @augments wp.media.View
3104 * @augments wp.Backbone.View
3105 * @augments Backbone.View
3107 media.view.FocusManager = media.View.extend({
3109 keydown: 'recordTab',
3110 focusin: 'updateIndex'
3114 if ( _.isUndefined( this.index ) ) {
3118 // Update our collection of `$tabbables`.
3119 this.$tabbables = this.$(':tabbable');
3121 // If tab is saved, focus it.
3122 this.$tabbables.eq( this.index ).focus();
3125 * @param {Object} event
3127 recordTab: function( event ) {
3128 // Look for the tab key.
3129 if ( 9 !== event.keyCode ) {
3133 // First try to update the index.
3134 if ( _.isUndefined( this.index ) ) {
3135 this.updateIndex( event );
3138 // If we still don't have an index, bail.
3139 if ( _.isUndefined( this.index ) ) {
3143 var index = this.index + ( event.shiftKey ? -1 : 1 );
3145 if ( index >= 0 && index < this.$tabbables.length ) {
3152 * @param {Object} event
3154 updateIndex: function( event ) {
3155 this.$tabbables = this.$(':tabbable');
3157 var index = this.$tabbables.index( event.target );
3159 if ( -1 === index ) {
3168 * wp.media.view.UploaderWindow
3171 * @augments wp.media.View
3172 * @augments wp.Backbone.View
3173 * @augments Backbone.View
3175 media.view.UploaderWindow = media.View.extend({
3177 className: 'uploader-window',
3178 template: media.template('uploader-window'),
3180 initialize: function() {
3183 this.$browser = $('<a href="#" class="browser" />').hide().appendTo('body');
3185 uploader = this.options.uploader = _.defaults( this.options.uploader || {}, {
3187 browser: this.$browser,
3191 // Ensure the dropzone is a jQuery collection.
3192 if ( uploader.dropzone && ! (uploader.dropzone instanceof $) ) {
3193 uploader.dropzone = $( uploader.dropzone );
3196 this.controller.on( 'activate', this.refresh, this );
3198 this.controller.on( 'detach', function() {
3199 this.$browser.remove();
3203 refresh: function() {
3204 if ( this.uploader ) {
3205 this.uploader.refresh();
3210 var postId = media.view.settings.post.id,
3213 // If the uploader already exists, bail.
3214 if ( this.uploader ) {
3219 this.options.uploader.params.post_id = postId;
3221 this.uploader = new wp.Uploader( this.options.uploader );
3223 dropzone = this.uploader.dropzone;
3224 dropzone.on( 'dropzone:enter', _.bind( this.show, this ) );
3225 dropzone.on( 'dropzone:leave', _.bind( this.hide, this ) );
3227 $( this.uploader ).on( 'uploader:ready', _.bind( this._ready, this ) );
3230 _ready: function() {
3231 this.controller.trigger( 'uploader:ready' );
3235 var $el = this.$el.show();
3237 // Ensure that the animation is triggered by waiting until
3238 // the transparent element is painted into the DOM.
3239 _.defer( function() {
3240 $el.css({ opacity: 1 });
3245 var $el = this.$el.css({ opacity: 0 });
3247 media.transition( $el ).done( function() {
3248 // Transition end events are subject to race conditions.
3249 // Make sure that the value is set as intended.
3250 if ( '0' === $el.css('opacity') ) {
3258 * wp.media.view.EditorUploader
3261 * @augments wp.media.View
3262 * @augments wp.Backbone.View
3263 * @augments Backbone.View
3265 media.view.EditorUploader = media.View.extend({
3267 className: 'uploader-editor',
3268 template: media.template( 'uploader-editor' ),
3271 overContainer: false,
3272 overDropzone: false,
3274 initialize: function() {
3277 this.initialized = false;
3279 // Bail if not enabled or UA does not support drag'n'drop or File API.
3280 if ( ! window.tinyMCEPreInit || ! window.tinyMCEPreInit.dragDropUpload || ! this.browserSupport() ) {
3284 this.$document = $(document);
3285 this.dropzones = [];
3288 this.$document.on( 'drop', '.uploader-editor', _.bind( this.drop, this ) );
3289 this.$document.on( 'dragover', '.uploader-editor', _.bind( this.dropzoneDragover, this ) );
3290 this.$document.on( 'dragleave', '.uploader-editor', _.bind( this.dropzoneDragleave, this ) );
3291 this.$document.on( 'click', '.uploader-editor', _.bind( this.click, this ) );
3293 this.$document.on( 'dragover', _.bind( this.containerDragover, this ) );
3294 this.$document.on( 'dragleave', _.bind( this.containerDragleave, this ) );
3296 this.$document.on( 'dragstart dragend drop', function( event ) {
3297 self.localDrag = event.type === 'dragstart';
3300 this.initialized = true;
3304 browserSupport: function() {
3305 var supports = false, div = document.createElement('div');
3307 supports = ( 'draggable' in div ) || ( 'ondragstart' in div && 'ondrop' in div );
3308 supports = supports && !! ( window.File && window.FileList && window.FileReader );
3312 refresh: function( e ) {
3314 for ( dropzone_id in this.dropzones ) {
3315 // Hide the dropzones only if dragging has left the screen.
3316 this.dropzones[ dropzone_id ].toggle( this.overContainer || this.overDropzone );
3319 if ( ! _.isUndefined( e ) ) {
3320 $( e.target ).closest( '.uploader-editor' ).toggleClass( 'droppable', this.overDropzone );
3326 render: function() {
3327 if ( ! this.initialized ) {
3331 media.View.prototype.render.apply( this, arguments );
3332 $( '.wp-editor-wrap, #wp-fullscreen-body' ).each( _.bind( this.attach, this ) );
3336 attach: function( index, editor ) {
3337 // Attach a dropzone to an editor.
3338 var dropzone = this.$el.clone();
3339 this.dropzones.push( dropzone );
3340 $( editor ).append( dropzone );
3344 drop: function( event ) {
3347 this.containerDragleave( event );
3348 this.dropzoneDragleave( event );
3350 this.files = event.originalEvent.dataTransfer.files;
3351 if ( this.files.length < 1 ) {
3355 // Set the active editor to the drop target.
3356 $wrap = $( event.target ).parents( '.wp-editor-wrap' );
3357 if ( $wrap.length > 0 && $wrap[0].id ) {
3358 window.wpActiveEditor = $wrap[0].id.slice( 3, -5 );
3361 if ( ! this.workflow ) {
3362 this.workflow = wp.media.editor.open( 'content', {
3365 title: wp.media.view.l10n.addMedia,
3368 this.workflow.on( 'uploader:ready', this.addFiles, this );
3370 this.workflow.state().reset();
3371 this.addFiles.apply( this );
3372 this.workflow.open();
3378 addFiles: function() {
3379 if ( this.files.length ) {
3380 this.workflow.uploader.uploader.uploader.addFile( _.toArray( this.files ) );
3386 containerDragover: function() {
3387 if ( this.localDrag ) {
3391 this.overContainer = true;
3395 containerDragleave: function() {
3396 this.overContainer = false;
3398 // Throttle dragleave because it's called when bouncing from some elements to others.
3399 _.delay( _.bind( this.refresh, this ), 50 );
3402 dropzoneDragover: function( e ) {
3403 if ( this.localDrag ) {
3407 this.overDropzone = true;
3412 dropzoneDragleave: function( e ) {
3413 this.overDropzone = false;
3414 _.delay( _.bind( this.refresh, this, e ), 50 );
3417 click: function( e ) {
3418 // In the rare case where the dropzone gets stuck, hide it on click.
3419 this.containerDragleave( e );
3420 this.dropzoneDragleave( e );
3421 this.localDrag = false;
3426 * wp.media.view.UploaderInline
3429 * @augments wp.media.View
3430 * @augments wp.Backbone.View
3431 * @augments Backbone.View
3433 media.view.UploaderInline = media.View.extend({
3435 className: 'uploader-inline',
3436 template: media.template('uploader-inline'),
3438 initialize: function() {
3439 _.defaults( this.options, {
3444 if ( ! this.options.$browser && this.controller.uploader ) {
3445 this.options.$browser = this.controller.uploader.$browser;
3448 if ( _.isUndefined( this.options.postId ) ) {
3449 this.options.postId = media.view.settings.post.id;
3452 if ( this.options.status ) {
3453 this.views.set( '.upload-inline-status', new media.view.UploaderStatus({
3454 controller: this.controller
3459 prepare: function() {
3460 var suggestedWidth = this.controller.state().get('suggestedWidth'),
3461 suggestedHeight = this.controller.state().get('suggestedHeight');
3463 if ( suggestedWidth && suggestedHeight ) {
3465 suggestedWidth: suggestedWidth,
3466 suggestedHeight: suggestedHeight
3471 * @returns {wp.media.view.UploaderInline} Returns itself to allow chaining
3473 dispose: function() {
3474 if ( this.disposing ) {
3476 * call 'dispose' directly on the parent class
3478 return media.View.prototype.dispose.apply( this, arguments );
3481 // Run remove on `dispose`, so we can be sure to refresh the
3482 // uploader with a view-less DOM. Track whether we're disposing
3483 // so we don't trigger an infinite loop.
3484 this.disposing = true;
3485 return this.remove();
3488 * @returns {wp.media.view.UploaderInline} Returns itself to allow chaining
3490 remove: function() {
3492 * call 'remove' directly on the parent class
3494 var result = media.View.prototype.remove.apply( this, arguments );
3496 _.defer( _.bind( this.refresh, this ) );
3500 refresh: function() {
3501 var uploader = this.controller.uploader;
3508 * @returns {wp.media.view.UploaderInline}
3511 var $browser = this.options.$browser,
3514 if ( this.controller.uploader ) {
3515 $placeholder = this.$('.browser');
3517 // Check if we've already replaced the placeholder.
3518 if ( $placeholder[0] === $browser[0] ) {
3522 $browser.detach().text( $placeholder.text() );
3523 $browser[0].className = $placeholder[0].className;
3524 $placeholder.replaceWith( $browser.show() );
3533 * wp.media.view.UploaderStatus
3536 * @augments wp.media.View
3537 * @augments wp.Backbone.View
3538 * @augments Backbone.View
3540 media.view.UploaderStatus = media.View.extend({
3541 className: 'media-uploader-status',
3542 template: media.template('uploader-status'),
3545 'click .upload-dismiss-errors': 'dismiss'
3548 initialize: function() {
3549 this.queue = wp.Uploader.queue;
3550 this.queue.on( 'add remove reset', this.visibility, this );
3551 this.queue.on( 'add remove reset change:percent', this.progress, this );
3552 this.queue.on( 'add remove reset change:uploading', this.info, this );
3554 this.errors = wp.Uploader.errors;
3555 this.errors.reset();
3556 this.errors.on( 'add remove reset', this.visibility, this );
3557 this.errors.on( 'add', this.error, this );
3560 * @global wp.Uploader
3561 * @returns {wp.media.view.UploaderStatus}
3563 dispose: function() {
3564 wp.Uploader.queue.off( null, null, this );
3566 * call 'dispose' directly on the parent class
3568 media.View.prototype.dispose.apply( this, arguments );
3572 visibility: function() {
3573 this.$el.toggleClass( 'uploading', !! this.queue.length );
3574 this.$el.toggleClass( 'errors', !! this.errors.length );
3575 this.$el.toggle( !! this.queue.length || !! this.errors.length );
3580 '$bar': '.media-progress-bar div',
3581 '$index': '.upload-index',
3582 '$total': '.upload-total',
3583 '$filename': '.upload-filename'
3584 }, function( selector, key ) {
3585 this[ key ] = this.$( selector );
3593 progress: function() {
3594 var queue = this.queue,
3597 if ( ! $bar || ! queue.length ) {
3601 $bar.width( ( queue.reduce( function( memo, attachment ) {
3602 if ( ! attachment.get('uploading') ) {
3606 var percent = attachment.get('percent');
3607 return memo + ( _.isNumber( percent ) ? percent : 100 );
3608 }, 0 ) / queue.length ) + '%' );
3612 var queue = this.queue,
3615 if ( ! queue.length ) {
3619 active = this.queue.find( function( attachment, i ) {
3621 return attachment.get('uploading');
3624 this.$index.text( index + 1 );
3625 this.$total.text( queue.length );
3626 this.$filename.html( active ? this.filename( active.get('filename') ) : '' );
3629 * @param {string} filename
3632 filename: function( filename ) {
3633 return media.truncate( _.escape( filename ), 24 );
3636 * @param {Backbone.Model} error
3638 error: function( error ) {
3639 this.views.add( '.upload-errors', new media.view.UploaderStatusError({
3640 filename: this.filename( error.get('file').name ),
3641 message: error.get('message')
3646 * @global wp.Uploader
3648 * @param {Object} event
3650 dismiss: function( event ) {
3651 var errors = this.views.get('.upload-errors');
3653 event.preventDefault();
3656 _.invoke( errors, 'remove' );
3658 wp.Uploader.errors.reset();
3663 * wp.media.view.UploaderStatusError
3666 * @augments wp.media.View
3667 * @augments wp.Backbone.View
3668 * @augments Backbone.View
3670 media.view.UploaderStatusError = media.View.extend({
3671 className: 'upload-error',
3672 template: media.template('uploader-status-error')
3676 * wp.media.view.Toolbar
3679 * @augments wp.media.View
3680 * @augments wp.Backbone.View
3681 * @augments Backbone.View
3683 media.view.Toolbar = media.View.extend({
3685 className: 'media-toolbar',
3687 initialize: function() {
3688 var state = this.controller.state(),
3689 selection = this.selection = state.get('selection'),
3690 library = this.library = state.get('library');
3694 // The toolbar is composed of two `PriorityList` views.
3695 this.primary = new media.view.PriorityList();
3696 this.secondary = new media.view.PriorityList();
3697 this.primary.$el.addClass('media-toolbar-primary');
3698 this.secondary.$el.addClass('media-toolbar-secondary');
3700 this.views.set([ this.secondary, this.primary ]);
3702 if ( this.options.items ) {
3703 this.set( this.options.items, { silent: true });
3706 if ( ! this.options.silent ) {
3711 selection.on( 'add remove reset', this.refresh, this );
3715 library.on( 'add remove reset', this.refresh, this );
3719 * @returns {wp.media.view.Toolbar} Returns itsef to allow chaining
3721 dispose: function() {
3722 if ( this.selection ) {
3723 this.selection.off( null, null, this );
3726 if ( this.library ) {
3727 this.library.off( null, null, this );
3730 * call 'dispose' directly on the parent class
3732 return media.View.prototype.dispose.apply( this, arguments );
3740 * @param {string} id
3741 * @param {Backbone.View|Object} view
3742 * @param {Object} [options={}]
3743 * @returns {wp.media.view.Toolbar} Returns itself to allow chaining
3745 set: function( id, view, options ) {
3747 options = options || {};
3749 // Accept an object with an `id` : `view` mapping.
3750 if ( _.isObject( id ) ) {
3751 _.each( id, function( view, id ) {
3752 this.set( id, view, { silent: true });
3756 if ( ! ( view instanceof Backbone.View ) ) {
3757 view.classes = [ 'media-button-' + id ].concat( view.classes || [] );
3758 view = new media.view.Button( view ).render();
3761 view.controller = view.controller || this.controller;
3763 this._views[ id ] = view;
3765 list = view.options.priority < 0 ? 'secondary' : 'primary';
3766 this[ list ].set( id, view, options );
3769 if ( ! options.silent ) {
3776 * @param {string} id
3777 * @returns {wp.media.view.Button}
3779 get: function( id ) {
3780 return this._views[ id ];
3783 * @param {string} id
3784 * @param {Object} options
3785 * @returns {wp.media.view.Toolbar} Returns itself to allow chaining
3787 unset: function( id, options ) {
3788 delete this._views[ id ];
3789 this.primary.unset( id, options );
3790 this.secondary.unset( id, options );
3792 if ( ! options || ! options.silent ) {
3798 refresh: function() {
3799 var state = this.controller.state(),
3800 library = state.get('library'),
3801 selection = state.get('selection');
3803 _.each( this._views, function( button ) {
3804 if ( ! button.model || ! button.options || ! button.options.requires ) {
3808 var requires = button.options.requires,
3811 // Prevent insertion of attachments if any of them are still uploading
3812 disabled = _.some( selection.models, function( attachment ) {
3813 return attachment.get('uploading') === true;
3816 if ( requires.selection && selection && ! selection.length ) {
3818 } else if ( requires.library && library && ! library.length ) {
3821 button.model.set( 'disabled', disabled );
3827 * wp.media.view.Toolbar.Select
3830 * @augments wp.media.view.Toolbar
3831 * @augments wp.media.View
3832 * @augments wp.Backbone.View
3833 * @augments Backbone.View
3835 media.view.Toolbar.Select = media.view.Toolbar.extend({
3836 initialize: function() {
3837 var options = this.options;
3839 _.bindAll( this, 'clickSelect' );
3841 _.defaults( options, {
3848 // Does the button rely on the selection?
3854 options.items = _.defaults( options.items || {}, {
3859 click: this.clickSelect,
3860 requires: options.requires
3864 * call 'initialize' directly on the parent class
3866 media.view.Toolbar.prototype.initialize.apply( this, arguments );
3869 clickSelect: function() {
3870 var options = this.options,
3871 controller = this.controller;
3873 if ( options.close ) {
3877 if ( options.event ) {
3878 controller.state().trigger( options.event );
3881 if ( options.state ) {
3882 controller.setState( options.state );
3885 if ( options.reset ) {
3892 * wp.media.view.Toolbar.Embed
3895 * @augments wp.media.view.Toolbar.Select
3896 * @augments wp.media.view.Toolbar
3897 * @augments wp.media.View
3898 * @augments wp.Backbone.View
3899 * @augments Backbone.View
3901 media.view.Toolbar.Embed = media.view.Toolbar.Select.extend({
3902 initialize: function() {
3903 _.defaults( this.options, {
3904 text: l10n.insertIntoPost,
3908 * call 'initialize' directly on the parent class
3910 media.view.Toolbar.Select.prototype.initialize.apply( this, arguments );
3913 refresh: function() {
3914 var url = this.controller.state().props.get('url');
3915 this.get('select').model.set( 'disabled', ! url || url === 'http://' );
3917 * call 'refresh' directly on the parent class
3919 media.view.Toolbar.Select.prototype.refresh.apply( this, arguments );
3924 * wp.media.view.Button
3927 * @augments wp.media.View
3928 * @augments wp.Backbone.View
3929 * @augments Backbone.View
3931 media.view.Button = media.View.extend({
3933 className: 'media-button',
3934 attributes: { href: '#' },
3947 initialize: function() {
3949 * Create a model with the provided `defaults`.
3951 * @member {Backbone.Model}
3953 this.model = new Backbone.Model( this.defaults );
3955 // If any of the `options` have a key from `defaults`, apply its
3956 // value to the `model` and remove it from the `options object.
3957 _.each( this.defaults, function( def, key ) {
3958 var value = this.options[ key ];
3959 if ( _.isUndefined( value ) ) {
3963 this.model.set( key, value );
3964 delete this.options[ key ];
3967 this.model.on( 'change', this.render, this );
3970 * @returns {wp.media.view.Button} Returns itself to allow chaining
3972 render: function() {
3973 var classes = [ 'button', this.className ],
3974 model = this.model.toJSON();
3976 if ( model.style ) {
3977 classes.push( 'button-' + model.style );
3981 classes.push( 'button-' + model.size );
3984 classes = _.uniq( classes.concat( this.options.classes ) );
3985 this.el.className = classes.join(' ');
3987 this.$el.attr( 'disabled', model.disabled );
3988 this.$el.text( this.model.get('text') );
3993 * @param {Object} event
3995 click: function( event ) {
3996 if ( '#' === this.attributes.href ) {
3997 event.preventDefault();
4000 if ( this.options.click && ! this.model.get('disabled') ) {
4001 this.options.click.apply( this, arguments );
4007 * wp.media.view.ButtonGroup
4010 * @augments wp.media.View
4011 * @augments wp.Backbone.View
4012 * @augments Backbone.View
4014 media.view.ButtonGroup = media.View.extend({
4016 className: 'button-group button-large media-button-group',
4018 initialize: function() {
4020 * @member {wp.media.view.Button[]}
4022 this.buttons = _.map( this.options.buttons || [], function( button ) {
4023 if ( button instanceof Backbone.View ) {
4026 return new media.view.Button( button ).render();
4030 delete this.options.buttons;
4032 if ( this.options.classes ) {
4033 this.$el.addClass( this.options.classes );
4038 * @returns {wp.media.view.ButtonGroup}
4040 render: function() {
4041 this.$el.html( $( _.pluck( this.buttons, 'el' ) ).detach() );
4047 * wp.media.view.PriorityList
4050 * @augments wp.media.View
4051 * @augments wp.Backbone.View
4052 * @augments Backbone.View
4054 media.view.PriorityList = media.View.extend({
4057 initialize: function() {
4060 this.set( _.extend( {}, this._views, this.options.views ), { silent: true });
4061 delete this.options.views;
4063 if ( ! this.options.silent ) {
4068 * @param {string} id
4069 * @param {wp.media.View|Object} view
4070 * @param {Object} options
4071 * @returns {wp.media.view.PriorityList} Returns itself to allow chaining
4073 set: function( id, view, options ) {
4074 var priority, views, index;
4076 options = options || {};
4078 // Accept an object with an `id` : `view` mapping.
4079 if ( _.isObject( id ) ) {
4080 _.each( id, function( view, id ) {
4081 this.set( id, view );
4086 if ( ! (view instanceof Backbone.View) ) {
4087 view = this.toView( view, id, options );
4089 view.controller = view.controller || this.controller;
4093 priority = view.options.priority || 10;
4094 views = this.views.get() || [];
4096 _.find( views, function( existing, i ) {
4097 if ( existing.options.priority > priority ) {
4103 this._views[ id ] = view;
4104 this.views.add( view, {
4105 at: _.isNumber( index ) ? index : views.length || 0
4111 * @param {string} id
4112 * @returns {wp.media.View}
4114 get: function( id ) {
4115 return this._views[ id ];
4118 * @param {string} id
4119 * @returns {wp.media.view.PriorityList}
4121 unset: function( id ) {
4122 var view = this.get( id );
4128 delete this._views[ id ];
4132 * @param {Object} options
4133 * @returns {wp.media.View}
4135 toView: function( options ) {
4136 return new media.View( options );
4141 * wp.media.view.MenuItem
4144 * @augments wp.media.View
4145 * @augments wp.Backbone.View
4146 * @augments Backbone.View
4148 media.view.MenuItem = media.View.extend({
4150 className: 'media-menu-item',
4160 * @param {Object} event
4162 _click: function( event ) {
4163 var clickOverride = this.options.click;
4166 event.preventDefault();
4169 if ( clickOverride ) {
4170 clickOverride.call( this );
4177 var state = this.options.state;
4179 this.controller.setState( state );
4183 * @returns {wp.media.view.MenuItem} returns itself to allow chaining
4185 render: function() {
4186 var options = this.options;
4188 if ( options.text ) {
4189 this.$el.text( options.text );
4190 } else if ( options.html ) {
4191 this.$el.html( options.html );
4199 * wp.media.view.Menu
4202 * @augments wp.media.view.PriorityList
4203 * @augments wp.media.View
4204 * @augments wp.Backbone.View
4205 * @augments Backbone.View
4207 media.view.Menu = media.view.PriorityList.extend({
4209 className: 'media-menu',
4211 ItemView: media.view.MenuItem,
4214 * @param {Object} options
4215 * @param {string} id
4216 * @returns {wp.media.View}
4218 toView: function( options, id ) {
4219 options = options || {};
4220 options[ this.property ] = options[ this.property ] || id;
4221 return new this.ItemView( options ).render();
4226 * call 'ready' directly on the parent class
4228 media.view.PriorityList.prototype.ready.apply( this, arguments );
4234 * call 'set' directly on the parent class
4236 media.view.PriorityList.prototype.set.apply( this, arguments );
4242 * call 'unset' directly on the parent class
4244 media.view.PriorityList.prototype.unset.apply( this, arguments );
4248 visibility: function() {
4249 var region = this.region,
4250 view = this.controller[ region ].get(),
4251 views = this.views.get(),
4252 hide = ! views || views.length < 2;
4254 if ( this === view ) {
4255 this.controller.$el.toggleClass( 'hide-' + region, hide );
4259 * @param {string} id
4261 select: function( id ) {
4262 var view = this.get( id );
4269 view.$el.addClass('active');
4272 deselect: function() {
4273 this.$el.children().removeClass('active');
4276 hide: function( id ) {
4277 var view = this.get( id );
4283 view.$el.addClass('hidden');
4286 show: function( id ) {
4287 var view = this.get( id );
4293 view.$el.removeClass('hidden');
4298 * wp.media.view.RouterItem
4301 * @augments wp.media.view.MenuItem
4302 * @augments wp.media.View
4303 * @augments wp.Backbone.View
4304 * @augments Backbone.View
4306 media.view.RouterItem = media.view.MenuItem.extend({
4308 var contentMode = this.options.contentMode;
4309 if ( contentMode ) {
4310 this.controller.content.mode( contentMode );
4316 * wp.media.view.Router
4319 * @augments wp.media.view.Menu
4320 * @augments wp.media.view.PriorityList
4321 * @augments wp.media.View
4322 * @augments wp.Backbone.View
4323 * @augments Backbone.View
4325 media.view.Router = media.view.Menu.extend({
4327 className: 'media-router',
4328 property: 'contentMode',
4329 ItemView: media.view.RouterItem,
4332 initialize: function() {
4333 this.controller.on( 'content:render', this.update, this );
4335 * call 'initialize' directly on the parent class
4337 media.view.Menu.prototype.initialize.apply( this, arguments );
4340 update: function() {
4341 var mode = this.controller.content.mode();
4343 this.select( mode );
4349 * wp.media.view.Sidebar
4352 * @augments wp.media.view.PriorityList
4353 * @augments wp.media.View
4354 * @augments wp.Backbone.View
4355 * @augments Backbone.View
4357 media.view.Sidebar = media.view.PriorityList.extend({
4358 className: 'media-sidebar'
4362 * wp.media.view.Attachment
4365 * @augments wp.media.View
4366 * @augments wp.Backbone.View
4367 * @augments Backbone.View
4369 media.view.Attachment = media.View.extend({
4371 className: 'attachment',
4372 template: media.template('attachment'),
4375 'click .attachment-preview': 'toggleSelectionHandler',
4376 'change [data-setting]': 'updateSetting',
4377 'change [data-setting] input': 'updateSetting',
4378 'change [data-setting] select': 'updateSetting',
4379 'change [data-setting] textarea': 'updateSetting',
4380 'click .close': 'removeFromLibrary',
4381 'click .check': 'removeFromSelection',
4382 'click a': 'preventDefault'
4387 initialize: function() {
4388 var selection = this.options.selection;
4390 this.model.on( 'change:sizes change:uploading', this.render, this );
4391 this.model.on( 'change:title', this._syncTitle, this );
4392 this.model.on( 'change:caption', this._syncCaption, this );
4393 this.model.on( 'change:percent', this.progress, this );
4395 // Update the selection.
4396 this.model.on( 'add', this.select, this );
4397 this.model.on( 'remove', this.deselect, this );
4399 selection.on( 'reset', this.updateSelect, this );
4402 // Update the model's details view.
4403 this.model.on( 'selection:single selection:unsingle', this.details, this );
4404 this.details( this.model, this.controller.state().get('selection') );
4407 * @returns {wp.media.view.Attachment} Returns itself to allow chaining
4409 dispose: function() {
4410 var selection = this.options.selection;
4412 // Make sure all settings are saved before removing the view.
4416 selection.off( null, null, this );
4419 * call 'dispose' directly on the parent class
4421 media.View.prototype.dispose.apply( this, arguments );
4425 * @returns {wp.media.view.Attachment} Returns itself to allow chaining
4427 render: function() {
4428 var options = _.defaults( this.model.toJSON(), {
4429 orientation: 'landscape',
4445 options.buttons = this.buttons;
4446 options.describe = this.controller.state().get('describe');
4448 if ( 'image' === options.type ) {
4449 options.size = this.imageSize();
4453 if ( options.nonces ) {
4454 options.can.remove = !! options.nonces['delete'];
4455 options.can.save = !! options.nonces.update;
4458 if ( this.controller.state().get('allowLocalEdits') ) {
4459 options.allowLocalEdits = true;
4462 this.views.detach();
4463 this.$el.html( this.template( options ) );
4465 this.$el.toggleClass( 'uploading', options.uploading );
4466 if ( options.uploading ) {
4467 this.$bar = this.$('.media-progress-bar div');
4472 // Check if the model is selected.
4473 this.updateSelect();
4475 // Update the save status.
4478 this.views.render();
4483 progress: function() {
4484 if ( this.$bar && this.$bar.length ) {
4485 this.$bar.width( this.model.get('percent') + '%' );
4489 * @param {Object} event
4491 toggleSelectionHandler: function( event ) {
4494 if ( event.shiftKey ) {
4496 } else if ( event.ctrlKey || event.metaKey ) {
4500 this.toggleSelection({
4505 * @param {Object} options
4507 toggleSelection: function( options ) {
4508 var collection = this.collection,
4509 selection = this.options.selection,
4511 method = options && options.method,
4512 single, models, singleIndex, modelIndex;
4514 if ( ! selection ) {
4518 single = selection.single();
4519 method = _.isUndefined( method ) ? selection.multiple : method;
4521 // If the `method` is set to `between`, select all models that
4522 // exist between the current and the selected model.
4523 if ( 'between' === method && single && selection.multiple ) {
4524 // If the models are the same, short-circuit.
4525 if ( single === model ) {
4529 singleIndex = collection.indexOf( single );
4530 modelIndex = collection.indexOf( this.model );
4532 if ( singleIndex < modelIndex ) {
4533 models = collection.models.slice( singleIndex, modelIndex + 1 );
4535 models = collection.models.slice( modelIndex, singleIndex + 1 );
4538 selection.add( models );
4539 selection.single( model );
4542 // If the `method` is set to `toggle`, just flip the selection
4543 // status, regardless of whether the model is the single model.
4544 } else if ( 'toggle' === method ) {
4545 selection[ this.selected() ? 'remove' : 'add' ]( model );
4546 selection.single( model );
4550 if ( method !== 'add' ) {
4554 if ( this.selected() ) {
4555 // If the model is the single model, remove it.
4556 // If it is not the same as the single model,
4557 // it now becomes the single model.
4558 selection[ single === model ? 'remove' : 'single' ]( model );
4560 // If the model is not selected, run the `method` on the
4561 // selection. By default, we `reset` the selection, but the
4562 // `method` can be set to `add` the model to the selection.
4563 selection[ method ]( model );
4564 selection.single( model );
4568 updateSelect: function() {
4569 this[ this.selected() ? 'select' : 'deselect' ]();
4572 * @returns {unresolved|Boolean}
4574 selected: function() {
4575 var selection = this.options.selection;
4577 return !! selection.get( this.model.cid );
4581 * @param {Backbone.Model} model
4582 * @param {Backbone.Collection} collection
4584 select: function( model, collection ) {
4585 var selection = this.options.selection;
4587 // Check if a selection exists and if it's the collection provided.
4588 // If they're not the same collection, bail; we're in another
4589 // selection's event loop.
4590 if ( ! selection || ( collection && collection !== selection ) ) {
4594 this.$el.addClass('selected');
4597 * @param {Backbone.Model} model
4598 * @param {Backbone.Collection} collection
4600 deselect: function( model, collection ) {
4601 var selection = this.options.selection;
4603 // Check if a selection exists and if it's the collection provided.
4604 // If they're not the same collection, bail; we're in another
4605 // selection's event loop.
4606 if ( ! selection || ( collection && collection !== selection ) ) {
4609 this.$el.removeClass('selected');
4612 * @param {Backbone.Model} model
4613 * @param {Backbone.Collection} collection
4615 details: function( model, collection ) {
4616 var selection = this.options.selection,
4619 if ( selection !== collection ) {
4623 details = selection.single();
4624 this.$el.toggleClass( 'details', details === this.model );
4627 * @param {Object} event
4629 preventDefault: function( event ) {
4630 event.preventDefault();
4633 * @param {string} size
4636 imageSize: function( size ) {
4637 var sizes = this.model.get('sizes');
4639 size = size || 'medium';
4641 // Use the provided image size if possible.
4642 if ( sizes && sizes[ size ] ) {
4643 return _.clone( sizes[ size ] );
4646 url: this.model.get('url'),
4647 width: this.model.get('width'),
4648 height: this.model.get('height'),
4649 orientation: this.model.get('orientation')
4654 * @param {Object} event
4656 updateSetting: function( event ) {
4657 var $setting = $( event.target ).closest('[data-setting]'),
4660 if ( ! $setting.length ) {
4664 setting = $setting.data('setting');
4665 value = event.target.value;
4667 if ( this.model.get( setting ) !== value ) {
4668 this.save( setting, value );
4673 * Pass all the arguments to the model's save method.
4675 * Records the aggregate status of all save requests and updates the
4676 * view's classes accordingly.
4680 save = this._save = this._save || { status: 'ready' },
4681 request = this.model.save.apply( this.model, arguments ),
4682 requests = save.requests ? $.when( request, save.requests ) : request;
4684 // If we're waiting to remove 'Saved.', stop.
4685 if ( save.savedTimer ) {
4686 clearTimeout( save.savedTimer );
4689 this.updateSave('waiting');
4690 save.requests = requests;
4691 requests.always( function() {
4692 // If we've performed another request since this one, bail.
4693 if ( save.requests !== requests ) {
4697 view.updateSave( requests.state() === 'resolved' ? 'complete' : 'error' );
4698 save.savedTimer = setTimeout( function() {
4699 view.updateSave('ready');
4700 delete save.savedTimer;
4705 * @param {string} status
4706 * @returns {wp.media.view.Attachment} Returns itself to allow chaining
4708 updateSave: function( status ) {
4709 var save = this._save = this._save || { status: 'ready' };
4711 if ( status && status !== save.status ) {
4712 this.$el.removeClass( 'save-' + save.status );
4713 save.status = status;
4716 this.$el.addClass( 'save-' + save.status );
4720 updateAll: function() {
4721 var $settings = this.$('[data-setting]'),
4725 changed = _.chain( $settings ).map( function( el ) {
4726 var $input = $('input, textarea, select, [value]', el ),
4729 if ( ! $input.length ) {
4733 setting = $(el).data('setting');
4734 value = $input.val();
4736 // Record the value if it changed.
4737 if ( model.get( setting ) !== value ) {
4738 return [ setting, value ];
4740 }).compact().object().value();
4742 if ( ! _.isEmpty( changed ) ) {
4743 model.save( changed );
4747 * @param {Object} event
4749 removeFromLibrary: function( event ) {
4750 // Stop propagation so the model isn't selected.
4751 event.stopPropagation();
4753 this.collection.remove( this.model );
4756 * @param {Object} event
4758 removeFromSelection: function( event ) {
4759 var selection = this.options.selection;
4760 if ( ! selection ) {
4764 // Stop propagation so the model isn't selected.
4765 event.stopPropagation();
4767 selection.remove( this.model );
4771 // Ensure settings remain in sync between attachment views.
4773 caption: '_syncCaption',
4775 }, function( method, setting ) {
4777 * @param {Backbone.Model} model
4778 * @param {string} value
4779 * @returns {wp.media.view.Attachment} Returns itself to allow chaining
4781 media.view.Attachment.prototype[ method ] = function( model, value ) {
4782 var $setting = this.$('[data-setting="' + setting + '"]');
4784 if ( ! $setting.length ) {
4788 // If the updated value is in sync with the value in the DOM, there
4789 // is no need to re-render. If we're currently editing the value,
4790 // it will automatically be in sync, suppressing the re-render for
4791 // the view we're editing, while updating any others.
4792 if ( value === $setting.find('input, textarea, select, [value]').val() ) {
4796 return this.render();
4801 * wp.media.view.Attachment.Library
4804 * @augments wp.media.view.Attachment
4805 * @augments wp.media.View
4806 * @augments wp.Backbone.View
4807 * @augments Backbone.View
4809 media.view.Attachment.Library = media.view.Attachment.extend({
4816 * wp.media.view.Attachment.EditLibrary
4819 * @augments wp.media.view.Attachment
4820 * @augments wp.media.View
4821 * @augments wp.Backbone.View
4822 * @augments Backbone.View
4824 media.view.Attachment.EditLibrary = media.view.Attachment.extend({
4831 * wp.media.view.Attachments
4834 * @augments wp.media.View
4835 * @augments wp.Backbone.View
4836 * @augments Backbone.View
4838 media.view.Attachments = media.View.extend({
4840 className: 'attachments',
4842 cssTemplate: media.template('attachments-css'),
4848 initialize: function() {
4849 this.el.id = _.uniqueId('__attachments-view-');
4851 _.defaults( this.options, {
4852 refreshSensitivity: 200,
4853 refreshThreshold: 3,
4854 AttachmentView: media.view.Attachment,
4859 this._viewsByCid = {};
4861 this.collection.on( 'add', function( attachment ) {
4862 this.views.add( this.createAttachmentView( attachment ), {
4863 at: this.collection.indexOf( attachment )
4867 this.collection.on( 'remove', function( attachment ) {
4868 var view = this._viewsByCid[ attachment.cid ];
4869 delete this._viewsByCid[ attachment.cid ];
4876 this.collection.on( 'reset', this.render, this );
4878 // Throttle the scroll handler.
4879 this.scroll = _.chain( this.scroll ).bind( this ).throttle( this.options.refreshSensitivity ).value();
4881 this.initSortable();
4883 _.bindAll( this, 'css' );
4884 this.model.on( 'change:edge change:gutter', this.css, this );
4885 this._resizeCss = _.debounce( _.bind( this.css, this ), this.refreshSensitivity );
4886 if ( this.options.resize ) {
4887 $(window).on( 'resize.attachments', this._resizeCss );
4892 dispose: function() {
4893 this.collection.props.off( null, null, this );
4894 $(window).off( 'resize.attachments', this._resizeCss );
4896 * call 'dispose' directly on the parent class
4898 media.View.prototype.dispose.apply( this, arguments );
4902 var $css = $( '#' + this.el.id + '-css' );
4904 if ( $css.length ) {
4908 media.view.Attachments.$head().append( this.cssTemplate({
4911 gutter: this.model.get('gutter')
4918 var edge = this.model.get('edge'),
4919 gutter, width, columns;
4921 if ( ! this.$el.is(':visible') ) {
4925 gutter = this.model.get('gutter') * 2;
4926 width = this.$el.width() - gutter;
4927 columns = Math.ceil( width / ( edge + gutter ) );
4928 edge = Math.floor( ( width - ( columns * gutter ) ) / columns );
4932 initSortable: function() {
4933 var collection = this.collection;
4935 if ( ! this.options.sortable || ! $.fn.sortable ) {
4939 this.$el.sortable( _.extend({
4940 // If the `collection` has a `comparator`, disable sorting.
4941 disabled: !! collection.comparator,
4943 // Prevent attachments from being dragged outside the bounding
4945 containment: this.$el,
4947 // Change the position of the attachment as soon as the
4948 // mouse pointer overlaps a thumbnail.
4949 tolerance: 'pointer',
4951 // Record the initial `index` of the dragged model.
4952 start: function( event, ui ) {
4953 ui.item.data('sortableIndexStart', ui.item.index());
4956 // Update the model's index in the collection.
4957 // Do so silently, as the view is already accurate.
4958 update: function( event, ui ) {
4959 var model = collection.at( ui.item.data('sortableIndexStart') ),
4960 comparator = collection.comparator;
4962 // Temporarily disable the comparator to prevent `add`
4964 delete collection.comparator;
4966 // Silently shift the model to its new index.
4967 collection.remove( model, {
4970 collection.add( model, {
4975 // Restore the comparator.
4976 collection.comparator = comparator;
4978 // Fire the `reset` event to ensure other collections sync.
4979 collection.trigger( 'reset', collection );
4981 // If the collection is sorted by menu order,
4982 // update the menu order.
4983 collection.saveMenuOrder();
4985 }, this.options.sortable ) );
4987 // If the `orderby` property is changed on the `collection`,
4988 // check to see if we have a `comparator`. If so, disable sorting.
4989 collection.props.on( 'change:orderby', function() {
4990 this.$el.sortable( 'option', 'disabled', !! collection.comparator );
4993 this.collection.props.on( 'change:orderby', this.refreshSortable, this );
4994 this.refreshSortable();
4997 refreshSortable: function() {
4998 if ( ! this.options.sortable || ! $.fn.sortable ) {
5002 // If the `collection` has a `comparator`, disable sorting.
5003 var collection = this.collection,
5004 orderby = collection.props.get('orderby'),
5005 enabled = 'menuOrder' === orderby || ! collection.comparator;
5007 this.$el.sortable( 'option', 'disabled', ! enabled );
5011 * @param {wp.media.model.Attachment} attachment
5012 * @returns {wp.media.View}
5014 createAttachmentView: function( attachment ) {
5015 var view = new this.options.AttachmentView({
5016 controller: this.controller,
5018 collection: this.collection,
5019 selection: this.options.selection
5022 return this._viewsByCid[ attachment.cid ] = view;
5025 prepare: function() {
5026 // Create all of the Attachment views, and replace
5027 // the list in a single DOM operation.
5028 if ( this.collection.length ) {
5029 this.views.set( this.collection.map( this.createAttachmentView, this ) );
5031 // If there are no elements, clear the views and load some.
5034 this.collection.more().done( this.scroll );
5039 // Trigger the scroll event to check if we're within the
5040 // threshold to query for additional attachments.
5044 scroll: function() {
5048 if ( ! this.$el.is(':visible') || ! this.collection.hasMore() ) {
5052 toolbar = this.views.parent.toolbar;
5054 // Show the spinner only if we are close to the bottom.
5055 if ( this.el.scrollHeight - ( this.el.scrollTop + this.el.clientHeight ) < this.el.clientHeight / 3 ) {
5056 toolbar.get('spinner').show();
5059 if ( this.el.scrollHeight < this.el.scrollTop + ( this.el.clientHeight * this.options.refreshThreshold ) ) {
5060 this.collection.more().done(function() {
5062 toolbar.get('spinner').hide();
5067 $head: (function() {
5070 return $head = $head || $('head');
5076 * wp.media.view.Search
5079 * @augments wp.media.View
5080 * @augments wp.Backbone.View
5081 * @augments Backbone.View
5083 media.view.Search = media.View.extend({
5085 className: 'search',
5089 placeholder: l10n.search
5100 * @returns {wp.media.view.Search} Returns itself to allow chaining
5102 render: function() {
5103 this.el.value = this.model.escape('search');
5107 search: function( event ) {
5108 if ( event.target.value ) {
5109 this.model.set( 'search', event.target.value );
5111 this.model.unset('search');
5117 * wp.media.view.AttachmentFilters
5120 * @augments wp.media.View
5121 * @augments wp.Backbone.View
5122 * @augments Backbone.View
5124 media.view.AttachmentFilters = media.View.extend({
5126 className: 'attachment-filters',
5134 initialize: function() {
5135 this.createFilters();
5136 _.extend( this.filters, this.options.filters );
5138 // Build `<option>` elements.
5139 this.$el.html( _.chain( this.filters ).map( function( filter, value ) {
5141 el: $( '<option></option>' ).val( value ).html( filter.text )[0],
5142 priority: filter.priority || 50
5144 }, this ).sortBy('priority').pluck('el').value() );
5146 this.model.on( 'change', this.select, this );
5150 createFilters: function() {
5154 change: function() {
5155 var filter = this.filters[ this.el.value ];
5158 this.model.set( filter.props );
5162 select: function() {
5163 var model = this.model,
5165 props = model.toJSON();
5167 _.find( this.filters, function( filter, id ) {
5168 var equal = _.all( filter.props, function( prop, key ) {
5169 return prop === ( _.isUndefined( props[ key ] ) ? null : props[ key ] );
5177 this.$el.val( value );
5182 * wp.media.view.AttachmentFilters.Uploaded
5185 * @augments wp.media.view.AttachmentFilters
5186 * @augments wp.media.View
5187 * @augments wp.Backbone.View
5188 * @augments Backbone.View
5190 media.view.AttachmentFilters.Uploaded = media.view.AttachmentFilters.extend({
5191 createFilters: function() {
5192 var type = this.model.get('type'),
5193 types = media.view.settings.mimeTypes,
5196 if ( types && type ) {
5197 text = types[ type ];
5202 text: text || l10n.allMediaItems,
5212 text: l10n.uploadedToThisPost,
5214 uploadedTo: media.view.settings.post.id,
5215 orderby: 'menuOrder',
5225 * wp.media.view.AttachmentFilters.All
5228 * @augments wp.media.view.AttachmentFilters
5229 * @augments wp.media.View
5230 * @augments wp.Backbone.View
5231 * @augments Backbone.View
5233 media.view.AttachmentFilters.All = media.view.AttachmentFilters.extend({
5234 createFilters: function() {
5237 _.each( media.view.settings.mimeTypes || {}, function( text, key ) {
5250 text: l10n.allMediaItems,
5260 filters.uploaded = {
5261 text: l10n.uploadedToThisPost,
5264 uploadedTo: media.view.settings.post.id,
5265 orderby: 'menuOrder',
5271 this.filters = filters;
5277 * wp.media.view.AttachmentsBrowser
5280 * @augments wp.media.View
5281 * @augments wp.Backbone.View
5282 * @augments Backbone.View
5284 media.view.AttachmentsBrowser = media.View.extend({
5286 className: 'attachments-browser',
5288 initialize: function() {
5289 _.defaults( this.options, {
5294 AttachmentView: media.view.Attachment.Library
5297 this.createToolbar();
5298 this.updateContent();
5299 this.createSidebar();
5301 this.collection.on( 'add remove reset', this.updateContent, this );
5304 * @returns {wp.media.view.AttachmentsBrowser} Returns itself to allow chaining
5306 dispose: function() {
5307 this.options.selection.off( null, null, this );
5308 media.View.prototype.dispose.apply( this, arguments );
5312 createToolbar: function() {
5313 var filters, FiltersConstructor;
5316 * @member {wp.media.view.Toolbar}
5318 this.toolbar = new media.view.Toolbar({
5319 controller: this.controller
5322 this.views.add( this.toolbar );
5324 filters = this.options.filters;
5325 if ( 'uploaded' === filters ) {
5326 FiltersConstructor = media.view.AttachmentFilters.Uploaded;
5327 } else if ( 'all' === filters ) {
5328 FiltersConstructor = media.view.AttachmentFilters.All;
5331 if ( FiltersConstructor ) {
5332 this.toolbar.set( 'filters', new FiltersConstructor({
5333 controller: this.controller,
5334 model: this.collection.props,
5339 this.toolbar.set( 'spinner', new media.view.Spinner({
5343 if ( this.options.search ) {
5344 this.toolbar.set( 'search', new media.view.Search({
5345 controller: this.controller,
5346 model: this.collection.props,
5351 if ( this.options.dragInfo ) {
5352 this.toolbar.set( 'dragInfo', new media.View({
5353 el: $( '<div class="instructions">' + l10n.dragInfo + '</div>' )[0],
5358 if ( this.options.suggestedWidth && this.options.suggestedHeight ) {
5359 this.toolbar.set( 'suggestedDimensions', new media.View({
5360 el: $( '<div class="instructions">' + l10n.suggestedDimensions + ' ' + this.options.suggestedWidth + ' × ' + this.options.suggestedHeight + '</div>' )[0],
5366 updateContent: function() {
5369 if( ! this.attachments ) {
5370 this.createAttachments();
5373 if ( ! this.collection.length ) {
5374 this.toolbar.get( 'spinner' ).show();
5375 this.collection.more().done(function() {
5376 if ( ! view.collection.length ) {
5377 view.createUploader();
5379 view.toolbar.get( 'spinner' ).hide();
5382 view.toolbar.get( 'spinner' ).hide();
5386 removeContent: function() {
5387 _.each(['attachments','uploader'], function( key ) {
5388 if ( this[ key ] ) {
5389 this[ key ].remove();
5395 createUploader: function() {
5396 this.removeContent();
5398 this.uploader = new media.view.UploaderInline({
5399 controller: this.controller,
5401 message: l10n.noItemsFound
5404 this.views.add( this.uploader );
5407 createAttachments: function() {
5408 this.removeContent();
5410 this.attachments = new media.view.Attachments({
5411 controller: this.controller,
5412 collection: this.collection,
5413 selection: this.options.selection,
5415 sortable: this.options.sortable,
5417 // The single `Attachment` view to be used in the `Attachments` view.
5418 AttachmentView: this.options.AttachmentView
5421 this.views.add( this.attachments );
5424 createSidebar: function() {
5425 var options = this.options,
5426 selection = options.selection,
5427 sidebar = this.sidebar = new media.view.Sidebar({
5428 controller: this.controller
5431 this.views.add( sidebar );
5433 if ( this.controller.uploader ) {
5434 sidebar.set( 'uploads', new media.view.UploaderStatus({
5435 controller: this.controller,
5440 selection.on( 'selection:single', this.createSingle, this );
5441 selection.on( 'selection:unsingle', this.disposeSingle, this );
5443 if ( selection.single() ) {
5444 this.createSingle();
5448 createSingle: function() {
5449 var sidebar = this.sidebar,
5450 single = this.options.selection.single();
5452 sidebar.set( 'details', new media.view.Attachment.Details({
5453 controller: this.controller,
5458 sidebar.set( 'compat', new media.view.AttachmentCompat({
5459 controller: this.controller,
5464 if ( this.options.display ) {
5465 sidebar.set( 'display', new media.view.Settings.AttachmentDisplay({
5466 controller: this.controller,
5467 model: this.model.display( single ),
5470 userSettings: this.model.get('displayUserSettings')
5475 disposeSingle: function() {
5476 var sidebar = this.sidebar;
5477 sidebar.unset('details');
5478 sidebar.unset('compat');
5479 sidebar.unset('display');
5484 * wp.media.view.Selection
5487 * @augments wp.media.View
5488 * @augments wp.Backbone.View
5489 * @augments Backbone.View
5491 media.view.Selection = media.View.extend({
5493 className: 'media-selection',
5494 template: media.template('media-selection'),
5497 'click .edit-selection': 'edit',
5498 'click .clear-selection': 'clear'
5501 initialize: function() {
5502 _.defaults( this.options, {
5508 * @member {wp.media.view.Attachments.Selection}
5510 this.attachments = new media.view.Attachments.Selection({
5511 controller: this.controller,
5512 collection: this.collection,
5513 selection: this.collection,
5514 model: new Backbone.Model({
5520 this.views.set( '.selection-view', this.attachments );
5521 this.collection.on( 'add remove reset', this.refresh, this );
5522 this.controller.on( 'content:activate', this.refresh, this );
5529 refresh: function() {
5530 // If the selection hasn't been rendered, bail.
5531 if ( ! this.$el.children().length ) {
5535 var collection = this.collection,
5536 editing = 'edit-selection' === this.controller.content.mode();
5538 // If nothing is selected, display nothing.
5539 this.$el.toggleClass( 'empty', ! collection.length );
5540 this.$el.toggleClass( 'one', 1 === collection.length );
5541 this.$el.toggleClass( 'editing', editing );
5543 this.$('.count').text( l10n.selected.replace('%d', collection.length) );
5546 edit: function( event ) {
5547 event.preventDefault();
5548 if ( this.options.editable ) {
5549 this.options.editable.call( this, this.collection );
5553 clear: function( event ) {
5554 event.preventDefault();
5555 this.collection.reset();
5561 * wp.media.view.Attachment.Selection
5564 * @augments wp.media.view.Attachment
5565 * @augments wp.media.View
5566 * @augments wp.Backbone.View
5567 * @augments Backbone.View
5569 media.view.Attachment.Selection = media.view.Attachment.extend({
5570 className: 'attachment selection',
5572 // On click, just select the model, instead of removing the model from
5574 toggleSelection: function() {
5575 this.options.selection.single( this.model );
5580 * wp.media.view.Attachments.Selection
5583 * @augments wp.media.view.Attachments
5584 * @augments wp.media.View
5585 * @augments wp.Backbone.View
5586 * @augments Backbone.View
5588 media.view.Attachments.Selection = media.view.Attachments.extend({
5590 initialize: function() {
5591 _.defaults( this.options, {
5595 // The single `Attachment` view to be used in the `Attachments` view.
5596 AttachmentView: media.view.Attachment.Selection
5599 * call 'initialize' directly on the parent class
5601 return media.view.Attachments.prototype.initialize.apply( this, arguments );
5606 * wp.media.view.Attachments.EditSelection
5609 * @augments wp.media.view.Attachment.Selection
5610 * @augments wp.media.view.Attachment
5611 * @augments wp.media.View
5612 * @augments wp.Backbone.View
5613 * @augments Backbone.View
5615 media.view.Attachment.EditSelection = media.view.Attachment.Selection.extend({
5623 * wp.media.view.Settings
5626 * @augments wp.media.View
5627 * @augments wp.Backbone.View
5628 * @augments Backbone.View
5630 media.view.Settings = media.View.extend({
5632 'click button': 'updateHandler',
5633 'change input': 'updateHandler',
5634 'change select': 'updateHandler',
5635 'change textarea': 'updateHandler'
5638 initialize: function() {
5639 this.model = this.model || new Backbone.Model();
5640 this.model.on( 'change', this.updateChanges, this );
5643 prepare: function() {
5645 model: this.model.toJSON()
5649 * @returns {wp.media.view.Settings} Returns itself to allow chaining
5651 render: function() {
5652 media.View.prototype.render.apply( this, arguments );
5653 // Select the correct values.
5654 _( this.model.attributes ).chain().keys().each( this.update, this );
5658 * @param {string} key
5660 update: function( key ) {
5661 var value = this.model.get( key ),
5662 $setting = this.$('[data-setting="' + key + '"]'),
5665 // Bail if we didn't find a matching setting.
5666 if ( ! $setting.length ) {
5670 // Attempt to determine how the setting is rendered and update
5671 // the selected value.
5673 // Handle dropdowns.
5674 if ( $setting.is('select') ) {
5675 $value = $setting.find('[value="' + value + '"]');
5677 if ( $value.length ) {
5678 $setting.find('option').prop( 'selected', false );
5679 $value.prop( 'selected', true );
5681 // If we can't find the desired value, record what *is* selected.
5682 this.model.set( key, $setting.find(':selected').val() );
5685 // Handle button groups.
5686 } else if ( $setting.hasClass('button-group') ) {
5687 $buttons = $setting.find('button').removeClass('active');
5688 $buttons.filter( '[value="' + value + '"]' ).addClass('active');
5690 // Handle text inputs and textareas.
5691 } else if ( $setting.is('input[type="text"], textarea') ) {
5692 if ( ! $setting.is(':focus') ) {
5693 $setting.val( value );
5695 // Handle checkboxes.
5696 } else if ( $setting.is('input[type="checkbox"]') ) {
5697 $setting.prop( 'checked', !! value );
5701 * @param {Object} event
5703 updateHandler: function( event ) {
5704 var $setting = $( event.target ).closest('[data-setting]'),
5705 value = event.target.value,
5708 event.preventDefault();
5710 if ( ! $setting.length ) {
5714 // Use the correct value for checkboxes.
5715 if ( $setting.is('input[type="checkbox"]') ) {
5716 value = $setting[0].checked;
5719 // Update the corresponding setting.
5720 this.model.set( $setting.data('setting'), value );
5722 // If the setting has a corresponding user setting,
5723 // update that as well.
5724 if ( userSetting = $setting.data('userSetting') ) {
5725 setUserSetting( userSetting, value );
5729 updateChanges: function( model ) {
5730 if ( model.hasChanged() ) {
5731 _( model.changed ).chain().keys().each( this.update, this );
5737 * wp.media.view.Settings.AttachmentDisplay
5740 * @augments wp.media.view.Settings
5741 * @augments wp.media.View
5742 * @augments wp.Backbone.View
5743 * @augments Backbone.View
5745 media.view.Settings.AttachmentDisplay = media.view.Settings.extend({
5746 className: 'attachment-display-settings',
5747 template: media.template('attachment-display-settings'),
5749 initialize: function() {
5750 var attachment = this.options.attachment;
5752 _.defaults( this.options, {
5756 * call 'initialize' directly on the parent class
5758 media.view.Settings.prototype.initialize.apply( this, arguments );
5759 this.model.on( 'change:link', this.updateLinkTo, this );
5762 attachment.on( 'change:uploading', this.render, this );
5766 dispose: function() {
5767 var attachment = this.options.attachment;
5769 attachment.off( null, null, this );
5772 * call 'dispose' directly on the parent class
5774 media.view.Settings.prototype.dispose.apply( this, arguments );
5777 * @returns {wp.media.view.AttachmentDisplay} Returns itself to allow chaining
5779 render: function() {
5780 var attachment = this.options.attachment;
5782 _.extend( this.options, {
5783 sizes: attachment.get('sizes'),
5784 type: attachment.get('type')
5788 * call 'render' directly on the parent class
5790 media.view.Settings.prototype.render.call( this );
5791 this.updateLinkTo();
5795 updateLinkTo: function() {
5796 var linkTo = this.model.get('link'),
5797 $input = this.$('.link-to-custom'),
5798 attachment = this.options.attachment;
5800 if ( 'none' === linkTo || 'embed' === linkTo || ( ! attachment && 'custom' !== linkTo ) ) {
5801 $input.addClass( 'hidden' );
5806 if ( 'post' === linkTo ) {
5807 $input.val( attachment.get('link') );
5808 } else if ( 'file' === linkTo ) {
5809 $input.val( attachment.get('url') );
5810 } else if ( ! this.model.get('linkUrl') ) {
5811 $input.val('http://');
5814 $input.prop( 'readonly', 'custom' !== linkTo );
5817 $input.removeClass( 'hidden' );
5819 // If the input is visible, focus and select its contents.
5820 if ( $input.is(':visible') ) {
5821 $input.focus()[0].select();
5827 * wp.media.view.Settings.Gallery
5830 * @augments wp.media.view.Settings
5831 * @augments wp.media.View
5832 * @augments wp.Backbone.View
5833 * @augments Backbone.View
5835 media.view.Settings.Gallery = media.view.Settings.extend({
5836 className: 'collection-settings gallery-settings',
5837 template: media.template('gallery-settings')
5841 * wp.media.view.Settings.Playlist
5844 * @augments wp.media.view.Settings
5845 * @augments wp.media.View
5846 * @augments wp.Backbone.View
5847 * @augments Backbone.View
5849 media.view.Settings.Playlist = media.view.Settings.extend({
5850 className: 'collection-settings playlist-settings',
5851 template: media.template('playlist-settings')
5855 * wp.media.view.Attachment.Details
5858 * @augments wp.media.view.Attachment
5859 * @augments wp.media.View
5860 * @augments wp.Backbone.View
5861 * @augments Backbone.View
5863 media.view.Attachment.Details = media.view.Attachment.extend({
5865 className: 'attachment-details',
5866 template: media.template('attachment-details'),
5869 'change [data-setting]': 'updateSetting',
5870 'change [data-setting] input': 'updateSetting',
5871 'change [data-setting] select': 'updateSetting',
5872 'change [data-setting] textarea': 'updateSetting',
5873 'click .delete-attachment': 'deleteAttachment',
5874 'click .trash-attachment': 'trashAttachment',
5875 'click .edit-attachment': 'editAttachment',
5876 'click .refresh-attachment': 'refreshAttachment'
5879 initialize: function() {
5881 * @member {wp.media.view.FocusManager}
5883 this.focusManager = new media.view.FocusManager({
5887 * call 'initialize' directly on the parent class
5889 media.view.Attachment.prototype.initialize.apply( this, arguments );
5892 * @returns {wp.media.view..Attachment.Details} Returns itself to allow chaining
5894 render: function() {
5896 * call 'render' directly on the parent class
5898 media.view.Attachment.prototype.render.apply( this, arguments );
5899 this.focusManager.focus();
5903 * @param {Object} event
5905 deleteAttachment: function( event ) {
5906 event.preventDefault();
5908 if ( confirm( l10n.warnDelete ) ) {
5909 this.model.destroy();
5913 * @param {Object} event
5915 trashAttachment: function( event ) {
5916 event.preventDefault();
5918 this.model.destroy();
5921 * @param {Object} event
5923 editAttachment: function( event ) {
5924 var editState = this.controller.states.get( 'edit-image' );
5925 if ( window.imageEdit && editState ) {
5926 event.preventDefault();
5928 editState.set( 'image', this.model );
5929 this.controller.setState( 'edit-image' );
5931 this.$el.addClass('needs-refresh');
5935 * @param {Object} event
5937 refreshAttachment: function( event ) {
5938 this.$el.removeClass('needs-refresh');
5939 event.preventDefault();
5946 * wp.media.view.AttachmentCompat
5949 * @augments wp.media.View
5950 * @augments wp.Backbone.View
5951 * @augments Backbone.View
5953 media.view.AttachmentCompat = media.View.extend({
5955 className: 'compat-item',
5958 'submit': 'preventDefault',
5959 'change input': 'save',
5960 'change select': 'save',
5961 'change textarea': 'save'
5964 initialize: function() {
5966 * @member {wp.media.view.FocusManager}
5968 this.focusManager = new media.view.FocusManager({
5972 this.model.on( 'change:compat', this.render, this );
5975 * @returns {wp.media.view.AttachmentCompat} Returns itself to allow chaining
5977 dispose: function() {
5978 if ( this.$(':focus').length ) {
5982 * call 'dispose' directly on the parent class
5984 return media.View.prototype.dispose.apply( this, arguments );
5987 * @returns {wp.media.view.AttachmentCompat} Returns itself to allow chaining
5989 render: function() {
5990 var compat = this.model.get('compat');
5991 if ( ! compat || ! compat.item ) {
5995 this.views.detach();
5996 this.$el.html( compat.item );
5997 this.views.render();
5999 this.focusManager.focus();
6003 * @param {Object} event
6005 preventDefault: function( event ) {
6006 event.preventDefault();
6009 * @param {Object} event
6011 save: function( event ) {
6015 event.preventDefault();
6018 _.each( this.$el.serializeArray(), function( pair ) {
6019 data[ pair.name ] = pair.value;
6022 this.model.saveCompat( data );
6027 * wp.media.view.Iframe
6030 * @augments wp.media.View
6031 * @augments wp.Backbone.View
6032 * @augments Backbone.View
6034 media.view.Iframe = media.View.extend({
6035 className: 'media-iframe',
6037 * @returns {wp.media.view.Iframe} Returns itself to allow chaining
6039 render: function() {
6040 this.views.detach();
6041 this.$el.html( '<iframe src="' + this.controller.state().get('src') + '" />' );
6042 this.views.render();
6048 * wp.media.view.Embed
6051 * @augments wp.media.View
6052 * @augments wp.Backbone.View
6053 * @augments Backbone.View
6055 media.view.Embed = media.View.extend({
6056 className: 'media-embed',
6058 initialize: function() {
6060 * @member {wp.media.view.EmbedUrl}
6062 this.url = new media.view.EmbedUrl({
6063 controller: this.controller,
6064 model: this.model.props
6067 this.views.set([ this.url ]);
6069 this.model.on( 'change:type', this.refresh, this );
6070 this.model.on( 'change:loading', this.loading, this );
6074 * @param {Object} view
6076 settings: function( view ) {
6077 if ( this._settings ) {
6078 this._settings.remove();
6080 this._settings = view;
6081 this.views.add( view );
6084 refresh: function() {
6085 var type = this.model.get('type'),
6088 if ( 'image' === type ) {
6089 constructor = media.view.EmbedImage;
6090 } else if ( 'link' === type ) {
6091 constructor = media.view.EmbedLink;
6096 this.settings( new constructor({
6097 controller: this.controller,
6098 model: this.model.props,
6103 loading: function() {
6104 this.$el.toggleClass( 'embed-loading', this.model.get('loading') );
6109 * wp.media.view.EmbedUrl
6112 * @augments wp.media.View
6113 * @augments wp.Backbone.View
6114 * @augments Backbone.View
6116 media.view.EmbedUrl = media.View.extend({
6118 className: 'embed-url',
6126 initialize: function() {
6127 this.$input = $('<input/>').attr( 'type', 'text' ).val( this.model.get('url') );
6128 this.input = this.$input[0];
6130 this.spinner = $('<span class="spinner" />')[0];
6131 this.$el.append([ this.input, this.spinner ]);
6133 this.model.on( 'change:url', this.render, this );
6136 * @returns {wp.media.view.EmbedUrl} Returns itself to allow chaining
6138 render: function() {
6139 var $input = this.$input;
6141 if ( $input.is(':focus') ) {
6145 this.input.value = this.model.get('url') || 'http://';
6147 * Call `render` directly on parent class with passed arguments
6149 media.View.prototype.render.apply( this, arguments );
6157 url: function( event ) {
6158 this.model.set( 'url', event.target.value );
6162 * If the input is visible, focus and select its contents.
6165 var $input = this.$input;
6166 if ( $input.is(':visible') ) {
6167 $input.focus()[0].select();
6173 * wp.media.view.EmbedLink
6176 * @augments wp.media.view.Settings
6177 * @augments wp.media.View
6178 * @augments wp.Backbone.View
6179 * @augments Backbone.View
6181 media.view.EmbedLink = media.view.Settings.extend({
6182 className: 'embed-link-settings',
6183 template: media.template('embed-link-settings')
6187 * wp.media.view.EmbedImage
6190 * @augments wp.media.view.Settings.AttachmentDisplay
6191 * @augments wp.media.view.Settings
6192 * @augments wp.media.View
6193 * @augments wp.Backbone.View
6194 * @augments Backbone.View
6196 media.view.EmbedImage = media.view.Settings.AttachmentDisplay.extend({
6197 className: 'embed-media-settings',
6198 template: media.template('embed-image-settings'),
6200 initialize: function() {
6202 * Call `initialize` directly on parent class with passed arguments
6204 media.view.Settings.AttachmentDisplay.prototype.initialize.apply( this, arguments );
6205 this.model.on( 'change:url', this.updateImage, this );
6208 updateImage: function() {
6209 this.$('img').attr( 'src', this.model.get('url') );
6214 * wp.media.view.ImageDetails
6217 * @augments wp.media.view.Settings.AttachmentDisplay
6218 * @augments wp.media.view.Settings
6219 * @augments wp.media.View
6220 * @augments wp.Backbone.View
6221 * @augments Backbone.View
6223 media.view.ImageDetails = media.view.Settings.AttachmentDisplay.extend({
6224 className: 'image-details',
6225 template: media.template('image-details'),
6226 events: _.defaults( media.view.Settings.AttachmentDisplay.prototype.events, {
6227 'click .edit-attachment': 'editAttachment',
6228 'click .replace-attachment': 'replaceAttachment',
6229 'click .advanced-toggle': 'onToggleAdvanced',
6230 'change [data-setting="customWidth"]': 'onCustomSize',
6231 'change [data-setting="customHeight"]': 'onCustomSize',
6232 'keyup [data-setting="customWidth"]': 'onCustomSize',
6233 'keyup [data-setting="customHeight"]': 'onCustomSize'
6235 initialize: function() {
6236 // used in AttachmentDisplay.prototype.updateLinkTo
6237 this.options.attachment = this.model.attachment;
6238 this.listenTo( this.model, 'change:url', this.updateUrl );
6239 this.listenTo( this.model, 'change:link', this.toggleLinkSettings );
6240 this.listenTo( this.model, 'change:size', this.toggleCustomSize );
6242 media.view.Settings.AttachmentDisplay.prototype.initialize.apply( this, arguments );
6245 prepare: function() {
6246 var attachment = false;
6248 if ( this.model.attachment ) {
6249 attachment = this.model.attachment.toJSON();
6252 model: this.model.toJSON(),
6253 attachment: attachment
6257 render: function() {
6261 if ( this.model.attachment && 'pending' === this.model.dfd.state() ) {
6262 this.model.dfd.done( function() {
6263 media.view.Settings.AttachmentDisplay.prototype.render.apply( self, args );
6265 } ).fail( function() {
6266 self.model.attachment = false;
6267 media.view.Settings.AttachmentDisplay.prototype.render.apply( self, args );
6271 media.view.Settings.AttachmentDisplay.prototype.render.apply( this, arguments );
6278 postRender: function() {
6279 setTimeout( _.bind( this.resetFocus, this ), 10 );
6280 this.toggleLinkSettings();
6281 if ( getUserSetting( 'advImgDetails' ) === 'show' ) {
6282 this.toggleAdvanced( true );
6284 this.trigger( 'post-render' );
6287 resetFocus: function() {
6288 this.$( '.link-to-custom' ).blur();
6289 this.$( '.embed-media-settings' ).scrollTop( 0 );
6292 updateUrl: function() {
6293 this.$( '.image img' ).attr( 'src', this.model.get( 'url' ) );
6294 this.$( '.url' ).val( this.model.get( 'url' ) );
6297 toggleLinkSettings: function() {
6298 if ( this.model.get( 'link' ) === 'none' ) {
6299 this.$( '.link-settings' ).addClass('hidden');
6301 this.$( '.link-settings' ).removeClass('hidden');
6305 toggleCustomSize: function() {
6306 if ( this.model.get( 'size' ) !== 'custom' ) {
6307 this.$( '.custom-size' ).addClass('hidden');
6309 this.$( '.custom-size' ).removeClass('hidden');
6313 onCustomSize: function( event ) {
6314 var dimension = $( event.target ).data('setting'),
6315 num = $( event.target ).val(),
6318 // Ignore bogus input
6319 if ( ! /^\d+/.test( num ) || parseInt( num, 10 ) < 1 ) {
6320 event.preventDefault();
6324 if ( dimension === 'customWidth' ) {
6325 value = Math.round( 1 / this.model.get( 'aspectRatio' ) * num );
6326 this.model.set( 'customHeight', value, { silent: true } );
6327 this.$( '[data-setting="customHeight"]' ).val( value );
6329 value = Math.round( this.model.get( 'aspectRatio' ) * num );
6330 this.model.set( 'customWidth', value, { silent: true } );
6331 this.$( '[data-setting="customWidth"]' ).val( value );
6336 onToggleAdvanced: function( event ) {
6337 event.preventDefault();
6338 this.toggleAdvanced();
6341 toggleAdvanced: function( show ) {
6342 var $advanced = this.$el.find( '.advanced-section' ),
6345 if ( $advanced.hasClass('advanced-visible') || show === false ) {
6346 $advanced.removeClass('advanced-visible');
6347 $advanced.find('.advanced-settings').addClass('hidden');
6350 $advanced.addClass('advanced-visible');
6351 $advanced.find('.advanced-settings').removeClass('hidden');
6355 setUserSetting( 'advImgDetails', mode );
6358 editAttachment: function( event ) {
6359 var editState = this.controller.states.get( 'edit-image' );
6361 if ( window.imageEdit && editState ) {
6362 event.preventDefault();
6363 editState.set( 'image', this.model.attachment );
6364 this.controller.setState( 'edit-image' );
6368 replaceAttachment: function( event ) {
6369 event.preventDefault();
6370 this.controller.setState( 'replace-image' );
6375 * wp.media.view.Cropper
6377 * Uses the imgAreaSelect plugin to allow a user to crop an image.
6379 * Takes imgAreaSelect options from
6380 * wp.customize.HeaderControl.calculateImageSelectOptions via
6381 * wp.customize.HeaderControl.openMM.
6384 * @augments wp.media.View
6385 * @augments wp.Backbone.View
6386 * @augments Backbone.View
6388 media.view.Cropper = media.View.extend({
6389 className: 'crop-content',
6390 template: media.template('crop-content'),
6391 initialize: function() {
6392 _.bindAll(this, 'onImageLoad');
6395 this.controller.frame.on('content:error:crop', this.onError, this);
6396 this.$image = this.$el.find('.crop-image');
6397 this.$image.on('load', this.onImageLoad);
6398 $(window).on('resize.cropper', _.debounce(this.onImageLoad, 250));
6400 remove: function() {
6401 $(window).off('resize.cropper');
6404 wp.media.View.prototype.remove.apply(this, arguments);
6406 prepare: function() {
6408 title: l10n.cropYourImage,
6409 url: this.options.attachment.get('url')
6412 onImageLoad: function() {
6413 var imgOptions = this.controller.get('imgSelectOptions');
6414 if (typeof imgOptions === 'function') {
6415 imgOptions = imgOptions(this.options.attachment, this.controller);
6418 imgOptions = _.extend(imgOptions, {parent: this.$el});
6419 this.trigger('image-loaded');
6420 this.controller.imgSelect = this.$image.imgAreaSelect(imgOptions);
6422 onError: function() {
6423 var filename = this.options.attachment.get('filename');
6425 this.views.add( '.upload-errors', new media.view.UploaderStatusError({
6426 filename: media.view.UploaderStatus.prototype.filename(filename),
6427 message: _wpMediaViewsL10n.cropError
6432 media.view.EditImage = media.View.extend({
6434 className: 'image-editor',
6435 template: media.template('image-editor'),
6437 initialize: function( options ) {
6438 this.editor = window.imageEdit;
6439 this.controller = options.controller;
6440 media.View.prototype.initialize.apply( this, arguments );
6443 prepare: function() {
6444 return this.model.toJSON();
6447 render: function() {
6448 media.View.prototype.render.apply( this, arguments );
6452 loadEditor: function() {
6453 this.editor.open( this.model.get('id'), this.model.get('nonces').edit, this );
6457 var lastState = this.controller.lastState();
6458 this.controller.setState( lastState );
6461 refresh: function() {
6467 lastState = this.controller.lastState();
6469 this.model.fetch().done( function() {
6470 self.controller.setState( lastState );
6477 * wp.media.view.Spinner
6480 * @augments wp.media.View
6481 * @augments wp.Backbone.View
6482 * @augments Backbone.View
6484 media.view.Spinner = media.View.extend({
6486 className: 'spinner',
6487 spinnerTimeout: false,
6491 if ( ! this.spinnerTimeout ) {
6492 this.spinnerTimeout = _.delay(function( $el ) {
6494 }, this.delay, this.$el );
6502 this.spinnerTimeout = clearTimeout( this.spinnerTimeout );