1 /* global _wpMediaViewsL10n, confirm, getUserSetting, setUserSetting */
5 isTouchDevice = ( 'ontouchend' in document );
7 // Link any localized strings.
8 l10n = media.view.l10n = typeof _wpMediaViewsL10n === 'undefined' ? {} : _wpMediaViewsL10n;
11 media.view.settings = l10n.settings || {};
14 // Copy the `post` setting over to the model settings.
15 media.model.settings.post = media.view.settings.post;
17 // Check if the browser supports CSS 3.0 transitions
18 $.support.transition = (function(){
19 var style = document.documentElement.style,
21 WebkitTransition: 'webkitTransitionEnd',
22 MozTransition: 'transitionend',
23 OTransition: 'oTransitionEnd otransitionend',
24 transition: 'transitionend'
27 transition = _.find( _.keys( transitions ), function( transition ) {
28 return ! _.isUndefined( style[ transition ] );
31 return transition && {
32 end: transitions[ transition ]
37 * A shared event bus used to provide events into
38 * the media workflows that 3rd-party devs can use to hook
41 media.events = _.extend( {}, Backbone.Events );
44 * Makes it easier to bind events using transitions.
46 * @param {string} selector
47 * @param {Number} sensitivity
50 media.transition = function( selector, sensitivity ) {
51 var deferred = $.Deferred();
53 sensitivity = sensitivity || 2000;
55 if ( $.support.transition ) {
56 if ( ! (selector instanceof $) ) {
57 selector = $( selector );
60 // Resolve the deferred when the first element finishes animating.
61 selector.first().one( $.support.transition.end, deferred.resolve );
63 // Just in case the event doesn't trigger, fire a callback.
64 _.delay( deferred.resolve, sensitivity );
66 // Otherwise, execute on the spot.
71 return deferred.promise();
75 * wp.media.controller.Region
77 * A region is a persistent application layout area.
79 * A region assumes one mode at any time, and can be switched to another.
81 * When mode changes, events are triggered on the region's parent view.
82 * The parent view will listen to specific events and fill the region with an
83 * appropriate view depending on mode. For example, a frame listens for the
84 * 'browse' mode t be activated on the 'content' view and then fills the region
85 * with an AttachmentsBrowser view.
89 * @param {object} options Options hash for the region.
90 * @param {string} options.id Unique identifier for the region.
91 * @param {Backbone.View} options.view A parent view the region exists within.
92 * @param {string} options.selector jQuery selector for the region within the parent view.
94 media.controller.Region = function( options ) {
95 _.extend( this, _.pick( options || {}, 'id', 'view', 'selector' ) );
98 // Use Backbone's self-propagating `extend` inheritance method.
99 media.controller.Region.extend = Backbone.Model.extend;
101 _.extend( media.controller.Region.prototype, {
107 * @param {string} mode
109 * @fires this.view#{this.id}:activate:{this._mode}
110 * @fires this.view#{this.id}:activate
111 * @fires this.view#{this.id}:deactivate:{this._mode}
112 * @fires this.view#{this.id}:deactivate
114 * @returns {wp.media.controller.Region} Returns itself to allow chaining.
116 mode: function( mode ) {
120 // Bail if we're trying to change to the current mode.
121 if ( mode === this._mode ) {
126 * Region mode deactivation event.
128 * @event this.view#{this.id}:deactivate:{this._mode}
129 * @event this.view#{this.id}:deactivate
131 this.trigger('deactivate');
137 * Region mode activation event.
139 * @event this.view#{this.id}:activate:{this._mode}
140 * @event this.view#{this.id}:activate
142 this.trigger('activate');
150 * @param {string} mode
152 * @fires this.view#{this.id}:create:{this._mode}
153 * @fires this.view#{this.id}:create
154 * @fires this.view#{this.id}:render:{this._mode}
155 * @fires this.view#{this.id}:render
157 * @returns {wp.media.controller.Region} Returns itself to allow chaining
159 render: function( mode ) {
160 // If the mode isn't active, activate it.
161 if ( mode && mode !== this._mode ) {
162 return this.mode( mode );
165 var set = { view: null },
169 * Create region view event.
171 * Region view creation takes place in an event callback on the frame.
173 * @event this.view#{this.id}:create:{this._mode}
174 * @event this.view#{this.id}:create
176 this.trigger( 'create', set );
180 * Render region view event.
182 * Region view creation takes place in an event callback on the frame.
184 * @event this.view#{this.id}:create:{this._mode}
185 * @event this.view#{this.id}:create
187 this.trigger( 'render', view );
195 * Get the region's view.
199 * @returns {wp.media.View}
202 return this.view.views.first( this.selector );
206 * Set the region's view as a subview of the frame.
210 * @param {Array|Object} views
211 * @param {Object} [options={}]
212 * @returns {wp.Backbone.Subviews} Subviews is returned to allow chaining
214 set: function( views, options ) {
218 return this.view.views.set( this.selector, views, options );
222 * Trigger regional view events on the frame.
226 * @param {string} event
227 * @returns {undefined|wp.media.controller.Region} Returns itself to allow chaining.
229 trigger: function( event ) {
232 if ( ! this._mode ) {
236 args = _.toArray( arguments );
237 base = this.id + ':' + event;
239 // Trigger `{this.id}:{event}:{this._mode}` event on the frame.
240 args[0] = base + ':' + this._mode;
241 this.view.trigger.apply( this.view, args );
243 // Trigger `{this.id}:{event}` event on the frame.
245 this.view.trigger.apply( this.view, args );
251 * wp.media.controller.StateMachine
253 * A state machine keeps track of state. It is in one state at a time,
254 * and can change from one state to another.
256 * States are stored as models in a Backbone collection.
261 * @augments Backbone.Model
263 * @mixes Backbone.Events
265 * @param {Array} states
267 media.controller.StateMachine = function( states ) {
268 // @todo This is dead code. The states collection gets created in media.view.Frame._createStates.
269 this.states = new Backbone.Collection( states );
272 // Use Backbone's self-propagating `extend` inheritance method.
273 media.controller.StateMachine.extend = Backbone.Model.extend;
275 _.extend( media.controller.StateMachine.prototype, Backbone.Events, {
279 * If no `id` is provided, returns the active state.
281 * Implicitly creates states.
283 * Ensure that the `states` collection exists so the `StateMachine`
284 * can be used as a mixin.
289 * @returns {wp.media.controller.State} Returns a State model
290 * from the StateMachine collection
292 state: function( id ) {
293 this.states = this.states || new Backbone.Collection();
295 // Default to the active state.
296 id = id || this._state;
298 if ( id && ! this.states.get( id ) ) {
299 this.states.add({ id: id });
301 return this.states.get( id );
305 * Sets the active state.
307 * Bail if we're trying to select the current state, if we haven't
308 * created the `states` collection, or are trying to select a state
309 * that does not exist.
315 * @fires wp.media.controller.State#deactivate
316 * @fires wp.media.controller.State#activate
318 * @returns {wp.media.controller.StateMachine} Returns itself to allow chaining
320 setState: function( id ) {
321 var previous = this.state();
323 if ( ( previous && id === previous.id ) || ! this.states || ! this.states.get( id ) ) {
328 previous.trigger('deactivate');
329 this._lastState = previous.id;
333 this.state().trigger('activate');
339 * Returns the previous active state.
341 * Call the `state()` method with no parameters to retrieve the current
346 * @returns {wp.media.controller.State} Returns a State model
347 * from the StateMachine collection
349 lastState: function() {
350 if ( this._lastState ) {
351 return this.state( this._lastState );
356 // Map all event binding and triggering on a StateMachine to its `states` collection.
357 _.each([ 'on', 'off', 'trigger' ], function( method ) {
359 * @returns {wp.media.controller.StateMachine} Returns itself to allow chaining.
361 media.controller.StateMachine.prototype[ method ] = function() {
362 // Ensure that the `states` collection exists so the `StateMachine`
363 // can be used as a mixin.
364 this.states = this.states || new Backbone.Collection();
365 // Forward the method to the `states` collection.
366 this.states[ method ].apply( this.states, arguments );
372 * wp.media.controller.State
374 * A state is a step in a workflow that when set will trigger the controllers
375 * for the regions to be updated as specified in the frame.
377 * A state has an event-driven lifecycle:
379 * 'ready' triggers when a state is added to a state machine's collection.
380 * 'activate' triggers when a state is activated by a state machine.
381 * 'deactivate' triggers when a state is deactivated by a state machine.
382 * 'reset' is not triggered automatically. It should be invoked by the
383 * proper controller to reset the state to its default.
386 * @augments Backbone.Model
388 media.controller.State = Backbone.Model.extend({
394 constructor: function() {
395 this.on( 'activate', this._preActivate, this );
396 this.on( 'activate', this.activate, this );
397 this.on( 'activate', this._postActivate, this );
398 this.on( 'deactivate', this._deactivate, this );
399 this.on( 'deactivate', this.deactivate, this );
400 this.on( 'reset', this.reset, this );
401 this.on( 'ready', this._ready, this );
402 this.on( 'ready', this.ready, this );
404 * Call parent constructor with passed arguments
406 Backbone.Model.apply( this, arguments );
407 this.on( 'change:menu', this._updateMenu, this );
410 * Ready event callback.
415 ready: function() {},
418 * Activate event callback.
423 activate: function() {},
426 * Deactivate event callback.
431 deactivate: function() {},
434 * Reset event callback.
439 reset: function() {},
453 _preActivate: function() {
461 _postActivate: function() {
462 this.on( 'change:menu', this._menu, this );
463 this.on( 'change:titleMode', this._title, this );
464 this.on( 'change:content', this._content, this );
465 this.on( 'change:toolbar', this._toolbar, this );
467 this.frame.on( 'title:render:default', this._renderTitle, this );
480 _deactivate: function() {
483 this.frame.off( 'title:render:default', this._renderTitle, this );
485 this.off( 'change:menu', this._menu, this );
486 this.off( 'change:titleMode', this._title, this );
487 this.off( 'change:content', this._content, this );
488 this.off( 'change:toolbar', this._toolbar, this );
496 this.frame.title.render( this.get('titleMode') || 'default' );
503 _renderTitle: function( view ) {
504 view.$el.text( this.get('title') || '' );
511 _router: function() {
512 var router = this.frame.router,
513 mode = this.get('router'),
516 this.frame.$el.toggleClass( 'hide-router', ! mode );
521 this.frame.router.render( mode );
524 if ( view && view.select ) {
525 view.select( this.frame.content.mode() );
534 var menu = this.frame.menu,
535 mode = this.get('menu'),
538 this.frame.$el.toggleClass( 'hide-menu', ! mode );
546 if ( view && view.select ) {
547 view.select( this.id );
555 _updateMenu: function() {
556 var previous = this.previous('menu'),
557 menu = this.get('menu');
560 this.frame.off( 'menu:render:' + previous, this._renderMenu, this );
564 this.frame.on( 'menu:render:' + menu, this._renderMenu, this );
569 * Create a view in the media menu for the state.
574 * @param {media.view.Menu} view The menu view.
576 _renderMenu: function( view ) {
577 var menuItem = this.get('menuItem'),
578 title = this.get('title'),
579 priority = this.get('priority');
581 if ( ! menuItem && title ) {
582 menuItem = { text: title };
585 menuItem.priority = priority;
593 view.set( this.id, menuItem );
597 _.each(['toolbar','content'], function( region ) {
601 media.controller.State.prototype[ '_' + region ] = function() {
602 var mode = this.get( region );
604 this.frame[ region ].render( mode );
610 * wp.media.selectionSync
612 * Sync an attachments selection in a state with another state.
614 * Allows for selecting multiple images in the Insert Media workflow, and then
615 * switching to the Insert Gallery workflow while preserving the attachments selection.
619 media.selectionSync = {
623 syncSelection: function() {
624 var selection = this.get('selection'),
625 manager = this.frame._selection;
627 if ( ! this.get('syncSelection') || ! manager || ! selection ) {
631 // If the selection supports multiple items, validate the stored
632 // attachments based on the new selection's conditions. Record
633 // the attachments that are not included; we'll maintain a
634 // reference to those. Other attachments are considered in flux.
635 if ( selection.multiple ) {
636 selection.reset( [], { silent: true });
637 selection.validateAll( manager.attachments );
638 manager.difference = _.difference( manager.attachments.models, selection.models );
641 // Sync the selection's single item with the master.
642 selection.single( manager.single );
646 * Record the currently active attachments, which is a combination
647 * of the selection's attachments and the set of selected
648 * attachments that this specific selection considered invalid.
649 * Reset the difference and record the single attachment.
653 recordSelection: function() {
654 var selection = this.get('selection'),
655 manager = this.frame._selection;
657 if ( ! this.get('syncSelection') || ! manager || ! selection ) {
661 if ( selection.multiple ) {
662 manager.attachments.reset( selection.toArray().concat( manager.difference ) );
663 manager.difference = [];
665 manager.attachments.add( selection.toArray() );
668 manager.single = selection._single;
673 * wp.media.controller.Library
675 * A state for choosing an attachment or group of attachments from the media library.
678 * @augments wp.media.controller.State
679 * @augments Backbone.Model
680 * @mixes media.selectionSync
682 * @param {object} [attributes] The attributes hash passed to the state.
683 * @param {string} [attributes.id=library] Unique identifier.
684 * @param {string} [attributes.title=Media library] Title for the state. Displays in the media menu and the frame's title region.
685 * @param {wp.media.model.Attachments} [attributes.library] The attachments collection to browse.
686 * If one is not supplied, a collection of all attachments will be created.
687 * @param {wp.media.model.Selection|object} [attributes.selection] A collection to contain attachment selections within the state.
688 * If the 'selection' attribute is a plain JS object,
689 * a Selection will be created using its values as the selection instance's `props` model.
690 * Otherwise, it will copy the library's `props` model.
691 * @param {boolean} [attributes.multiple=false] Whether multi-select is enabled.
692 * @param {string} [attributes.content=upload] Initial mode for the content region.
693 * Overridden by persistent user setting if 'contentUserSetting' is true.
694 * @param {string} [attributes.menu=default] Initial mode for the menu region.
695 * @param {string} [attributes.router=browse] Initial mode for the router region.
696 * @param {string} [attributes.toolbar=select] Initial mode for the toolbar region.
697 * @param {boolean} [attributes.searchable=true] Whether the library is searchable.
698 * @param {boolean|string} [attributes.filterable=false] Whether the library is filterable, and if so what filters should be shown.
699 * Accepts 'all', 'uploaded', or 'unattached'.
700 * @param {boolean} [attributes.sortable=true] Whether the Attachments should be sortable. Depends on the orderby property being set to menuOrder on the attachments collection.
701 * @param {boolean} [attributes.autoSelect=true] Whether an uploaded attachment should be automatically added to the selection.
702 * @param {boolean} [attributes.describe=false] Whether to offer UI to describe attachments - e.g. captioning images in a gallery.
703 * @param {boolean} [attributes.contentUserSetting=true] Whether the content region's mode should be set and persisted per user.
704 * @param {boolean} [attributes.syncSelection=true] Whether the Attachments selection should be persisted from the last state.
706 media.controller.Library = media.controller.State.extend({
709 title: l10n.mediaLibraryTitle,
720 contentUserSetting: true,
725 * If a library isn't provided, query all media items.
726 * If a selection instance isn't provided, create one.
730 initialize: function() {
731 var selection = this.get('selection'),
734 if ( ! this.get('library') ) {
735 this.set( 'library', media.query() );
738 if ( ! (selection instanceof media.model.Selection) ) {
742 props = this.get('library').props.toJSON();
743 props = _.omit( props, 'orderby', 'query' );
746 this.set( 'selection', new media.model.Selection( null, {
747 multiple: this.get('multiple'),
752 this.resetDisplays();
758 activate: function() {
759 this.syncSelection();
761 wp.Uploader.queue.on( 'add', this.uploading, this );
763 this.get('selection').on( 'add remove reset', this.refreshContent, this );
765 if ( this.get( 'router' ) && this.get('contentUserSetting') ) {
766 this.frame.on( 'content:activate', this.saveContentMode, this );
767 this.set( 'content', getUserSetting( 'libraryContent', this.get('content') ) );
774 deactivate: function() {
775 this.recordSelection();
777 this.frame.off( 'content:activate', this.saveContentMode, this );
779 // Unbind all event handlers that use this state as the context
780 // from the selection.
781 this.get('selection').off( null, null, this );
783 wp.Uploader.queue.off( null, null, this );
787 * Reset the library to its initial state.
792 this.get('selection').reset();
793 this.resetDisplays();
794 this.refreshContent();
798 * Reset the attachment display settings defaults to the site options.
800 * If site options don't define them, fall back to a persistent user setting.
804 resetDisplays: function() {
805 var defaultProps = media.view.settings.defaultProps;
807 this._defaultDisplaySettings = {
808 align: defaultProps.align || getUserSetting( 'align', 'none' ),
809 size: defaultProps.size || getUserSetting( 'imgsize', 'medium' ),
810 link: defaultProps.link || getUserSetting( 'urlbutton', 'file' )
815 * Create a model to represent display settings (alignment, etc.) for an attachment.
819 * @param {wp.media.model.Attachment} attachment
820 * @returns {Backbone.Model}
822 display: function( attachment ) {
823 var displays = this._displays;
825 if ( ! displays[ attachment.cid ] ) {
826 displays[ attachment.cid ] = new Backbone.Model( this.defaultDisplaySettings( attachment ) );
828 return displays[ attachment.cid ];
832 * Given an attachment, create attachment display settings properties.
836 * @param {wp.media.model.Attachment} attachment
839 defaultDisplaySettings: function( attachment ) {
840 var settings = this._defaultDisplaySettings;
841 if ( settings.canEmbed = this.canEmbed( attachment ) ) {
842 settings.link = 'embed';
848 * Whether an attachment can be embedded (audio or video).
852 * @param {wp.media.model.Attachment} attachment
855 canEmbed: function( attachment ) {
856 // If uploading, we know the filename but not the mime type.
857 if ( ! attachment.get('uploading') ) {
858 var type = attachment.get('type');
859 if ( type !== 'audio' && type !== 'video' ) {
864 return _.contains( media.view.settings.embedExts, attachment.get('filename').split('.').pop() );
869 * If the state is active, no items are selected, and the current
870 * content mode is not an option in the state's router (provided
871 * the state has a router), reset the content mode to the default.
875 refreshContent: function() {
876 var selection = this.get('selection'),
878 router = frame.router.get(),
879 mode = frame.content.mode();
881 if ( this.active && ! selection.length && router && ! router.get( mode ) ) {
882 this.frame.content.render( this.get('content') );
887 * Callback handler when an attachment is uploaded.
889 * Switch to the Media Library if uploaded from the 'Upload Files' tab.
891 * Adds any uploading attachments to the selection.
893 * If the state only supports one attachment to be selected and multiple
894 * attachments are uploaded, the last attachment in the upload queue will
899 * @param {wp.media.model.Attachment} attachment
901 uploading: function( attachment ) {
902 var content = this.frame.content;
904 if ( 'upload' === content.mode() ) {
905 this.frame.content.mode('browse');
908 if ( this.get( 'autoSelect' ) ) {
909 this.get('selection').add( attachment );
910 this.frame.trigger( 'library:selection:add' );
915 * Persist the mode of the content region as a user setting.
919 saveContentMode: function() {
920 if ( 'browse' !== this.get('router') ) {
924 var mode = this.frame.content.mode(),
925 view = this.frame.router.get();
927 if ( view && view.get( mode ) ) {
928 setUserSetting( 'libraryContent', mode );
933 // Make selectionSync available on any Media Library state.
934 _.extend( media.controller.Library.prototype, media.selectionSync );
937 * wp.media.controller.ImageDetails
939 * A state for editing the attachment display settings of an image that's been
940 * inserted into the editor.
943 * @augments wp.media.controller.State
944 * @augments Backbone.Model
946 * @param {object} [attributes] The attributes hash passed to the state.
947 * @param {string} [attributes.id=image-details] Unique identifier.
948 * @param {string} [attributes.title=Image Details] Title for the state. Displays in the frame's title region.
949 * @param {wp.media.model.Attachment} attributes.image The image's model.
950 * @param {string|false} [attributes.content=image-details] Initial mode for the content region.
951 * @param {string|false} [attributes.menu=false] Initial mode for the menu region.
952 * @param {string|false} [attributes.router=false] Initial mode for the router region.
953 * @param {string|false} [attributes.toolbar=image-details] Initial mode for the toolbar region.
954 * @param {boolean} [attributes.editing=false] Unused.
955 * @param {int} [attributes.priority=60] Unused.
957 * @todo This state inherits some defaults from media.controller.Library.prototype.defaults,
958 * however this may not do anything.
960 media.controller.ImageDetails = media.controller.State.extend({
961 defaults: _.defaults({
963 title: l10n.imageDetailsTitle,
964 content: 'image-details',
967 toolbar: 'image-details',
970 }, media.controller.Library.prototype.defaults ),
975 * @param options Attributes
977 initialize: function( options ) {
978 this.image = options.image;
979 media.controller.State.prototype.initialize.apply( this, arguments );
985 activate: function() {
986 this.frame.modal.$el.addClass('image-details');
991 * wp.media.controller.GalleryEdit
993 * A state for editing a gallery's images and settings.
996 * @augments wp.media.controller.Library
997 * @augments wp.media.controller.State
998 * @augments Backbone.Model
1000 * @param {object} [attributes] The attributes hash passed to the state.
1001 * @param {string} [attributes.id=gallery-edit] Unique identifier.
1002 * @param {string} [attributes.title=Edit Gallery] Title for the state. Displays in the frame's title region.
1003 * @param {wp.media.model.Attachments} [attributes.library] The collection of attachments in the gallery.
1004 * If one is not supplied, an empty media.model.Selection collection is created.
1005 * @param {boolean} [attributes.multiple=false] Whether multi-select is enabled.
1006 * @param {boolean} [attributes.searchable=false] Whether the library is searchable.
1007 * @param {boolean} [attributes.sortable=true] Whether the Attachments should be sortable. Depends on the orderby property being set to menuOrder on the attachments collection.
1008 * @param {string|false} [attributes.content=browse] Initial mode for the content region.
1009 * @param {string|false} [attributes.toolbar=image-details] Initial mode for the toolbar region.
1010 * @param {boolean} [attributes.describe=true] Whether to offer UI to describe attachments - e.g. captioning images in a gallery.
1011 * @param {boolean} [attributes.displaySettings=true] Whether to show the attachment display settings interface.
1012 * @param {boolean} [attributes.dragInfo=true] Whether to show instructional text about the attachments being sortable.
1013 * @param {int} [attributes.idealColumnWidth=170] The ideal column width in pixels for attachments.
1014 * @param {boolean} [attributes.editing=false] Whether the gallery is being created, or editing an existing instance.
1015 * @param {int} [attributes.priority=60] The priority for the state link in the media menu.
1016 * @param {boolean} [attributes.syncSelection=false] Whether the Attachments selection should be persisted from the last state.
1017 * Defaults to false for this state, because the library passed in *is* the selection.
1018 * @param {view} [attributes.AttachmentView] The single `Attachment` view to be used in the `Attachments`.
1019 * If none supplied, defaults to wp.media.view.Attachment.EditLibrary.
1021 media.controller.GalleryEdit = media.controller.Library.extend({
1024 title: l10n.editGalleryTitle,
1030 toolbar: 'gallery-edit',
1032 displaySettings: true,
1034 idealColumnWidth: 170,
1037 syncSelection: false
1043 initialize: function() {
1044 // If we haven't been provided a `library`, create a `Selection`.
1045 if ( ! this.get('library') )
1046 this.set( 'library', new media.model.Selection() );
1048 // The single `Attachment` view to be used in the `Attachments` view.
1049 if ( ! this.get('AttachmentView') )
1050 this.set( 'AttachmentView', media.view.Attachment.EditLibrary );
1051 media.controller.Library.prototype.initialize.apply( this, arguments );
1057 activate: function() {
1058 var library = this.get('library');
1060 // Limit the library to images only.
1061 library.props.set( 'type', 'image' );
1063 // Watch for uploaded attachments.
1064 this.get('library').observe( wp.Uploader.queue );
1066 this.frame.on( 'content:render:browse', this.gallerySettings, this );
1068 media.controller.Library.prototype.activate.apply( this, arguments );
1074 deactivate: function() {
1075 // Stop watching for uploaded attachments.
1076 this.get('library').unobserve( wp.Uploader.queue );
1078 this.frame.off( 'content:render:browse', this.gallerySettings, this );
1080 media.controller.Library.prototype.deactivate.apply( this, arguments );
1088 gallerySettings: function( browser ) {
1089 if ( ! this.get('displaySettings') ) {
1093 var library = this.get('library');
1095 if ( ! library || ! browser ) {
1099 library.gallery = library.gallery || new Backbone.Model();
1101 browser.sidebar.set({
1102 gallery: new media.view.Settings.Gallery({
1104 model: library.gallery,
1109 browser.toolbar.set( 'reverse', {
1110 text: l10n.reverseOrder,
1114 library.reset( library.toArray().reverse() );
1121 * A state for selecting more images to add to a gallery.
1124 * @augments wp.media.controller.Library
1125 * @augments wp.media.controller.State
1126 * @augments Backbone.Model
1128 * @param {object} [attributes] The attributes hash passed to the state.
1129 * @param {string} [attributes.id=gallery-library] Unique identifier.
1130 * @param {string} [attributes.title=Add to Gallery] Title for the state. Displays in the frame's title region.
1131 * @param {boolean} [attributes.multiple=add] Whether multi-select is enabled. @todo 'add' doesn't seem do anything special, and gets used as a boolean.
1132 * @param {wp.media.model.Attachments} [attributes.library] The attachments collection to browse.
1133 * If one is not supplied, a collection of all images will be created.
1134 * @param {boolean|string} [attributes.filterable=uploaded] Whether the library is filterable, and if so what filters should be shown.
1135 * Accepts 'all', 'uploaded', or 'unattached'.
1136 * @param {string} [attributes.menu=gallery] Initial mode for the menu region.
1137 * @param {string} [attributes.content=upload] Initial mode for the content region.
1138 * Overridden by persistent user setting if 'contentUserSetting' is true.
1139 * @param {string} [attributes.router=browse] Initial mode for the router region.
1140 * @param {string} [attributes.toolbar=gallery-add] Initial mode for the toolbar region.
1141 * @param {boolean} [attributes.searchable=true] Whether the library is searchable.
1142 * @param {boolean} [attributes.sortable=true] Whether the Attachments should be sortable. Depends on the orderby property being set to menuOrder on the attachments collection.
1143 * @param {boolean} [attributes.autoSelect=true] Whether an uploaded attachment should be automatically added to the selection.
1144 * @param {boolean} [attributes.contentUserSetting=true] Whether the content region's mode should be set and persisted per user.
1145 * @param {int} [attributes.priority=100] The priority for the state link in the media menu.
1146 * @param {boolean} [attributes.syncSelection=false] Whether the Attachments selection should be persisted from the last state.
1147 * Defaults to false because for this state, because the library of the Edit Gallery state is the selection.
1149 media.controller.GalleryAdd = media.controller.Library.extend({
1150 defaults: _.defaults({
1151 id: 'gallery-library',
1152 title: l10n.addToGalleryTitle,
1154 filterable: 'uploaded',
1156 toolbar: 'gallery-add',
1158 syncSelection: false
1159 }, media.controller.Library.prototype.defaults ),
1164 initialize: function() {
1165 // If a library wasn't supplied, create a library of images.
1166 if ( ! this.get('library') )
1167 this.set( 'library', media.query({ type: 'image' }) );
1169 media.controller.Library.prototype.initialize.apply( this, arguments );
1175 activate: function() {
1176 var library = this.get('library'),
1177 edit = this.frame.state('gallery-edit').get('library');
1179 if ( this.editLibrary && this.editLibrary !== edit )
1180 library.unobserve( this.editLibrary );
1182 // Accepts attachments that exist in the original library and
1183 // that do not exist in gallery's library.
1184 library.validator = function( attachment ) {
1185 return !! this.mirroring.get( attachment.cid ) && ! edit.get( attachment.cid ) && media.model.Selection.prototype.validator.apply( this, arguments );
1188 // Reset the library to ensure that all attachments are re-added
1189 // to the collection. Do so silently, as calling `observe` will
1190 // trigger the `reset` event.
1191 library.reset( library.mirroring.models, { silent: true });
1192 library.observe( edit );
1193 this.editLibrary = edit;
1195 media.controller.Library.prototype.activate.apply( this, arguments );
1200 * wp.media.controller.CollectionEdit
1202 * A state for editing a collection, which is used by audio and video playlists,
1203 * and can be used for other collections.
1206 * @augments wp.media.controller.Library
1207 * @augments wp.media.controller.State
1208 * @augments Backbone.Model
1210 * @param {object} [attributes] The attributes hash passed to the state.
1211 * @param {string} attributes.title Title for the state. Displays in the media menu and the frame's title region.
1212 * @param {wp.media.model.Attachments} [attributes.library] The attachments collection to edit.
1213 * If one is not supplied, an empty media.model.Selection collection is created.
1214 * @param {boolean} [attributes.multiple=false] Whether multi-select is enabled.
1215 * @param {string} [attributes.content=browse] Initial mode for the content region.
1216 * @param {string} attributes.menu Initial mode for the menu region. @todo this needs a better explanation.
1217 * @param {boolean} [attributes.searchable=false] Whether the library is searchable.
1218 * @param {boolean} [attributes.sortable=true] Whether the Attachments should be sortable. Depends on the orderby property being set to menuOrder on the attachments collection.
1219 * @param {boolean} [attributes.describe=true] Whether to offer UI to describe the attachments - e.g. captioning images in a gallery.
1220 * @param {boolean} [attributes.dragInfo=true] Whether to show instructional text about the attachments being sortable.
1221 * @param {boolean} [attributes.dragInfoText] Instructional text about the attachments being sortable.
1222 * @param {int} [attributes.idealColumnWidth=170] The ideal column width in pixels for attachments.
1223 * @param {boolean} [attributes.editing=false] Whether the gallery is being created, or editing an existing instance.
1224 * @param {int} [attributes.priority=60] The priority for the state link in the media menu.
1225 * @param {boolean} [attributes.syncSelection=false] Whether the Attachments selection should be persisted from the last state.
1226 * Defaults to false for this state, because the library passed in *is* the selection.
1227 * @param {view} [attributes.SettingsView] The view to edit the collection instance settings (e.g. Playlist settings with "Show tracklist" checkbox).
1228 * @param {view} [attributes.AttachmentView] The single `Attachment` view to be used in the `Attachments`.
1229 * If none supplied, defaults to wp.media.view.Attachment.EditLibrary.
1230 * @param {string} attributes.type The collection's media type. (e.g. 'video').
1231 * @param {string} attributes.collectionType The collection type. (e.g. 'playlist').
1233 media.controller.CollectionEdit = media.controller.Library.extend({
1241 idealColumnWidth: 170,
1244 SettingsView: false,
1245 syncSelection: false
1251 initialize: function() {
1252 var collectionType = this.get('collectionType');
1254 if ( 'video' === this.get( 'type' ) ) {
1255 collectionType = 'video-' + collectionType;
1258 this.set( 'id', collectionType + '-edit' );
1259 this.set( 'toolbar', collectionType + '-edit' );
1261 // If we haven't been provided a `library`, create a `Selection`.
1262 if ( ! this.get('library') ) {
1263 this.set( 'library', new media.model.Selection() );
1265 // The single `Attachment` view to be used in the `Attachments` view.
1266 if ( ! this.get('AttachmentView') ) {
1267 this.set( 'AttachmentView', media.view.Attachment.EditLibrary );
1269 media.controller.Library.prototype.initialize.apply( this, arguments );
1275 activate: function() {
1276 var library = this.get('library');
1278 // Limit the library to images only.
1279 library.props.set( 'type', this.get( 'type' ) );
1281 // Watch for uploaded attachments.
1282 this.get('library').observe( wp.Uploader.queue );
1284 this.frame.on( 'content:render:browse', this.renderSettings, this );
1286 media.controller.Library.prototype.activate.apply( this, arguments );
1292 deactivate: function() {
1293 // Stop watching for uploaded attachments.
1294 this.get('library').unobserve( wp.Uploader.queue );
1296 this.frame.off( 'content:render:browse', this.renderSettings, this );
1298 media.controller.Library.prototype.deactivate.apply( this, arguments );
1302 * Render the collection embed settings view in the browser sidebar.
1304 * @todo This is against the pattern elsewhere in media. Typically the frame
1305 * is responsible for adding region mode callbacks. Explain.
1309 * @param {wp.media.view.attachmentsBrowser} The attachments browser view.
1311 renderSettings: function( attachmentsBrowserView ) {
1312 var library = this.get('library'),
1313 collectionType = this.get('collectionType'),
1314 dragInfoText = this.get('dragInfoText'),
1315 SettingsView = this.get('SettingsView'),
1318 if ( ! library || ! attachmentsBrowserView ) {
1322 library[ collectionType ] = library[ collectionType ] || new Backbone.Model();
1324 obj[ collectionType ] = new SettingsView({
1326 model: library[ collectionType ],
1330 attachmentsBrowserView.sidebar.set( obj );
1332 if ( dragInfoText ) {
1333 attachmentsBrowserView.toolbar.set( 'dragInfo', new media.View({
1334 el: $( '<div class="instructions">' + dragInfoText + '</div>' )[0],
1339 // Add the 'Reverse order' button to the toolbar.
1340 attachmentsBrowserView.toolbar.set( 'reverse', {
1341 text: l10n.reverseOrder,
1345 library.reset( library.toArray().reverse() );
1352 * wp.media.controller.CollectionAdd
1354 * A state for adding attachments to a collection (e.g. video playlist).
1357 * @augments wp.media.controller.Library
1358 * @augments wp.media.controller.State
1359 * @augments Backbone.Model
1361 * @param {object} [attributes] The attributes hash passed to the state.
1362 * @param {string} [attributes.id=library] Unique identifier.
1363 * @param {string} attributes.title Title for the state. Displays in the frame's title region.
1364 * @param {boolean} [attributes.multiple=add] Whether multi-select is enabled. @todo 'add' doesn't seem do anything special, and gets used as a boolean.
1365 * @param {wp.media.model.Attachments} [attributes.library] The attachments collection to browse.
1366 * If one is not supplied, a collection of attachments of the specified type will be created.
1367 * @param {boolean|string} [attributes.filterable=uploaded] Whether the library is filterable, and if so what filters should be shown.
1368 * Accepts 'all', 'uploaded', or 'unattached'.
1369 * @param {string} [attributes.menu=gallery] Initial mode for the menu region.
1370 * @param {string} [attributes.content=upload] Initial mode for the content region.
1371 * Overridden by persistent user setting if 'contentUserSetting' is true.
1372 * @param {string} [attributes.router=browse] Initial mode for the router region.
1373 * @param {string} [attributes.toolbar=gallery-add] Initial mode for the toolbar region.
1374 * @param {boolean} [attributes.searchable=true] Whether the library is searchable.
1375 * @param {boolean} [attributes.sortable=true] Whether the Attachments should be sortable. Depends on the orderby property being set to menuOrder on the attachments collection.
1376 * @param {boolean} [attributes.autoSelect=true] Whether an uploaded attachment should be automatically added to the selection.
1377 * @param {boolean} [attributes.contentUserSetting=true] Whether the content region's mode should be set and persisted per user.
1378 * @param {int} [attributes.priority=100] The priority for the state link in the media menu.
1379 * @param {boolean} [attributes.syncSelection=false] Whether the Attachments selection should be persisted from the last state.
1380 * Defaults to false because for this state, because the library of the Edit Gallery state is the selection.
1381 * @param {string} attributes.type The collection's media type. (e.g. 'video').
1382 * @param {string} attributes.collectionType The collection type. (e.g. 'playlist').
1384 media.controller.CollectionAdd = media.controller.Library.extend({
1385 defaults: _.defaults( {
1386 // Selection defaults. @see media.model.Selection
1388 // Attachments browser defaults. @see media.view.AttachmentsBrowser
1389 filterable: 'uploaded',
1392 syncSelection: false
1393 }, media.controller.Library.prototype.defaults ),
1398 initialize: function() {
1399 var collectionType = this.get('collectionType');
1401 if ( 'video' === this.get( 'type' ) ) {
1402 collectionType = 'video-' + collectionType;
1405 this.set( 'id', collectionType + '-library' );
1406 this.set( 'toolbar', collectionType + '-add' );
1407 this.set( 'menu', collectionType );
1409 // If we haven't been provided a `library`, create a `Selection`.
1410 if ( ! this.get('library') ) {
1411 this.set( 'library', media.query({ type: this.get('type') }) );
1413 media.controller.Library.prototype.initialize.apply( this, arguments );
1419 activate: function() {
1420 var library = this.get('library'),
1421 editLibrary = this.get('editLibrary'),
1422 edit = this.frame.state( this.get('collectionType') + '-edit' ).get('library');
1424 if ( editLibrary && editLibrary !== edit ) {
1425 library.unobserve( editLibrary );
1428 // Accepts attachments that exist in the original library and
1429 // that do not exist in gallery's library.
1430 library.validator = function( attachment ) {
1431 return !! this.mirroring.get( attachment.cid ) && ! edit.get( attachment.cid ) && media.model.Selection.prototype.validator.apply( this, arguments );
1434 // Reset the library to ensure that all attachments are re-added
1435 // to the collection. Do so silently, as calling `observe` will
1436 // trigger the `reset` event.
1437 library.reset( library.mirroring.models, { silent: true });
1438 library.observe( edit );
1439 this.set('editLibrary', edit);
1441 media.controller.Library.prototype.activate.apply( this, arguments );
1446 * wp.media.controller.FeaturedImage
1448 * A state for selecting a featured image for a post.
1451 * @augments wp.media.controller.Library
1452 * @augments wp.media.controller.State
1453 * @augments Backbone.Model
1455 * @param {object} [attributes] The attributes hash passed to the state.
1456 * @param {string} [attributes.id=featured-image] Unique identifier.
1457 * @param {string} [attributes.title=Set Featured Image] Title for the state. Displays in the media menu and the frame's title region.
1458 * @param {wp.media.model.Attachments} [attributes.library] The attachments collection to browse.
1459 * If one is not supplied, a collection of all images will be created.
1460 * @param {boolean} [attributes.multiple=false] Whether multi-select is enabled.
1461 * @param {string} [attributes.content=upload] Initial mode for the content region.
1462 * Overridden by persistent user setting if 'contentUserSetting' is true.
1463 * @param {string} [attributes.menu=default] Initial mode for the menu region.
1464 * @param {string} [attributes.router=browse] Initial mode for the router region.
1465 * @param {string} [attributes.toolbar=featured-image] Initial mode for the toolbar region.
1466 * @param {int} [attributes.priority=60] The priority for the state link in the media menu.
1467 * @param {boolean} [attributes.searchable=true] Whether the library is searchable.
1468 * @param {boolean|string} [attributes.filterable=false] Whether the library is filterable, and if so what filters should be shown.
1469 * Accepts 'all', 'uploaded', or 'unattached'.
1470 * @param {boolean} [attributes.sortable=true] Whether the Attachments should be sortable. Depends on the orderby property being set to menuOrder on the attachments collection.
1471 * @param {boolean} [attributes.autoSelect=true] Whether an uploaded attachment should be automatically added to the selection.
1472 * @param {boolean} [attributes.describe=false] Whether to offer UI to describe attachments - e.g. captioning images in a gallery.
1473 * @param {boolean} [attributes.contentUserSetting=true] Whether the content region's mode should be set and persisted per user.
1474 * @param {boolean} [attributes.syncSelection=true] Whether the Attachments selection should be persisted from the last state.
1476 media.controller.FeaturedImage = media.controller.Library.extend({
1477 defaults: _.defaults({
1478 id: 'featured-image',
1479 title: l10n.setFeaturedImageTitle,
1481 filterable: 'uploaded',
1482 toolbar: 'featured-image',
1485 }, media.controller.Library.prototype.defaults ),
1490 initialize: function() {
1491 var library, comparator;
1493 // If we haven't been provided a `library`, create a `Selection`.
1494 if ( ! this.get('library') ) {
1495 this.set( 'library', media.query({ type: 'image' }) );
1498 media.controller.Library.prototype.initialize.apply( this, arguments );
1500 library = this.get('library');
1501 comparator = library.comparator;
1503 // Overload the library's comparator to push items that are not in
1504 // the mirrored query to the front of the aggregate collection.
1505 library.comparator = function( a, b ) {
1506 var aInQuery = !! this.mirroring.get( a.cid ),
1507 bInQuery = !! this.mirroring.get( b.cid );
1509 if ( ! aInQuery && bInQuery ) {
1511 } else if ( aInQuery && ! bInQuery ) {
1514 return comparator.apply( this, arguments );
1518 // Add all items in the selection to the library, so any featured
1519 // images that are not initially loaded still appear.
1520 library.observe( this.get('selection') );
1526 activate: function() {
1527 this.updateSelection();
1528 this.frame.on( 'open', this.updateSelection, this );
1530 media.controller.Library.prototype.activate.apply( this, arguments );
1536 deactivate: function() {
1537 this.frame.off( 'open', this.updateSelection, this );
1539 media.controller.Library.prototype.deactivate.apply( this, arguments );
1545 updateSelection: function() {
1546 var selection = this.get('selection'),
1547 id = media.view.settings.post.featuredImageId,
1550 if ( '' !== id && -1 !== id ) {
1551 attachment = media.model.Attachment.get( id );
1555 selection.reset( attachment ? [ attachment ] : [] );
1560 * wp.media.controller.ReplaceImage
1562 * A state for replacing an image.
1565 * @augments wp.media.controller.Library
1566 * @augments wp.media.controller.State
1567 * @augments Backbone.Model
1569 * @param {object} [attributes] The attributes hash passed to the state.
1570 * @param {string} [attributes.id=replace-image] Unique identifier.
1571 * @param {string} [attributes.title=Replace Image] Title for the state. Displays in the media menu and the frame's title region.
1572 * @param {wp.media.model.Attachments} [attributes.library] The attachments collection to browse.
1573 * If one is not supplied, a collection of all images will be created.
1574 * @param {boolean} [attributes.multiple=false] Whether multi-select is enabled.
1575 * @param {string} [attributes.content=upload] Initial mode for the content region.
1576 * Overridden by persistent user setting if 'contentUserSetting' is true.
1577 * @param {string} [attributes.menu=default] Initial mode for the menu region.
1578 * @param {string} [attributes.router=browse] Initial mode for the router region.
1579 * @param {string} [attributes.toolbar=replace] Initial mode for the toolbar region.
1580 * @param {int} [attributes.priority=60] The priority for the state link in the media menu.
1581 * @param {boolean} [attributes.searchable=true] Whether the library is searchable.
1582 * @param {boolean|string} [attributes.filterable=uploaded] Whether the library is filterable, and if so what filters should be shown.
1583 * Accepts 'all', 'uploaded', or 'unattached'.
1584 * @param {boolean} [attributes.sortable=true] Whether the Attachments should be sortable. Depends on the orderby property being set to menuOrder on the attachments collection.
1585 * @param {boolean} [attributes.autoSelect=true] Whether an uploaded attachment should be automatically added to the selection.
1586 * @param {boolean} [attributes.describe=false] Whether to offer UI to describe attachments - e.g. captioning images in a gallery.
1587 * @param {boolean} [attributes.contentUserSetting=true] Whether the content region's mode should be set and persisted per user.
1588 * @param {boolean} [attributes.syncSelection=true] Whether the Attachments selection should be persisted from the last state.
1590 media.controller.ReplaceImage = media.controller.Library.extend({
1591 defaults: _.defaults({
1592 id: 'replace-image',
1593 title: l10n.replaceImageTitle,
1595 filterable: 'uploaded',
1600 }, media.controller.Library.prototype.defaults ),
1607 initialize: function( options ) {
1608 var library, comparator;
1610 this.image = options.image;
1611 // If we haven't been provided a `library`, create a `Selection`.
1612 if ( ! this.get('library') ) {
1613 this.set( 'library', media.query({ type: 'image' }) );
1616 media.controller.Library.prototype.initialize.apply( this, arguments );
1618 library = this.get('library');
1619 comparator = library.comparator;
1621 // Overload the library's comparator to push items that are not in
1622 // the mirrored query to the front of the aggregate collection.
1623 library.comparator = function( a, b ) {
1624 var aInQuery = !! this.mirroring.get( a.cid ),
1625 bInQuery = !! this.mirroring.get( b.cid );
1627 if ( ! aInQuery && bInQuery ) {
1629 } else if ( aInQuery && ! bInQuery ) {
1632 return comparator.apply( this, arguments );
1636 // Add all items in the selection to the library, so any featured
1637 // images that are not initially loaded still appear.
1638 library.observe( this.get('selection') );
1644 activate: function() {
1645 this.updateSelection();
1646 media.controller.Library.prototype.activate.apply( this, arguments );
1652 updateSelection: function() {
1653 var selection = this.get('selection'),
1654 attachment = this.image.attachment;
1656 selection.reset( attachment ? [ attachment ] : [] );
1661 * wp.media.controller.EditImage
1663 * A state for editing (cropping, etc.) an image.
1666 * @augments wp.media.controller.State
1667 * @augments Backbone.Model
1669 * @param {object} attributes The attributes hash passed to the state.
1670 * @param {wp.media.model.Attachment} attributes.model The attachment.
1671 * @param {string} [attributes.id=edit-image] Unique identifier.
1672 * @param {string} [attributes.title=Edit Image] Title for the state. Displays in the media menu and the frame's title region.
1673 * @param {string} [attributes.content=edit-image] Initial mode for the content region.
1674 * @param {string} [attributes.toolbar=edit-image] Initial mode for the toolbar region.
1675 * @param {string} [attributes.menu=false] Initial mode for the menu region.
1676 * @param {string} [attributes.url] Unused. @todo Consider removal.
1678 media.controller.EditImage = media.controller.State.extend({
1681 title: l10n.editImage,
1683 toolbar: 'edit-image',
1684 content: 'edit-image',
1691 activate: function() {
1692 this.listenTo( this.frame, 'toolbar:render:edit-image', this.toolbar );
1698 deactivate: function() {
1699 this.stopListening( this.frame );
1705 toolbar: function() {
1706 var frame = this.frame,
1707 lastState = frame.lastState(),
1708 previous = lastState && lastState.id;
1710 frame.toolbar.set( new media.view.Toolbar({
1719 frame.setState( previous );
1731 * wp.media.controller.MediaLibrary
1734 * @augments wp.media.controller.Library
1735 * @augments wp.media.controller.State
1736 * @augments Backbone.Model
1738 media.controller.MediaLibrary = media.controller.Library.extend({
1739 defaults: _.defaults({
1740 // Attachments browser defaults. @see media.view.AttachmentsBrowser
1741 filterable: 'uploaded',
1743 displaySettings: false,
1745 syncSelection: false
1746 }, media.controller.Library.prototype.defaults ),
1753 initialize: function( options ) {
1754 this.media = options.media;
1755 this.type = options.type;
1756 this.set( 'library', media.query({ type: this.type }) );
1758 media.controller.Library.prototype.initialize.apply( this, arguments );
1764 activate: function() {
1765 // @todo this should use this.frame.
1766 if ( media.frame.lastMime ) {
1767 this.set( 'library', media.query({ type: media.frame.lastMime }) );
1768 delete media.frame.lastMime;
1770 media.controller.Library.prototype.activate.apply( this, arguments );
1775 * wp.media.controller.Embed
1777 * A state for embedding media from a URL.
1780 * @augments wp.media.controller.State
1781 * @augments Backbone.Model
1783 * @param {object} attributes The attributes hash passed to the state.
1784 * @param {string} [attributes.id=embed] Unique identifier.
1785 * @param {string} [attributes.title=Insert From URL] Title for the state. Displays in the media menu and the frame's title region.
1786 * @param {string} [attributes.content=embed] Initial mode for the content region.
1787 * @param {string} [attributes.menu=default] Initial mode for the menu region.
1788 * @param {string} [attributes.toolbar=main-embed] Initial mode for the toolbar region.
1789 * @param {string} [attributes.menu=false] Initial mode for the menu region.
1790 * @param {int} [attributes.priority=120] The priority for the state link in the media menu.
1791 * @param {string} [attributes.type=link] The type of embed. Currently only link is supported.
1792 * @param {string} [attributes.url] The embed URL.
1793 * @param {object} [attributes.metadata={}] Properties of the embed, which will override attributes.url if set.
1795 media.controller.Embed = media.controller.State.extend({
1798 title: l10n.insertFromUrlTitle,
1801 toolbar: 'main-embed',
1808 // The amount of time used when debouncing the scan.
1811 initialize: function(options) {
1812 this.metadata = options.metadata;
1813 this.debouncedScan = _.debounce( _.bind( this.scan, this ), this.sensitivity );
1814 this.props = new Backbone.Model( this.metadata || { url: '' });
1815 this.props.on( 'change:url', this.debouncedScan, this );
1816 this.props.on( 'change:url', this.refresh, this );
1817 this.on( 'scan', this.scanImage, this );
1821 * Trigger a scan of the embedded URL's content for metadata required to embed.
1823 * @fires wp.media.controller.Embed#scan
1833 // Scan is triggered with the list of `attributes` to set on the
1834 // state, useful for the 'type' attribute and 'scanners' attribute,
1835 // an array of promise objects for asynchronous scan operations.
1836 if ( this.props.get('url') ) {
1837 this.trigger( 'scan', attributes );
1840 if ( attributes.scanners.length ) {
1841 scanners = attributes.scanners = $.when.apply( $, attributes.scanners );
1842 scanners.always( function() {
1843 if ( embed.get('scanners') === scanners ) {
1844 embed.set( 'loading', false );
1848 attributes.scanners = null;
1851 attributes.loading = !! attributes.scanners;
1852 this.set( attributes );
1855 * Try scanning the embed as an image to discover its dimensions.
1857 * @param {Object} attributes
1859 scanImage: function( attributes ) {
1860 var frame = this.frame,
1862 url = this.props.get('url'),
1863 image = new Image(),
1864 deferred = $.Deferred();
1866 attributes.scanners.push( deferred.promise() );
1868 // Try to load the image and find its width/height.
1869 image.onload = function() {
1872 if ( state !== frame.state() || url !== state.props.get('url') ) {
1882 height: image.height
1886 image.onerror = deferred.reject;
1890 refresh: function() {
1891 this.frame.toolbar.get().refresh();
1895 this.props.clear().set({ url: '' });
1897 if ( this.active ) {
1904 * wp.media.controller.Cropper
1906 * A state for cropping an image.
1909 * @augments wp.media.controller.State
1910 * @augments Backbone.Model
1912 media.controller.Cropper = media.controller.State.extend({
1915 title: l10n.cropImage,
1916 // Region mode defaults.
1924 activate: function() {
1925 this.frame.on( 'content:create:crop', this.createCropContent, this );
1926 this.frame.on( 'close', this.removeCropper, this );
1927 this.set('selection', new Backbone.Collection(this.frame._selection.single));
1930 deactivate: function() {
1931 this.frame.toolbar.mode('browse');
1934 createCropContent: function() {
1935 this.cropperView = new wp.media.view.Cropper({controller: this,
1936 attachment: this.get('selection').first() });
1937 this.cropperView.on('image-loaded', this.createCropToolbar, this);
1938 this.frame.content.set(this.cropperView);
1941 removeCropper: function() {
1942 this.imgSelect.cancelSelection();
1943 this.imgSelect.setOptions({remove: true});
1944 this.imgSelect.update();
1945 this.cropperView.remove();
1947 createCropToolbar: function() {
1948 var canSkipCrop, toolbarOptions;
1950 canSkipCrop = this.get('canSkipCrop') || false;
1953 controller: this.frame,
1957 text: l10n.cropImage,
1959 requires: { library: false, selection: false },
1963 selection = this.controller.state().get('selection').first();
1965 selection.set({cropDetails: this.controller.state().imgSelect.getSelection()});
1967 this.$el.text(l10n.cropping);
1968 this.$el.attr('disabled', true);
1969 this.controller.state().doCrop( selection ).done( function( croppedImage ) {
1970 self.controller.trigger('cropped', croppedImage );
1971 self.controller.close();
1972 }).fail( function() {
1973 self.controller.trigger('content:error:crop');
1980 if ( canSkipCrop ) {
1981 _.extend( toolbarOptions.items, {
1984 text: l10n.skipCropping,
1986 requires: { library: false, selection: false },
1988 var selection = this.controller.state().get('selection').first();
1989 this.controller.state().cropperView.remove();
1990 this.controller.trigger('skippedcrop', selection);
1991 this.controller.close();
1997 this.frame.toolbar.set( new wp.media.view.Toolbar(toolbarOptions) );
2000 doCrop: function( attachment ) {
2001 return wp.ajax.post( 'custom-header-crop', {
2002 nonce: attachment.get('nonces').edit,
2003 id: attachment.get('id'),
2004 cropDetails: attachment.get('cropDetails')
2012 * The base view class for media.
2014 * Undelegating events, removing events from the model, and
2015 * removing events from the controller mirror the code for
2016 * `Backbone.View.dispose` in Backbone 0.9.8 development.
2018 * This behavior has since been removed, and should not be used
2019 * outside of the media manager.
2022 * @augments wp.Backbone.View
2023 * @augments Backbone.View
2025 media.View = wp.Backbone.View.extend({
2026 constructor: function( options ) {
2027 if ( options && options.controller ) {
2028 this.controller = options.controller;
2030 wp.Backbone.View.apply( this, arguments );
2033 * @todo The internal comment mentions this might have been a stop-gap
2034 * before Backbone 0.9.8 came out. Figure out if Backbone core takes
2035 * care of this in Backbone.View now.
2037 * @returns {wp.media.View} Returns itself to allow chaining
2039 dispose: function() {
2040 // Undelegating events, removing events from the model, and
2041 // removing events from the controller mirror the code for
2042 // `Backbone.View.dispose` in Backbone 0.9.8 development.
2043 this.undelegateEvents();
2045 if ( this.model && this.model.off ) {
2046 this.model.off( null, null, this );
2049 if ( this.collection && this.collection.off ) {
2050 this.collection.off( null, null, this );
2053 // Unbind controller events.
2054 if ( this.controller && this.controller.off ) {
2055 this.controller.off( null, null, this );
2061 * @returns {wp.media.View} Returns itself to allow chaining
2063 remove: function() {
2066 * call 'remove' directly on the parent class
2068 return wp.Backbone.View.prototype.remove.apply( this, arguments );
2073 * wp.media.view.Frame
2075 * A frame is a composite view consisting of one or more regions and one or more
2078 * @see wp.media.controller.State
2079 * @see wp.media.controller.Region
2082 * @augments wp.media.View
2083 * @augments wp.Backbone.View
2084 * @augments Backbone.View
2085 * @mixes wp.media.controller.StateMachine
2087 media.view.Frame = media.View.extend({
2088 initialize: function() {
2089 _.defaults( this.options, {
2092 this._createRegions();
2093 this._createStates();
2094 this._createModes();
2097 _createRegions: function() {
2098 // Clone the regions array.
2099 this.regions = this.regions ? this.regions.slice() : [];
2101 // Initialize regions.
2102 _.each( this.regions, function( region ) {
2103 this[ region ] = new media.controller.Region({
2106 selector: '.media-frame-' + region
2111 * Create the frame's states.
2113 * @see wp.media.controller.State
2114 * @see wp.media.controller.StateMachine
2116 * @fires wp.media.controller.State#ready
2118 _createStates: function() {
2119 // Create the default `states` collection.
2120 this.states = new Backbone.Collection( null, {
2121 model: media.controller.State
2124 // Ensure states have a reference to the frame.
2125 this.states.on( 'add', function( model ) {
2127 model.trigger('ready');
2130 if ( this.options.states ) {
2131 this.states.add( this.options.states );
2136 * A frame can be in a mode or multiple modes at one time.
2138 * For example, the manage media frame can be in the `Bulk Select` or `Edit` mode.
2140 _createModes: function() {
2141 // Store active "modes" that the frame is in. Unrelated to region modes.
2142 this.activeModes = new Backbone.Collection();
2143 this.activeModes.on( 'add remove reset', _.bind( this.triggerModeEvents, this ) );
2145 _.each( this.options.mode, function( mode ) {
2146 this.activateMode( mode );
2150 * Reset all states on the frame to their defaults.
2152 * @returns {wp.media.view.Frame} Returns itself to allow chaining
2155 this.states.invoke( 'trigger', 'reset' );
2159 * Map activeMode collection events to the frame.
2161 triggerModeEvents: function( model, collection, options ) {
2162 var collectionEvent,
2165 remove: 'deactivate'
2168 // Probably a better way to do this.
2169 _.each( options, function( value, key ) {
2171 collectionEvent = key;
2175 if ( ! _.has( modeEventMap, collectionEvent ) ) {
2179 eventToTrigger = model.get('id') + ':' + modeEventMap[collectionEvent];
2180 this.trigger( eventToTrigger );
2183 * Activate a mode on the frame.
2185 * @param string mode Mode ID.
2186 * @returns {this} Returns itself to allow chaining.
2188 activateMode: function( mode ) {
2189 // Bail if the mode is already active.
2190 if ( this.isModeActive( mode ) ) {
2193 this.activeModes.add( [ { id: mode } ] );
2194 // Add a CSS class to the frame so elements can be styled for the mode.
2195 this.$el.addClass( 'mode-' + mode );
2200 * Deactivate a mode on the frame.
2202 * @param string mode Mode ID.
2203 * @returns {this} Returns itself to allow chaining.
2205 deactivateMode: function( mode ) {
2206 // Bail if the mode isn't active.
2207 if ( ! this.isModeActive( mode ) ) {
2210 this.activeModes.remove( this.activeModes.where( { id: mode } ) );
2211 this.$el.removeClass( 'mode-' + mode );
2213 * Frame mode deactivation event.
2215 * @event this#{mode}:deactivate
2217 this.trigger( mode + ':deactivate' );
2222 * Check if a mode is enabled on the frame.
2224 * @param string mode Mode ID.
2227 isModeActive: function( mode ) {
2228 return Boolean( this.activeModes.where( { id: mode } ).length );
2232 // Make the `Frame` a `StateMachine`.
2233 _.extend( media.view.Frame.prototype, media.controller.StateMachine.prototype );
2236 * wp.media.view.MediaFrame
2238 * The frame used to create the media modal.
2241 * @augments wp.media.view.Frame
2242 * @augments wp.media.View
2243 * @augments wp.Backbone.View
2244 * @augments Backbone.View
2245 * @mixes wp.media.controller.StateMachine
2247 media.view.MediaFrame = media.view.Frame.extend({
2248 className: 'media-frame',
2249 template: media.template('media-frame'),
2250 regions: ['menu','title','content','toolbar','router'],
2253 'click div.media-frame-title h1': 'toggleMenu'
2257 * @global wp.Uploader
2259 initialize: function() {
2260 media.view.Frame.prototype.initialize.apply( this, arguments );
2262 _.defaults( this.options, {
2268 // Ensure core UI is enabled.
2269 this.$el.addClass('wp-core-ui');
2271 // Initialize modal container view.
2272 if ( this.options.modal ) {
2273 this.modal = new media.view.Modal({
2275 title: this.options.title
2278 this.modal.content( this );
2281 // Force the uploader off if the upload limit has been exceeded or
2282 // if the browser isn't supported.
2283 if ( wp.Uploader.limitExceeded || ! wp.Uploader.browser.supported ) {
2284 this.options.uploader = false;
2287 // Initialize window-wide uploader.
2288 if ( this.options.uploader ) {
2289 this.uploader = new media.view.UploaderWindow({
2292 dropzone: this.modal ? this.modal.$el : this.$el,
2296 this.views.set( '.media-frame-uploader', this.uploader );
2299 this.on( 'attach', _.bind( this.views.ready, this.views ), this );
2301 // Bind default title creation.
2302 this.on( 'title:create:default', this.createTitle, this );
2303 this.title.mode('default');
2305 this.on( 'title:render', function( view ) {
2306 view.$el.append( '<span class="dashicons dashicons-arrow-down"></span>' );
2309 // Bind default menu.
2310 this.on( 'menu:create:default', this.createMenu, this );
2313 * @returns {wp.media.view.MediaFrame} Returns itself to allow chaining
2315 render: function() {
2316 // Activate the default state if no active state exists.
2317 if ( ! this.state() && this.options.state ) {
2318 this.setState( this.options.state );
2321 * call 'render' directly on the parent class
2323 return media.view.Frame.prototype.render.apply( this, arguments );
2326 * @param {Object} title
2327 * @this wp.media.controller.Region
2329 createTitle: function( title ) {
2330 title.view = new media.View({
2336 * @param {Object} menu
2337 * @this wp.media.controller.Region
2339 createMenu: function( menu ) {
2340 menu.view = new media.view.Menu({
2345 toggleMenu: function() {
2346 this.$el.find( '.media-menu' ).toggleClass( 'visible' );
2350 * @param {Object} toolbar
2351 * @this wp.media.controller.Region
2353 createToolbar: function( toolbar ) {
2354 toolbar.view = new media.view.Toolbar({
2359 * @param {Object} router
2360 * @this wp.media.controller.Region
2362 createRouter: function( router ) {
2363 router.view = new media.view.Router({
2368 * @param {Object} options
2370 createIframeStates: function( options ) {
2371 var settings = media.view.settings,
2372 tabs = settings.tabs,
2373 tabUrl = settings.tabUrl,
2376 if ( ! tabs || ! tabUrl ) {
2380 // Add the post ID to the tab URL if it exists.
2381 $postId = $('#post_ID');
2382 if ( $postId.length ) {
2383 tabUrl += '&post_id=' + $postId.val();
2386 // Generate the tab states.
2387 _.each( tabs, function( title, id ) {
2388 this.state( 'iframe:' + id ).set( _.defaults({
2390 src: tabUrl + '&tab=' + id,
2397 this.on( 'content:create:iframe', this.iframeContent, this );
2398 this.on( 'content:deactivate:iframe', this.iframeContentCleanup, this );
2399 this.on( 'menu:render:default', this.iframeMenu, this );
2400 this.on( 'open', this.hijackThickbox, this );
2401 this.on( 'close', this.restoreThickbox, this );
2405 * @param {Object} content
2406 * @this wp.media.controller.Region
2408 iframeContent: function( content ) {
2409 this.$el.addClass('hide-toolbar');
2410 content.view = new media.view.Iframe({
2415 iframeContentCleanup: function() {
2416 this.$el.removeClass('hide-toolbar');
2419 iframeMenu: function( view ) {
2426 _.each( media.view.settings.tabs, function( title, id ) {
2427 views[ 'iframe:' + id ] = {
2428 text: this.state( 'iframe:' + id ).get('title'),
2436 hijackThickbox: function() {
2439 if ( ! window.tb_remove || this._tb_remove ) {
2443 this._tb_remove = window.tb_remove;
2444 window.tb_remove = function() {
2447 frame.setState( frame.options.state );
2448 frame._tb_remove.call( window );
2452 restoreThickbox: function() {
2453 if ( ! this._tb_remove ) {
2457 window.tb_remove = this._tb_remove;
2458 delete this._tb_remove;
2462 // Map some of the modal's methods to the frame.
2463 _.each(['open','close','attach','detach','escape'], function( method ) {
2465 * @returns {wp.media.view.MediaFrame} Returns itself to allow chaining
2467 media.view.MediaFrame.prototype[ method ] = function() {
2469 this.modal[ method ].apply( this.modal, arguments );
2476 * wp.media.view.MediaFrame.Select
2478 * A frame for selecting an item or items from the media library.
2481 * @augments wp.media.view.MediaFrame
2482 * @augments wp.media.view.Frame
2483 * @augments wp.media.View
2484 * @augments wp.Backbone.View
2485 * @augments Backbone.View
2486 * @mixes wp.media.controller.StateMachine
2488 media.view.MediaFrame.Select = media.view.MediaFrame.extend({
2489 initialize: function() {
2490 // Call 'initialize' directly on the parent class.
2491 media.view.MediaFrame.prototype.initialize.apply( this, arguments );
2493 _.defaults( this.options, {
2500 this.createSelection();
2501 this.createStates();
2502 this.bindHandlers();
2506 * Attach a selection collection to the frame.
2508 * A selection is a collection of attachments used for a specific purpose
2509 * by a media frame. e.g. Selecting an attachment (or many) to insert into
2512 * @see media.model.Selection
2514 createSelection: function() {
2515 var selection = this.options.selection;
2517 if ( ! (selection instanceof media.model.Selection) ) {
2518 this.options.selection = new media.model.Selection( selection, {
2519 multiple: this.options.multiple
2524 attachments: new media.model.Attachments(),
2530 * Create the default states on the frame.
2532 createStates: function() {
2533 var options = this.options;
2535 if ( this.options.states ) {
2539 // Add the default states.
2542 new media.controller.Library({
2543 library: media.query( options.library ),
2544 multiple: options.multiple,
2545 title: options.title,
2552 * Bind region mode event callbacks.
2554 * @see media.controller.Region.render
2556 bindHandlers: function() {
2557 this.on( 'router:create:browse', this.createRouter, this );
2558 this.on( 'router:render:browse', this.browseRouter, this );
2559 this.on( 'content:create:browse', this.browseContent, this );
2560 this.on( 'content:render:upload', this.uploadContent, this );
2561 this.on( 'toolbar:create:select', this.createSelectToolbar, this );
2565 * Render callback for the router region in the `browse` mode.
2567 * @param {wp.media.view.Router} routerView
2569 browseRouter: function( routerView ) {
2572 text: l10n.uploadFilesTitle,
2576 text: l10n.mediaLibraryTitle,
2583 * Render callback for the content region in the `browse` mode.
2585 * @param {wp.media.controller.Region} contentRegion
2587 browseContent: function( contentRegion ) {
2588 var state = this.state();
2590 this.$el.removeClass('hide-toolbar');
2592 // Browse our library of attachments.
2593 contentRegion.view = new media.view.AttachmentsBrowser({
2595 collection: state.get('library'),
2596 selection: state.get('selection'),
2598 sortable: state.get('sortable'),
2599 search: state.get('searchable'),
2600 filters: state.get('filterable'),
2601 date: state.get('date'),
2602 display: state.has('display') ? state.get('display') : state.get('displaySettings'),
2603 dragInfo: state.get('dragInfo'),
2605 idealColumnWidth: state.get('idealColumnWidth'),
2606 suggestedWidth: state.get('suggestedWidth'),
2607 suggestedHeight: state.get('suggestedHeight'),
2609 AttachmentView: state.get('AttachmentView')
2614 * Render callback for the content region in the `upload` mode.
2616 uploadContent: function() {
2617 this.$el.removeClass( 'hide-toolbar' );
2618 this.content.set( new media.view.UploaderInline({
2626 * @param {Object} toolbar
2627 * @param {Object} [options={}]
2628 * @this wp.media.controller.Region
2630 createSelectToolbar: function( toolbar, options ) {
2631 options = options || this.options.button || {};
2632 options.controller = this;
2634 toolbar.view = new media.view.Toolbar.Select( options );
2639 * wp.media.view.MediaFrame.Post
2641 * The frame for manipulating media on the Edit Post page.
2644 * @augments wp.media.view.MediaFrame.Select
2645 * @augments wp.media.view.MediaFrame
2646 * @augments wp.media.view.Frame
2647 * @augments wp.media.View
2648 * @augments wp.Backbone.View
2649 * @augments Backbone.View
2650 * @mixes wp.media.controller.StateMachine
2652 media.view.MediaFrame.Post = media.view.MediaFrame.Select.extend({
2653 initialize: function() {
2656 count: media.view.settings.attachmentCounts.audio,
2660 count: media.view.settings.attachmentCounts.video,
2661 state: 'video-playlist'
2665 _.defaults( this.options, {
2672 // Call 'initialize' directly on the parent class.
2673 media.view.MediaFrame.Select.prototype.initialize.apply( this, arguments );
2674 this.createIframeStates();
2679 * Create the default states.
2681 createStates: function() {
2682 var options = this.options;
2686 new media.controller.Library({
2688 title: l10n.insertMediaTitle,
2690 toolbar: 'main-insert',
2692 library: media.query( options.library ),
2693 multiple: options.multiple ? 'reset' : false,
2696 // If the user isn't allowed to edit fields,
2697 // can they still edit it locally?
2698 allowLocalEdits: true,
2700 // Show the attachment display settings.
2701 displaySettings: true,
2702 // Update user settings when users adjust the
2703 // attachment display settings.
2704 displayUserSettings: true
2707 new media.controller.Library({
2709 title: l10n.createGalleryTitle,
2711 toolbar: 'main-gallery',
2712 filterable: 'uploaded',
2716 library: media.query( _.defaults({
2718 }, options.library ) )
2722 new media.controller.Embed( { metadata: options.metadata } ),
2724 new media.controller.EditImage( { model: options.editImage } ),
2727 new media.controller.GalleryEdit({
2728 library: options.selection,
2729 editing: options.editing,
2733 new media.controller.GalleryAdd(),
2735 new media.controller.Library({
2737 title: l10n.createPlaylistTitle,
2739 toolbar: 'main-playlist',
2740 filterable: 'uploaded',
2744 library: media.query( _.defaults({
2746 }, options.library ) )
2750 new media.controller.CollectionEdit({
2752 collectionType: 'playlist',
2753 title: l10n.editPlaylistTitle,
2754 SettingsView: media.view.Settings.Playlist,
2755 library: options.selection,
2756 editing: options.editing,
2758 dragInfoText: l10n.playlistDragInfo,
2762 new media.controller.CollectionAdd({
2764 collectionType: 'playlist',
2765 title: l10n.addToPlaylistTitle
2768 new media.controller.Library({
2769 id: 'video-playlist',
2770 title: l10n.createVideoPlaylistTitle,
2772 toolbar: 'main-video-playlist',
2773 filterable: 'uploaded',
2777 library: media.query( _.defaults({
2779 }, options.library ) )
2782 new media.controller.CollectionEdit({
2784 collectionType: 'playlist',
2785 title: l10n.editVideoPlaylistTitle,
2786 SettingsView: media.view.Settings.Playlist,
2787 library: options.selection,
2788 editing: options.editing,
2789 menu: 'video-playlist',
2790 dragInfoText: l10n.videoPlaylistDragInfo,
2794 new media.controller.CollectionAdd({
2796 collectionType: 'playlist',
2797 title: l10n.addToVideoPlaylistTitle
2801 if ( media.view.settings.post.featuredImageId ) {
2802 this.states.add( new media.controller.FeaturedImage() );
2806 bindHandlers: function() {
2807 var handlers, checkCounts;
2809 media.view.MediaFrame.Select.prototype.bindHandlers.apply( this, arguments );
2811 this.on( 'activate', this.activate, this );
2813 // Only bother checking media type counts if one of the counts is zero
2814 checkCounts = _.find( this.counts, function( type ) {
2815 return type.count === 0;
2818 if ( typeof checkCounts !== 'undefined' ) {
2819 this.listenTo( media.model.Attachments.all, 'change:type', this.mediaTypeCounts );
2822 this.on( 'menu:create:gallery', this.createMenu, this );
2823 this.on( 'menu:create:playlist', this.createMenu, this );
2824 this.on( 'menu:create:video-playlist', this.createMenu, this );
2825 this.on( 'toolbar:create:main-insert', this.createToolbar, this );
2826 this.on( 'toolbar:create:main-gallery', this.createToolbar, this );
2827 this.on( 'toolbar:create:main-playlist', this.createToolbar, this );
2828 this.on( 'toolbar:create:main-video-playlist', this.createToolbar, this );
2829 this.on( 'toolbar:create:featured-image', this.featuredImageToolbar, this );
2830 this.on( 'toolbar:create:main-embed', this.mainEmbedToolbar, this );
2834 'default': 'mainMenu',
2835 'gallery': 'galleryMenu',
2836 'playlist': 'playlistMenu',
2837 'video-playlist': 'videoPlaylistMenu'
2841 'embed': 'embedContent',
2842 'edit-image': 'editImageContent',
2843 'edit-selection': 'editSelectionContent'
2847 'main-insert': 'mainInsertToolbar',
2848 'main-gallery': 'mainGalleryToolbar',
2849 'gallery-edit': 'galleryEditToolbar',
2850 'gallery-add': 'galleryAddToolbar',
2851 'main-playlist': 'mainPlaylistToolbar',
2852 'playlist-edit': 'playlistEditToolbar',
2853 'playlist-add': 'playlistAddToolbar',
2854 'main-video-playlist': 'mainVideoPlaylistToolbar',
2855 'video-playlist-edit': 'videoPlaylistEditToolbar',
2856 'video-playlist-add': 'videoPlaylistAddToolbar'
2860 _.each( handlers, function( regionHandlers, region ) {
2861 _.each( regionHandlers, function( callback, handler ) {
2862 this.on( region + ':render:' + handler, this[ callback ], this );
2867 activate: function() {
2868 // Hide menu items for states tied to particular media types if there are no items
2869 _.each( this.counts, function( type ) {
2870 if ( type.count < 1 ) {
2871 this.menuItemVisibility( type.state, 'hide' );
2876 mediaTypeCounts: function( model, attr ) {
2877 if ( typeof this.counts[ attr ] !== 'undefined' && this.counts[ attr ].count < 1 ) {
2878 this.counts[ attr ].count++;
2879 this.menuItemVisibility( this.counts[ attr ].state, 'show' );
2885 * @param {wp.Backbone.View} view
2887 mainMenu: function( view ) {
2889 'library-separator': new media.View({
2890 className: 'separator',
2896 menuItemVisibility: function( state, visibility ) {
2897 var menu = this.menu.get();
2898 if ( visibility === 'hide' ) {
2900 } else if ( visibility === 'show' ) {
2905 * @param {wp.Backbone.View} view
2907 galleryMenu: function( view ) {
2908 var lastState = this.lastState(),
2909 previous = lastState && lastState.id,
2914 text: l10n.cancelGalleryTitle,
2918 frame.setState( previous );
2923 // Keep focus inside media modal
2924 // after canceling a gallery
2925 this.controller.modal.focusManager.focus();
2928 separateCancel: new media.View({
2929 className: 'separator',
2935 playlistMenu: function( view ) {
2936 var lastState = this.lastState(),
2937 previous = lastState && lastState.id,
2942 text: l10n.cancelPlaylistTitle,
2946 frame.setState( previous );
2952 separateCancel: new media.View({
2953 className: 'separator',
2959 videoPlaylistMenu: function( view ) {
2960 var lastState = this.lastState(),
2961 previous = lastState && lastState.id,
2966 text: l10n.cancelVideoPlaylistTitle,
2970 frame.setState( previous );
2976 separateCancel: new media.View({
2977 className: 'separator',
2984 embedContent: function() {
2985 var view = new media.view.Embed({
2990 this.content.set( view );
2992 if ( ! isTouchDevice ) {
2997 editSelectionContent: function() {
2998 var state = this.state(),
2999 selection = state.get('selection'),
3002 view = new media.view.AttachmentsBrowser({
3004 collection: selection,
3005 selection: selection,
3011 AttachmentView: media.view.Attachment.EditSelection
3014 view.toolbar.set( 'backToLibrary', {
3015 text: l10n.returnToLibrary,
3019 this.controller.content.mode('browse');
3023 // Browse our library of attachments.
3024 this.content.set( view );
3026 // Trigger the controller to set focus
3027 this.trigger( 'edit:selection', this );
3030 editImageContent: function() {
3031 var image = this.state().get('image'),
3032 view = new media.view.EditImage( { model: image, controller: this } ).render();
3034 this.content.set( view );
3036 // after creating the wrapper view, load the actual editor via an ajax call
3044 * @param {wp.Backbone.View} view
3046 selectionStatusToolbar: function( view ) {
3047 var editable = this.state().get('editable');
3049 view.set( 'selection', new media.view.Selection({
3051 collection: this.state().get('selection'),
3054 // If the selection is editable, pass the callback to
3055 // switch the content mode.
3056 editable: editable && function() {
3057 this.controller.content.mode('edit-selection');
3063 * @param {wp.Backbone.View} view
3065 mainInsertToolbar: function( view ) {
3066 var controller = this;
3068 this.selectionStatusToolbar( view );
3070 view.set( 'insert', {
3073 text: l10n.insertIntoPost,
3074 requires: { selection: true },
3077 * @fires wp.media.controller.State#insert
3080 var state = controller.state(),
3081 selection = state.get('selection');
3084 state.trigger( 'insert', selection ).reset();
3090 * @param {wp.Backbone.View} view
3092 mainGalleryToolbar: function( view ) {
3093 var controller = this;
3095 this.selectionStatusToolbar( view );
3097 view.set( 'gallery', {
3099 text: l10n.createNewGallery,
3101 requires: { selection: true },
3104 var selection = controller.state().get('selection'),
3105 edit = controller.state('gallery-edit'),
3106 models = selection.where({ type: 'image' });
3108 edit.set( 'library', new media.model.Selection( models, {
3109 props: selection.props.toJSON(),
3113 this.controller.setState('gallery-edit');
3115 // Keep focus inside media modal
3116 // after jumping to gallery view
3117 this.controller.modal.focusManager.focus();
3122 mainPlaylistToolbar: function( view ) {
3123 var controller = this;
3125 this.selectionStatusToolbar( view );
3127 view.set( 'playlist', {
3129 text: l10n.createNewPlaylist,
3131 requires: { selection: true },
3134 var selection = controller.state().get('selection'),
3135 edit = controller.state('playlist-edit'),
3136 models = selection.where({ type: 'audio' });
3138 edit.set( 'library', new media.model.Selection( models, {
3139 props: selection.props.toJSON(),
3143 this.controller.setState('playlist-edit');
3145 // Keep focus inside media modal
3146 // after jumping to playlist view
3147 this.controller.modal.focusManager.focus();
3152 mainVideoPlaylistToolbar: function( view ) {
3153 var controller = this;
3155 this.selectionStatusToolbar( view );
3157 view.set( 'video-playlist', {
3159 text: l10n.createNewVideoPlaylist,
3161 requires: { selection: true },
3164 var selection = controller.state().get('selection'),
3165 edit = controller.state('video-playlist-edit'),
3166 models = selection.where({ type: 'video' });
3168 edit.set( 'library', new media.model.Selection( models, {
3169 props: selection.props.toJSON(),
3173 this.controller.setState('video-playlist-edit');
3175 // Keep focus inside media modal
3176 // after jumping to video playlist view
3177 this.controller.modal.focusManager.focus();
3182 featuredImageToolbar: function( toolbar ) {
3183 this.createSelectToolbar( toolbar, {
3184 text: l10n.setFeaturedImage,
3185 state: this.options.state
3189 mainEmbedToolbar: function( toolbar ) {
3190 toolbar.view = new media.view.Toolbar.Embed({
3195 galleryEditToolbar: function() {
3196 var editing = this.state().get('editing');
3197 this.toolbar.set( new media.view.Toolbar({
3202 text: editing ? l10n.updateGallery : l10n.insertGallery,
3204 requires: { library: true },
3207 * @fires wp.media.controller.State#update
3210 var controller = this.controller,
3211 state = controller.state();
3214 state.trigger( 'update', state.get('library') );
3216 // Restore and reset the default state.
3217 controller.setState( controller.options.state );
3225 galleryAddToolbar: function() {
3226 this.toolbar.set( new media.view.Toolbar({
3231 text: l10n.addToGallery,
3233 requires: { selection: true },
3236 * @fires wp.media.controller.State#reset
3239 var controller = this.controller,
3240 state = controller.state(),
3241 edit = controller.state('gallery-edit');
3243 edit.get('library').add( state.get('selection').models );
3244 state.trigger('reset');
3245 controller.setState('gallery-edit');
3252 playlistEditToolbar: function() {
3253 var editing = this.state().get('editing');
3254 this.toolbar.set( new media.view.Toolbar({
3259 text: editing ? l10n.updatePlaylist : l10n.insertPlaylist,
3261 requires: { library: true },
3264 * @fires wp.media.controller.State#update
3267 var controller = this.controller,
3268 state = controller.state();
3271 state.trigger( 'update', state.get('library') );
3273 // Restore and reset the default state.
3274 controller.setState( controller.options.state );
3282 playlistAddToolbar: function() {
3283 this.toolbar.set( new media.view.Toolbar({
3288 text: l10n.addToPlaylist,
3290 requires: { selection: true },
3293 * @fires wp.media.controller.State#reset
3296 var controller = this.controller,
3297 state = controller.state(),
3298 edit = controller.state('playlist-edit');
3300 edit.get('library').add( state.get('selection').models );
3301 state.trigger('reset');
3302 controller.setState('playlist-edit');
3309 videoPlaylistEditToolbar: function() {
3310 var editing = this.state().get('editing');
3311 this.toolbar.set( new media.view.Toolbar({
3316 text: editing ? l10n.updateVideoPlaylist : l10n.insertVideoPlaylist,
3318 requires: { library: true },
3321 var controller = this.controller,
3322 state = controller.state(),
3323 library = state.get('library');
3325 library.type = 'video';
3328 state.trigger( 'update', library );
3330 // Restore and reset the default state.
3331 controller.setState( controller.options.state );
3339 videoPlaylistAddToolbar: function() {
3340 this.toolbar.set( new media.view.Toolbar({
3345 text: l10n.addToVideoPlaylist,
3347 requires: { selection: true },
3350 var controller = this.controller,
3351 state = controller.state(),
3352 edit = controller.state('video-playlist-edit');
3354 edit.get('library').add( state.get('selection').models );
3355 state.trigger('reset');
3356 controller.setState('video-playlist-edit');
3365 * wp.media.view.MediaFrame.ImageDetails
3367 * A media frame for manipulating an image that's already been inserted
3371 * @augments wp.media.view.MediaFrame.Select
3372 * @augments wp.media.view.MediaFrame
3373 * @augments wp.media.view.Frame
3374 * @augments wp.media.View
3375 * @augments wp.Backbone.View
3376 * @augments Backbone.View
3377 * @mixes wp.media.controller.StateMachine
3379 media.view.MediaFrame.ImageDetails = media.view.MediaFrame.Select.extend({
3383 menu: 'image-details',
3384 content: 'image-details',
3385 toolbar: 'image-details',
3387 title: l10n.imageDetailsTitle,
3391 initialize: function( options ) {
3392 this.image = new media.model.PostImage( options.metadata );
3393 this.options.selection = new media.model.Selection( this.image.attachment, { multiple: false } );
3394 media.view.MediaFrame.Select.prototype.initialize.apply( this, arguments );
3397 bindHandlers: function() {
3398 media.view.MediaFrame.Select.prototype.bindHandlers.apply( this, arguments );
3399 this.on( 'menu:create:image-details', this.createMenu, this );
3400 this.on( 'content:create:image-details', this.imageDetailsContent, this );
3401 this.on( 'content:render:edit-image', this.editImageContent, this );
3402 this.on( 'toolbar:render:image-details', this.renderImageDetailsToolbar, this );
3403 // override the select toolbar
3404 this.on( 'toolbar:render:replace', this.renderReplaceImageToolbar, this );
3407 createStates: function() {
3409 new media.controller.ImageDetails({
3413 new media.controller.ReplaceImage({
3414 id: 'replace-image',
3415 library: media.query( { type: 'image' } ),
3418 title: l10n.imageReplaceTitle,
3421 displaySettings: true
3423 new media.controller.EditImage( {
3425 selection: this.options.selection
3430 imageDetailsContent: function( options ) {
3431 options.view = new media.view.ImageDetails({
3433 model: this.state().image,
3434 attachment: this.state().image.attachment
3438 editImageContent: function() {
3439 var state = this.state(),
3440 model = state.get('image'),
3447 view = new media.view.EditImage( { model: model, controller: this } ).render();
3449 this.content.set( view );
3451 // after bringing in the frame, load the actual editor via an ajax call
3456 renderImageDetailsToolbar: function() {
3457 this.toolbar.set( new media.view.Toolbar({
3466 var controller = this.controller,
3467 state = controller.state();
3471 // not sure if we want to use wp.media.string.image which will create a shortcode or
3472 // perhaps wp.html.string to at least to build the <img />
3473 state.trigger( 'update', controller.image.toJSON() );
3475 // Restore and reset the default state.
3476 controller.setState( controller.options.state );
3484 renderReplaceImageToolbar: function() {
3486 lastState = frame.lastState(),
3487 previous = lastState && lastState.id;
3489 this.toolbar.set( new media.view.Toolbar({
3497 frame.setState( previous );
3510 var controller = this.controller,
3511 state = controller.state(),
3512 selection = state.get( 'selection' ),
3513 attachment = selection.single();
3517 controller.image.changeAttachment( attachment, state.display( attachment ) );
3519 // not sure if we want to use wp.media.string.image which will create a shortcode or
3520 // perhaps wp.html.string to at least to build the <img />
3521 state.trigger( 'replace', controller.image.toJSON() );
3523 // Restore and reset the default state.
3524 controller.setState( controller.options.state );
3535 * wp.media.view.Modal
3537 * A modal view, which the media modal uses as its default container.
3540 * @augments wp.media.View
3541 * @augments wp.Backbone.View
3542 * @augments Backbone.View
3544 media.view.Modal = media.View.extend({
3546 template: media.template('media-modal'),
3553 'click .media-modal-backdrop, .media-modal-close': 'escapeHandler',
3554 'keydown': 'keydown'
3557 initialize: function() {
3558 _.defaults( this.options, {
3559 container: document.body,
3565 this.focusManager = new media.view.FocusManager({
3572 prepare: function() {
3574 title: this.options.title
3579 * @returns {wp.media.view.Modal} Returns itself to allow chaining
3581 attach: function() {
3582 if ( this.views.attached ) {
3586 if ( ! this.views.rendered ) {
3590 this.$el.appendTo( this.options.container );
3592 // Manually mark the view as attached and trigger ready.
3593 this.views.attached = true;
3596 return this.propagate('attach');
3600 * @returns {wp.media.view.Modal} Returns itself to allow chaining
3602 detach: function() {
3603 if ( this.$el.is(':visible') ) {
3608 this.views.attached = false;
3609 return this.propagate('detach');
3613 * @returns {wp.media.view.Modal} Returns itself to allow chaining
3617 options = this.options,
3620 if ( $el.is(':visible') ) {
3624 if ( ! this.views.attached ) {
3628 // If the `freeze` option is set, record the window's scroll position.
3629 if ( options.freeze ) {
3631 scrollTop: $( window ).scrollTop()
3635 // Disable page scrolling.
3636 $( 'body' ).addClass( 'modal-open' );
3640 // Try to close the onscreen keyboard
3641 if ( 'ontouchend' in document ) {
3642 if ( ( mceEditor = window.tinymce && window.tinymce.activeEditor ) && ! mceEditor.isHidden() && mceEditor.iframeElement ) {
3643 mceEditor.iframeElement.focus();
3644 mceEditor.iframeElement.blur();
3646 setTimeout( function() {
3647 mceEditor.iframeElement.blur();
3654 return this.propagate('open');
3658 * @param {Object} options
3659 * @returns {wp.media.view.Modal} Returns itself to allow chaining
3661 close: function( options ) {
3662 var freeze = this._freeze;
3664 if ( ! this.views.attached || ! this.$el.is(':visible') ) {
3668 // Enable page scrolling.
3669 $( 'body' ).removeClass( 'modal-open' );
3671 // Hide modal and remove restricted media modal tab focus once it's closed
3672 this.$el.hide().undelegate( 'keydown' );
3674 // Put focus back in useful location once modal is closed
3675 $('#wpbody-content').focus();
3677 this.propagate('close');
3679 // If the `freeze` option is set, restore the container's scroll position.
3681 $( window ).scrollTop( freeze.scrollTop );
3684 if ( options && options.escape ) {
3685 this.propagate('escape');
3691 * @returns {wp.media.view.Modal} Returns itself to allow chaining
3693 escape: function() {
3694 return this.close({ escape: true });
3697 * @param {Object} event
3699 escapeHandler: function( event ) {
3700 event.preventDefault();
3705 * @param {Array|Object} content Views to register to '.media-modal-content'
3706 * @returns {wp.media.view.Modal} Returns itself to allow chaining
3708 content: function( content ) {
3709 this.views.set( '.media-modal-content', content );
3714 * Triggers a modal event and if the `propagate` option is set,
3715 * forwards events to the modal's controller.
3717 * @param {string} id
3718 * @returns {wp.media.view.Modal} Returns itself to allow chaining
3720 propagate: function( id ) {
3723 if ( this.options.propagate ) {
3724 this.controller.trigger( id );
3730 * @param {Object} event
3732 keydown: function( event ) {
3733 // Close the modal when escape is pressed.
3734 if ( 27 === event.which && this.$el.is(':visible') ) {
3736 event.stopImmediatePropagation();
3742 * wp.media.view.FocusManager
3745 * @augments wp.media.View
3746 * @augments wp.Backbone.View
3747 * @augments Backbone.View
3749 media.view.FocusManager = media.View.extend({
3752 'keydown': 'constrainTabbing'
3755 focus: function() { // Reset focus on first left menu item
3756 this.$('.media-menu-item').first().focus();
3759 * @param {Object} event
3761 constrainTabbing: function( event ) {
3764 // Look for the tab key.
3765 if ( 9 !== event.keyCode ) {
3769 tabbables = this.$( ':tabbable' );
3771 // Keep tab focus within media modal while it's open
3772 if ( tabbables.last()[0] === event.target && ! event.shiftKey ) {
3773 tabbables.first().focus();
3775 } else if ( tabbables.first()[0] === event.target && event.shiftKey ) {
3776 tabbables.last().focus();
3784 * wp.media.view.UploaderWindow
3786 * An uploader window that allows for dragging and dropping media.
3789 * @augments wp.media.View
3790 * @augments wp.Backbone.View
3791 * @augments Backbone.View
3793 * @param {object} [options] Options hash passed to the view.
3794 * @param {object} [options.uploader] Uploader properties.
3795 * @param {jQuery} [options.uploader.browser]
3796 * @param {jQuery} [options.uploader.dropzone] jQuery collection of the dropzone.
3797 * @param {object} [options.uploader.params]
3799 media.view.UploaderWindow = media.View.extend({
3801 className: 'uploader-window',
3802 template: media.template('uploader-window'),
3804 initialize: function() {
3807 this.$browser = $('<a href="#" class="browser" />').hide().appendTo('body');
3809 uploader = this.options.uploader = _.defaults( this.options.uploader || {}, {
3811 browser: this.$browser,
3815 // Ensure the dropzone is a jQuery collection.
3816 if ( uploader.dropzone && ! (uploader.dropzone instanceof $) ) {
3817 uploader.dropzone = $( uploader.dropzone );
3820 this.controller.on( 'activate', this.refresh, this );
3822 this.controller.on( 'detach', function() {
3823 this.$browser.remove();
3827 refresh: function() {
3828 if ( this.uploader ) {
3829 this.uploader.refresh();
3834 var postId = media.view.settings.post.id,
3837 // If the uploader already exists, bail.
3838 if ( this.uploader ) {
3843 this.options.uploader.params.post_id = postId;
3845 this.uploader = new wp.Uploader( this.options.uploader );
3847 dropzone = this.uploader.dropzone;
3848 dropzone.on( 'dropzone:enter', _.bind( this.show, this ) );
3849 dropzone.on( 'dropzone:leave', _.bind( this.hide, this ) );
3851 $( this.uploader ).on( 'uploader:ready', _.bind( this._ready, this ) );
3854 _ready: function() {
3855 this.controller.trigger( 'uploader:ready' );
3859 var $el = this.$el.show();
3861 // Ensure that the animation is triggered by waiting until
3862 // the transparent element is painted into the DOM.
3863 _.defer( function() {
3864 $el.css({ opacity: 1 });
3869 var $el = this.$el.css({ opacity: 0 });
3871 media.transition( $el ).done( function() {
3872 // Transition end events are subject to race conditions.
3873 // Make sure that the value is set as intended.
3874 if ( '0' === $el.css('opacity') ) {
3879 // https://core.trac.wordpress.org/ticket/27341
3880 _.delay( function() {
3881 if ( '0' === $el.css('opacity') && $el.is(':visible') ) {
3889 * Creates a dropzone on WP editor instances (elements with .wp-editor-wrap
3890 * or #wp-fullscreen-body) and relays drag'n'dropped files to a media workflow.
3892 * wp.media.view.EditorUploader
3895 * @augments wp.media.View
3896 * @augments wp.Backbone.View
3897 * @augments Backbone.View
3899 media.view.EditorUploader = media.View.extend({
3901 className: 'uploader-editor',
3902 template: media.template( 'uploader-editor' ),
3905 overContainer: false,
3906 overDropzone: false,
3910 * Bind drag'n'drop events to callbacks.
3912 initialize: function() {
3915 this.initialized = false;
3917 // Bail if not enabled or UA does not support drag'n'drop or File API.
3918 if ( ! window.tinyMCEPreInit || ! window.tinyMCEPreInit.dragDropUpload || ! this.browserSupport() ) {
3922 this.$document = $(document);
3923 this.dropzones = [];
3926 this.$document.on( 'drop', '.uploader-editor', _.bind( this.drop, this ) );
3927 this.$document.on( 'dragover', '.uploader-editor', _.bind( this.dropzoneDragover, this ) );
3928 this.$document.on( 'dragleave', '.uploader-editor', _.bind( this.dropzoneDragleave, this ) );
3929 this.$document.on( 'click', '.uploader-editor', _.bind( this.click, this ) );
3931 this.$document.on( 'dragover', _.bind( this.containerDragover, this ) );
3932 this.$document.on( 'dragleave', _.bind( this.containerDragleave, this ) );
3934 this.$document.on( 'dragstart dragend drop', function( event ) {
3935 self.localDrag = event.type === 'dragstart';
3938 this.initialized = true;
3943 * Check browser support for drag'n'drop.
3947 browserSupport: function() {
3948 var supports = false, div = document.createElement('div');
3950 supports = ( 'draggable' in div ) || ( 'ondragstart' in div && 'ondrop' in div );
3951 supports = supports && !! ( window.File && window.FileList && window.FileReader );
3955 isDraggingFile: function( event ) {
3956 if ( this.draggingFile !== null ) {
3957 return this.draggingFile;
3960 if ( _.isUndefined( event.originalEvent ) || _.isUndefined( event.originalEvent.dataTransfer ) ) {
3964 this.draggingFile = _.indexOf( event.originalEvent.dataTransfer.types, 'Files' ) > -1 &&
3965 _.indexOf( event.originalEvent.dataTransfer.types, 'text/plain' ) === -1;
3967 return this.draggingFile;
3970 refresh: function( e ) {
3972 for ( dropzone_id in this.dropzones ) {
3973 // Hide the dropzones only if dragging has left the screen.
3974 this.dropzones[ dropzone_id ].toggle( this.overContainer || this.overDropzone );
3977 if ( ! _.isUndefined( e ) ) {
3978 $( e.target ).closest( '.uploader-editor' ).toggleClass( 'droppable', this.overDropzone );
3981 if ( ! this.overContainer && ! this.overDropzone ) {
3982 this.draggingFile = null;
3988 render: function() {
3989 if ( ! this.initialized ) {
3993 media.View.prototype.render.apply( this, arguments );
3994 $( '.wp-editor-wrap, #wp-fullscreen-body' ).each( _.bind( this.attach, this ) );
3998 attach: function( index, editor ) {
3999 // Attach a dropzone to an editor.
4000 var dropzone = this.$el.clone();
4001 this.dropzones.push( dropzone );
4002 $( editor ).append( dropzone );
4007 * When a file is dropped on the editor uploader, open up an editor media workflow
4008 * and upload the file immediately.
4010 * @param {jQuery.Event} event The 'drop' event.
4012 drop: function( event ) {
4013 var $wrap = null, uploadView;
4015 this.containerDragleave( event );
4016 this.dropzoneDragleave( event );
4018 this.files = event.originalEvent.dataTransfer.files;
4019 if ( this.files.length < 1 ) {
4023 // Set the active editor to the drop target.
4024 $wrap = $( event.target ).parents( '.wp-editor-wrap' );
4025 if ( $wrap.length > 0 && $wrap[0].id ) {
4026 window.wpActiveEditor = $wrap[0].id.slice( 3, -5 );
4029 if ( ! this.workflow ) {
4030 this.workflow = wp.media.editor.open( 'content', {
4033 title: wp.media.view.l10n.addMedia,
4036 uploadView = this.workflow.uploader;
4037 if ( uploadView.uploader && uploadView.uploader.ready ) {
4038 this.addFiles.apply( this );
4040 this.workflow.on( 'uploader:ready', this.addFiles, this );
4043 this.workflow.state().reset();
4044 this.addFiles.apply( this );
4045 this.workflow.open();
4052 * Add the files to the uploader.
4054 addFiles: function() {
4055 if ( this.files.length ) {
4056 this.workflow.uploader.uploader.uploader.addFile( _.toArray( this.files ) );
4062 containerDragover: function( event ) {
4063 if ( this.localDrag || ! this.isDraggingFile( event ) ) {
4067 this.overContainer = true;
4071 containerDragleave: function() {
4072 this.overContainer = false;
4074 // Throttle dragleave because it's called when bouncing from some elements to others.
4075 _.delay( _.bind( this.refresh, this ), 50 );
4078 dropzoneDragover: function( event ) {
4079 if ( this.localDrag || ! this.isDraggingFile( event ) ) {
4083 this.overDropzone = true;
4084 this.refresh( event );
4088 dropzoneDragleave: function( e ) {
4089 this.overDropzone = false;
4090 _.delay( _.bind( this.refresh, this, e ), 50 );
4093 click: function( e ) {
4094 // In the rare case where the dropzone gets stuck, hide it on click.
4095 this.containerDragleave( e );
4096 this.dropzoneDragleave( e );
4097 this.localDrag = false;
4102 * wp.media.view.UploaderInline
4104 * The inline uploader that shows up in the 'Upload Files' tab.
4107 * @augments wp.media.View
4108 * @augments wp.Backbone.View
4109 * @augments Backbone.View
4111 media.view.UploaderInline = media.View.extend({
4113 className: 'uploader-inline',
4114 template: media.template('uploader-inline'),
4117 'click .close': 'hide'
4120 initialize: function() {
4121 _.defaults( this.options, {
4127 if ( ! this.options.$browser && this.controller.uploader ) {
4128 this.options.$browser = this.controller.uploader.$browser;
4131 if ( _.isUndefined( this.options.postId ) ) {
4132 this.options.postId = media.view.settings.post.id;
4135 if ( this.options.status ) {
4136 this.views.set( '.upload-inline-status', new media.view.UploaderStatus({
4137 controller: this.controller
4142 prepare: function() {
4143 var suggestedWidth = this.controller.state().get('suggestedWidth'),
4144 suggestedHeight = this.controller.state().get('suggestedHeight'),
4147 data.message = this.options.message;
4148 data.canClose = this.options.canClose;
4150 if ( suggestedWidth && suggestedHeight ) {
4151 data.suggestedWidth = suggestedWidth;
4152 data.suggestedHeight = suggestedHeight;
4158 * @returns {wp.media.view.UploaderInline} Returns itself to allow chaining
4160 dispose: function() {
4161 if ( this.disposing ) {
4163 * call 'dispose' directly on the parent class
4165 return media.View.prototype.dispose.apply( this, arguments );
4168 // Run remove on `dispose`, so we can be sure to refresh the
4169 // uploader with a view-less DOM. Track whether we're disposing
4170 // so we don't trigger an infinite loop.
4171 this.disposing = true;
4172 return this.remove();
4175 * @returns {wp.media.view.UploaderInline} Returns itself to allow chaining
4177 remove: function() {
4179 * call 'remove' directly on the parent class
4181 var result = media.View.prototype.remove.apply( this, arguments );
4183 _.defer( _.bind( this.refresh, this ) );
4187 refresh: function() {
4188 var uploader = this.controller.uploader;
4195 * @returns {wp.media.view.UploaderInline}
4198 var $browser = this.options.$browser,
4201 if ( this.controller.uploader ) {
4202 $placeholder = this.$('.browser');
4204 // Check if we've already replaced the placeholder.
4205 if ( $placeholder[0] === $browser[0] ) {
4209 $browser.detach().text( $placeholder.text() );
4210 $browser[0].className = $placeholder[0].className;
4211 $placeholder.replaceWith( $browser.show() );
4218 this.$el.removeClass( 'hidden' );
4221 this.$el.addClass( 'hidden' );
4227 * wp.media.view.UploaderStatus
4229 * An uploader status for on-going uploads.
4232 * @augments wp.media.View
4233 * @augments wp.Backbone.View
4234 * @augments Backbone.View
4236 media.view.UploaderStatus = media.View.extend({
4237 className: 'media-uploader-status',
4238 template: media.template('uploader-status'),
4241 'click .upload-dismiss-errors': 'dismiss'
4244 initialize: function() {
4245 this.queue = wp.Uploader.queue;
4246 this.queue.on( 'add remove reset', this.visibility, this );
4247 this.queue.on( 'add remove reset change:percent', this.progress, this );
4248 this.queue.on( 'add remove reset change:uploading', this.info, this );
4250 this.errors = wp.Uploader.errors;
4251 this.errors.reset();
4252 this.errors.on( 'add remove reset', this.visibility, this );
4253 this.errors.on( 'add', this.error, this );
4256 * @global wp.Uploader
4257 * @returns {wp.media.view.UploaderStatus}
4259 dispose: function() {
4260 wp.Uploader.queue.off( null, null, this );
4262 * call 'dispose' directly on the parent class
4264 media.View.prototype.dispose.apply( this, arguments );
4268 visibility: function() {
4269 this.$el.toggleClass( 'uploading', !! this.queue.length );
4270 this.$el.toggleClass( 'errors', !! this.errors.length );
4271 this.$el.toggle( !! this.queue.length || !! this.errors.length );
4276 '$bar': '.media-progress-bar div',
4277 '$index': '.upload-index',
4278 '$total': '.upload-total',
4279 '$filename': '.upload-filename'
4280 }, function( selector, key ) {
4281 this[ key ] = this.$( selector );
4289 progress: function() {
4290 var queue = this.queue,
4293 if ( ! $bar || ! queue.length ) {
4297 $bar.width( ( queue.reduce( function( memo, attachment ) {
4298 if ( ! attachment.get('uploading') ) {
4302 var percent = attachment.get('percent');
4303 return memo + ( _.isNumber( percent ) ? percent : 100 );
4304 }, 0 ) / queue.length ) + '%' );
4308 var queue = this.queue,
4311 if ( ! queue.length ) {
4315 active = this.queue.find( function( attachment, i ) {
4317 return attachment.get('uploading');
4320 this.$index.text( index + 1 );
4321 this.$total.text( queue.length );
4322 this.$filename.html( active ? this.filename( active.get('filename') ) : '' );
4325 * @param {string} filename
4328 filename: function( filename ) {
4329 return media.truncate( _.escape( filename ), 24 );
4332 * @param {Backbone.Model} error
4334 error: function( error ) {
4335 this.views.add( '.upload-errors', new media.view.UploaderStatusError({
4336 filename: this.filename( error.get('file').name ),
4337 message: error.get('message')
4342 * @global wp.Uploader
4344 * @param {Object} event
4346 dismiss: function( event ) {
4347 var errors = this.views.get('.upload-errors');
4349 event.preventDefault();
4352 _.invoke( errors, 'remove' );
4354 wp.Uploader.errors.reset();
4359 * wp.media.view.UploaderStatusError
4362 * @augments wp.media.View
4363 * @augments wp.Backbone.View
4364 * @augments Backbone.View
4366 media.view.UploaderStatusError = media.View.extend({
4367 className: 'upload-error',
4368 template: media.template('uploader-status-error')
4372 * wp.media.view.Toolbar
4374 * A toolbar which consists of a primary and a secondary section. Each sections
4375 * can be filled with views.
4378 * @augments wp.media.View
4379 * @augments wp.Backbone.View
4380 * @augments Backbone.View
4382 media.view.Toolbar = media.View.extend({
4384 className: 'media-toolbar',
4386 initialize: function() {
4387 var state = this.controller.state(),
4388 selection = this.selection = state.get('selection'),
4389 library = this.library = state.get('library');
4393 // The toolbar is composed of two `PriorityList` views.
4394 this.primary = new media.view.PriorityList();
4395 this.secondary = new media.view.PriorityList();
4396 this.primary.$el.addClass('media-toolbar-primary search-form');
4397 this.secondary.$el.addClass('media-toolbar-secondary');
4399 this.views.set([ this.secondary, this.primary ]);
4401 if ( this.options.items ) {
4402 this.set( this.options.items, { silent: true });
4405 if ( ! this.options.silent ) {
4410 selection.on( 'add remove reset', this.refresh, this );
4414 library.on( 'add remove reset', this.refresh, this );
4418 * @returns {wp.media.view.Toolbar} Returns itsef to allow chaining
4420 dispose: function() {
4421 if ( this.selection ) {
4422 this.selection.off( null, null, this );
4425 if ( this.library ) {
4426 this.library.off( null, null, this );
4429 * call 'dispose' directly on the parent class
4431 return media.View.prototype.dispose.apply( this, arguments );
4439 * @param {string} id
4440 * @param {Backbone.View|Object} view
4441 * @param {Object} [options={}]
4442 * @returns {wp.media.view.Toolbar} Returns itself to allow chaining
4444 set: function( id, view, options ) {
4446 options = options || {};
4448 // Accept an object with an `id` : `view` mapping.
4449 if ( _.isObject( id ) ) {
4450 _.each( id, function( view, id ) {
4451 this.set( id, view, { silent: true });
4455 if ( ! ( view instanceof Backbone.View ) ) {
4456 view.classes = [ 'media-button-' + id ].concat( view.classes || [] );
4457 view = new media.view.Button( view ).render();
4460 view.controller = view.controller || this.controller;
4462 this._views[ id ] = view;
4464 list = view.options.priority < 0 ? 'secondary' : 'primary';
4465 this[ list ].set( id, view, options );
4468 if ( ! options.silent ) {
4475 * @param {string} id
4476 * @returns {wp.media.view.Button}
4478 get: function( id ) {
4479 return this._views[ id ];
4482 * @param {string} id
4483 * @param {Object} options
4484 * @returns {wp.media.view.Toolbar} Returns itself to allow chaining
4486 unset: function( id, options ) {
4487 delete this._views[ id ];
4488 this.primary.unset( id, options );
4489 this.secondary.unset( id, options );
4491 if ( ! options || ! options.silent ) {
4497 refresh: function() {
4498 var state = this.controller.state(),
4499 library = state.get('library'),
4500 selection = state.get('selection');
4502 _.each( this._views, function( button ) {
4503 if ( ! button.model || ! button.options || ! button.options.requires ) {
4507 var requires = button.options.requires,
4510 // Prevent insertion of attachments if any of them are still uploading
4511 disabled = _.some( selection.models, function( attachment ) {
4512 return attachment.get('uploading') === true;
4515 if ( requires.selection && selection && ! selection.length ) {
4517 } else if ( requires.library && library && ! library.length ) {
4520 button.model.set( 'disabled', disabled );
4526 * wp.media.view.Toolbar.Select
4529 * @augments wp.media.view.Toolbar
4530 * @augments wp.media.View
4531 * @augments wp.Backbone.View
4532 * @augments Backbone.View
4534 media.view.Toolbar.Select = media.view.Toolbar.extend({
4535 initialize: function() {
4536 var options = this.options;
4538 _.bindAll( this, 'clickSelect' );
4540 _.defaults( options, {
4547 // Does the button rely on the selection?
4553 options.items = _.defaults( options.items || {}, {
4558 click: this.clickSelect,
4559 requires: options.requires
4562 // Call 'initialize' directly on the parent class.
4563 media.view.Toolbar.prototype.initialize.apply( this, arguments );
4566 clickSelect: function() {
4567 var options = this.options,
4568 controller = this.controller;
4570 if ( options.close ) {
4574 if ( options.event ) {
4575 controller.state().trigger( options.event );
4578 if ( options.state ) {
4579 controller.setState( options.state );
4582 if ( options.reset ) {
4589 * wp.media.view.Toolbar.Embed
4592 * @augments wp.media.view.Toolbar.Select
4593 * @augments wp.media.view.Toolbar
4594 * @augments wp.media.View
4595 * @augments wp.Backbone.View
4596 * @augments Backbone.View
4598 media.view.Toolbar.Embed = media.view.Toolbar.Select.extend({
4599 initialize: function() {
4600 _.defaults( this.options, {
4601 text: l10n.insertIntoPost,
4604 // Call 'initialize' directly on the parent class.
4605 media.view.Toolbar.Select.prototype.initialize.apply( this, arguments );
4608 refresh: function() {
4609 var url = this.controller.state().props.get('url');
4610 this.get('select').model.set( 'disabled', ! url || url === 'http://' );
4612 * call 'refresh' directly on the parent class
4614 media.view.Toolbar.Select.prototype.refresh.apply( this, arguments );
4619 * wp.media.view.Button
4622 * @augments wp.media.View
4623 * @augments wp.Backbone.View
4624 * @augments Backbone.View
4626 media.view.Button = media.View.extend({
4628 className: 'media-button',
4629 attributes: { href: '#' },
4642 initialize: function() {
4644 * Create a model with the provided `defaults`.
4646 * @member {Backbone.Model}
4648 this.model = new Backbone.Model( this.defaults );
4650 // If any of the `options` have a key from `defaults`, apply its
4651 // value to the `model` and remove it from the `options object.
4652 _.each( this.defaults, function( def, key ) {
4653 var value = this.options[ key ];
4654 if ( _.isUndefined( value ) ) {
4658 this.model.set( key, value );
4659 delete this.options[ key ];
4662 this.model.on( 'change', this.render, this );
4665 * @returns {wp.media.view.Button} Returns itself to allow chaining
4667 render: function() {
4668 var classes = [ 'button', this.className ],
4669 model = this.model.toJSON();
4671 if ( model.style ) {
4672 classes.push( 'button-' + model.style );
4676 classes.push( 'button-' + model.size );
4679 classes = _.uniq( classes.concat( this.options.classes ) );
4680 this.el.className = classes.join(' ');
4682 this.$el.attr( 'disabled', model.disabled );
4683 this.$el.text( this.model.get('text') );
4688 * @param {Object} event
4690 click: function( event ) {
4691 if ( '#' === this.attributes.href ) {
4692 event.preventDefault();
4695 if ( this.options.click && ! this.model.get('disabled') ) {
4696 this.options.click.apply( this, arguments );
4702 * wp.media.view.ButtonGroup
4705 * @augments wp.media.View
4706 * @augments wp.Backbone.View
4707 * @augments Backbone.View
4709 media.view.ButtonGroup = media.View.extend({
4711 className: 'button-group button-large media-button-group',
4713 initialize: function() {
4715 * @member {wp.media.view.Button[]}
4717 this.buttons = _.map( this.options.buttons || [], function( button ) {
4718 if ( button instanceof Backbone.View ) {
4721 return new media.view.Button( button ).render();
4725 delete this.options.buttons;
4727 if ( this.options.classes ) {
4728 this.$el.addClass( this.options.classes );
4733 * @returns {wp.media.view.ButtonGroup}
4735 render: function() {
4736 this.$el.html( $( _.pluck( this.buttons, 'el' ) ).detach() );
4742 * wp.media.view.PriorityList
4745 * @augments wp.media.View
4746 * @augments wp.Backbone.View
4747 * @augments Backbone.View
4749 media.view.PriorityList = media.View.extend({
4752 initialize: function() {
4755 this.set( _.extend( {}, this._views, this.options.views ), { silent: true });
4756 delete this.options.views;
4758 if ( ! this.options.silent ) {
4763 * @param {string} id
4764 * @param {wp.media.View|Object} view
4765 * @param {Object} options
4766 * @returns {wp.media.view.PriorityList} Returns itself to allow chaining
4768 set: function( id, view, options ) {
4769 var priority, views, index;
4771 options = options || {};
4773 // Accept an object with an `id` : `view` mapping.
4774 if ( _.isObject( id ) ) {
4775 _.each( id, function( view, id ) {
4776 this.set( id, view );
4781 if ( ! (view instanceof Backbone.View) ) {
4782 view = this.toView( view, id, options );
4784 view.controller = view.controller || this.controller;
4788 priority = view.options.priority || 10;
4789 views = this.views.get() || [];
4791 _.find( views, function( existing, i ) {
4792 if ( existing.options.priority > priority ) {
4798 this._views[ id ] = view;
4799 this.views.add( view, {
4800 at: _.isNumber( index ) ? index : views.length || 0
4806 * @param {string} id
4807 * @returns {wp.media.View}
4809 get: function( id ) {
4810 return this._views[ id ];
4813 * @param {string} id
4814 * @returns {wp.media.view.PriorityList}
4816 unset: function( id ) {
4817 var view = this.get( id );
4823 delete this._views[ id ];
4827 * @param {Object} options
4828 * @returns {wp.media.View}
4830 toView: function( options ) {
4831 return new media.View( options );
4836 * wp.media.view.MenuItem
4839 * @augments wp.media.View
4840 * @augments wp.Backbone.View
4841 * @augments Backbone.View
4843 media.view.MenuItem = media.View.extend({
4845 className: 'media-menu-item',
4855 * @param {Object} event
4857 _click: function( event ) {
4858 var clickOverride = this.options.click;
4861 event.preventDefault();
4864 if ( clickOverride ) {
4865 clickOverride.call( this );
4870 // When selecting a tab along the left side,
4871 // focus should be transferred into the main panel
4872 if ( ! isTouchDevice ) {
4873 $('.media-frame-content input').first().focus();
4878 var state = this.options.state;
4881 this.controller.setState( state );
4882 this.views.parent.$el.removeClass( 'visible' ); // TODO: or hide on any click, see below
4886 * @returns {wp.media.view.MenuItem} returns itself to allow chaining
4888 render: function() {
4889 var options = this.options;
4891 if ( options.text ) {
4892 this.$el.text( options.text );
4893 } else if ( options.html ) {
4894 this.$el.html( options.html );
4902 * wp.media.view.Menu
4905 * @augments wp.media.view.PriorityList
4906 * @augments wp.media.View
4907 * @augments wp.Backbone.View
4908 * @augments Backbone.View
4910 media.view.Menu = media.view.PriorityList.extend({
4912 className: 'media-menu',
4914 ItemView: media.view.MenuItem,
4917 /* TODO: alternatively hide on any click anywhere
4923 this.$el.removeClass( 'visible' );
4928 * @param {Object} options
4929 * @param {string} id
4930 * @returns {wp.media.View}
4932 toView: function( options, id ) {
4933 options = options || {};
4934 options[ this.property ] = options[ this.property ] || id;
4935 return new this.ItemView( options ).render();
4940 * call 'ready' directly on the parent class
4942 media.view.PriorityList.prototype.ready.apply( this, arguments );
4948 * call 'set' directly on the parent class
4950 media.view.PriorityList.prototype.set.apply( this, arguments );
4956 * call 'unset' directly on the parent class
4958 media.view.PriorityList.prototype.unset.apply( this, arguments );
4962 visibility: function() {
4963 var region = this.region,
4964 view = this.controller[ region ].get(),
4965 views = this.views.get(),
4966 hide = ! views || views.length < 2;
4968 if ( this === view ) {
4969 this.controller.$el.toggleClass( 'hide-' + region, hide );
4973 * @param {string} id
4975 select: function( id ) {
4976 var view = this.get( id );
4983 view.$el.addClass('active');
4986 deselect: function() {
4987 this.$el.children().removeClass('active');
4990 hide: function( id ) {
4991 var view = this.get( id );
4997 view.$el.addClass('hidden');
5000 show: function( id ) {
5001 var view = this.get( id );
5007 view.$el.removeClass('hidden');
5012 * wp.media.view.RouterItem
5015 * @augments wp.media.view.MenuItem
5016 * @augments wp.media.View
5017 * @augments wp.Backbone.View
5018 * @augments Backbone.View
5020 media.view.RouterItem = media.view.MenuItem.extend({
5022 * On click handler to activate the content region's corresponding mode.
5025 var contentMode = this.options.contentMode;
5026 if ( contentMode ) {
5027 this.controller.content.mode( contentMode );
5033 * wp.media.view.Router
5036 * @augments wp.media.view.Menu
5037 * @augments wp.media.view.PriorityList
5038 * @augments wp.media.View
5039 * @augments wp.Backbone.View
5040 * @augments Backbone.View
5042 media.view.Router = media.view.Menu.extend({
5044 className: 'media-router',
5045 property: 'contentMode',
5046 ItemView: media.view.RouterItem,
5049 initialize: function() {
5050 this.controller.on( 'content:render', this.update, this );
5051 // Call 'initialize' directly on the parent class.
5052 media.view.Menu.prototype.initialize.apply( this, arguments );
5055 update: function() {
5056 var mode = this.controller.content.mode();
5058 this.select( mode );
5064 * wp.media.view.Sidebar
5067 * @augments wp.media.view.PriorityList
5068 * @augments wp.media.View
5069 * @augments wp.Backbone.View
5070 * @augments Backbone.View
5072 media.view.Sidebar = media.view.PriorityList.extend({
5073 className: 'media-sidebar'
5077 * wp.media.view.Attachment
5080 * @augments wp.media.View
5081 * @augments wp.Backbone.View
5082 * @augments Backbone.View
5084 media.view.Attachment = media.View.extend({
5086 className: 'attachment',
5087 template: media.template('attachment'),
5089 attributes: function() {
5093 'aria-label': this.model.get( 'title' ),
5094 'aria-checked': false,
5095 'data-id': this.model.get( 'id' )
5100 'click .js--select-attachment': 'toggleSelectionHandler',
5101 'change [data-setting]': 'updateSetting',
5102 'change [data-setting] input': 'updateSetting',
5103 'change [data-setting] select': 'updateSetting',
5104 'change [data-setting] textarea': 'updateSetting',
5105 'click .close': 'removeFromLibrary',
5106 'click .check': 'checkClickHandler',
5107 'click a': 'preventDefault',
5108 'keydown .close': 'removeFromLibrary',
5109 'keydown': 'toggleSelectionHandler'
5114 initialize: function() {
5115 var selection = this.options.selection,
5116 options = _.defaults( this.options, {
5117 rerenderOnModelChange: true
5120 if ( options.rerenderOnModelChange ) {
5121 this.model.on( 'change', this.render, this );
5123 this.model.on( 'change:percent', this.progress, this );
5125 this.model.on( 'change:title', this._syncTitle, this );
5126 this.model.on( 'change:caption', this._syncCaption, this );
5127 this.model.on( 'change:artist', this._syncArtist, this );
5128 this.model.on( 'change:album', this._syncAlbum, this );
5130 // Update the selection.
5131 this.model.on( 'add', this.select, this );
5132 this.model.on( 'remove', this.deselect, this );
5134 selection.on( 'reset', this.updateSelect, this );
5135 // Update the model's details view.
5136 this.model.on( 'selection:single selection:unsingle', this.details, this );
5137 this.details( this.model, this.controller.state().get('selection') );
5140 this.listenTo( this.controller, 'attachment:compat:waiting attachment:compat:ready', this.updateSave );
5143 * @returns {wp.media.view.Attachment} Returns itself to allow chaining
5145 dispose: function() {
5146 var selection = this.options.selection;
5148 // Make sure all settings are saved before removing the view.
5152 selection.off( null, null, this );
5155 * call 'dispose' directly on the parent class
5157 media.View.prototype.dispose.apply( this, arguments );
5161 * @returns {wp.media.view.Attachment} Returns itself to allow chaining
5163 render: function() {
5164 var options = _.defaults( this.model.toJSON(), {
5165 orientation: 'landscape',
5181 options.buttons = this.buttons;
5182 options.describe = this.controller.state().get('describe');
5184 if ( 'image' === options.type ) {
5185 options.size = this.imageSize();
5189 if ( options.nonces ) {
5190 options.can.remove = !! options.nonces['delete'];
5191 options.can.save = !! options.nonces.update;
5194 if ( this.controller.state().get('allowLocalEdits') ) {
5195 options.allowLocalEdits = true;
5198 if ( options.uploading && ! options.percent ) {
5199 options.percent = 0;
5202 this.views.detach();
5203 this.$el.html( this.template( options ) );
5205 this.$el.toggleClass( 'uploading', options.uploading );
5207 if ( options.uploading ) {
5208 this.$bar = this.$('.media-progress-bar div');
5213 // Check if the model is selected.
5214 this.updateSelect();
5216 // Update the save status.
5219 this.views.render();
5224 progress: function() {
5225 if ( this.$bar && this.$bar.length ) {
5226 this.$bar.width( this.model.get('percent') + '%' );
5231 * @param {Object} event
5233 toggleSelectionHandler: function( event ) {
5236 // Don't do anything inside inputs.
5237 if ( 'INPUT' === event.target.nodeName ) {
5241 // Catch arrow events
5242 if ( 37 === event.keyCode || 38 === event.keyCode || 39 === event.keyCode || 40 === event.keyCode ) {
5243 this.controller.trigger( 'attachment:keydown:arrow', event );
5247 // Catch enter and space events
5248 if ( 'keydown' === event.type && 13 !== event.keyCode && 32 !== event.keyCode ) {
5252 event.preventDefault();
5254 // In the grid view, bubble up an edit:attachment event to the controller.
5255 if ( this.controller.isModeActive( 'grid' ) ) {
5256 if ( this.controller.isModeActive( 'edit' ) ) {
5257 // Pass the current target to restore focus when closing
5258 this.controller.trigger( 'edit:attachment', this.model, event.currentTarget );
5262 if ( this.controller.isModeActive( 'select' ) ) {
5267 if ( event.shiftKey ) {
5269 } else if ( event.ctrlKey || event.metaKey ) {
5273 this.toggleSelection({
5277 this.controller.trigger( 'selection:toggle' );
5280 * @param {Object} options
5282 toggleSelection: function( options ) {
5283 var collection = this.collection,
5284 selection = this.options.selection,
5286 method = options && options.method,
5287 single, models, singleIndex, modelIndex;
5289 if ( ! selection ) {
5293 single = selection.single();
5294 method = _.isUndefined( method ) ? selection.multiple : method;
5296 // If the `method` is set to `between`, select all models that
5297 // exist between the current and the selected model.
5298 if ( 'between' === method && single && selection.multiple ) {
5299 // If the models are the same, short-circuit.
5300 if ( single === model ) {
5304 singleIndex = collection.indexOf( single );
5305 modelIndex = collection.indexOf( this.model );
5307 if ( singleIndex < modelIndex ) {
5308 models = collection.models.slice( singleIndex, modelIndex + 1 );
5310 models = collection.models.slice( modelIndex, singleIndex + 1 );
5313 selection.add( models );
5314 selection.single( model );
5317 // If the `method` is set to `toggle`, just flip the selection
5318 // status, regardless of whether the model is the single model.
5319 } else if ( 'toggle' === method ) {
5320 selection[ this.selected() ? 'remove' : 'add' ]( model );
5321 selection.single( model );
5323 } else if ( 'add' === method ) {
5324 selection.add( model );
5325 selection.single( model );
5329 // Fixes bug that loses focus when selecting a featured image
5334 if ( method !== 'add' ) {
5338 if ( this.selected() ) {
5339 // If the model is the single model, remove it.
5340 // If it is not the same as the single model,
5341 // it now becomes the single model.
5342 selection[ single === model ? 'remove' : 'single' ]( model );
5344 // If the model is not selected, run the `method` on the
5345 // selection. By default, we `reset` the selection, but the
5346 // `method` can be set to `add` the model to the selection.
5347 selection[ method ]( model );
5348 selection.single( model );
5352 updateSelect: function() {
5353 this[ this.selected() ? 'select' : 'deselect' ]();
5356 * @returns {unresolved|Boolean}
5358 selected: function() {
5359 var selection = this.options.selection;
5361 return !! selection.get( this.model.cid );
5365 * @param {Backbone.Model} model
5366 * @param {Backbone.Collection} collection
5368 select: function( model, collection ) {
5369 var selection = this.options.selection,
5370 controller = this.controller;
5372 // Check if a selection exists and if it's the collection provided.
5373 // If they're not the same collection, bail; we're in another
5374 // selection's event loop.
5375 if ( ! selection || ( collection && collection !== selection ) ) {
5379 // Bail if the model is already selected.
5380 if ( this.$el.hasClass( 'selected' ) ) {
5384 // Add 'selected' class to model, set aria-checked to true.
5385 this.$el.addClass( 'selected' ).attr( 'aria-checked', true );
5386 // Make the checkbox tabable, except in media grid (bulk select mode).
5387 if ( ! ( controller.isModeActive( 'grid' ) && controller.isModeActive( 'select' ) ) ) {
5388 this.$( '.check' ).attr( 'tabindex', '0' );
5392 * @param {Backbone.Model} model
5393 * @param {Backbone.Collection} collection
5395 deselect: function( model, collection ) {
5396 var selection = this.options.selection;
5398 // Check if a selection exists and if it's the collection provided.
5399 // If they're not the same collection, bail; we're in another
5400 // selection's event loop.
5401 if ( ! selection || ( collection && collection !== selection ) ) {
5404 this.$el.removeClass( 'selected' ).attr( 'aria-checked', false )
5405 .find( '.check' ).attr( 'tabindex', '-1' );
5408 * @param {Backbone.Model} model
5409 * @param {Backbone.Collection} collection
5411 details: function( model, collection ) {
5412 var selection = this.options.selection,
5415 if ( selection !== collection ) {
5419 details = selection.single();
5420 this.$el.toggleClass( 'details', details === this.model );
5423 * @param {Object} event
5425 preventDefault: function( event ) {
5426 event.preventDefault();
5429 * @param {string} size
5432 imageSize: function( size ) {
5433 var sizes = this.model.get('sizes');
5435 size = size || 'medium';
5437 // Use the provided image size if possible.
5438 if ( sizes && sizes[ size ] ) {
5439 return _.clone( sizes[ size ] );
5442 url: this.model.get('url'),
5443 width: this.model.get('width'),
5444 height: this.model.get('height'),
5445 orientation: this.model.get('orientation')
5450 * @param {Object} event
5452 updateSetting: function( event ) {
5453 var $setting = $( event.target ).closest('[data-setting]'),
5456 if ( ! $setting.length ) {
5460 setting = $setting.data('setting');
5461 value = event.target.value;
5463 if ( this.model.get( setting ) !== value ) {
5464 this.save( setting, value );
5469 * Pass all the arguments to the model's save method.
5471 * Records the aggregate status of all save requests and updates the
5472 * view's classes accordingly.
5476 save = this._save = this._save || { status: 'ready' },
5477 request = this.model.save.apply( this.model, arguments ),
5478 requests = save.requests ? $.when( request, save.requests ) : request;
5480 // If we're waiting to remove 'Saved.', stop.
5481 if ( save.savedTimer ) {
5482 clearTimeout( save.savedTimer );
5485 this.updateSave('waiting');
5486 save.requests = requests;
5487 requests.always( function() {
5488 // If we've performed another request since this one, bail.
5489 if ( save.requests !== requests ) {
5493 view.updateSave( requests.state() === 'resolved' ? 'complete' : 'error' );
5494 save.savedTimer = setTimeout( function() {
5495 view.updateSave('ready');
5496 delete save.savedTimer;
5501 * @param {string} status
5502 * @returns {wp.media.view.Attachment} Returns itself to allow chaining
5504 updateSave: function( status ) {
5505 var save = this._save = this._save || { status: 'ready' };
5507 if ( status && status !== save.status ) {
5508 this.$el.removeClass( 'save-' + save.status );
5509 save.status = status;
5512 this.$el.addClass( 'save-' + save.status );
5516 updateAll: function() {
5517 var $settings = this.$('[data-setting]'),
5521 changed = _.chain( $settings ).map( function( el ) {
5522 var $input = $('input, textarea, select, [value]', el ),
5525 if ( ! $input.length ) {
5529 setting = $(el).data('setting');
5530 value = $input.val();
5532 // Record the value if it changed.
5533 if ( model.get( setting ) !== value ) {
5534 return [ setting, value ];
5536 }).compact().object().value();
5538 if ( ! _.isEmpty( changed ) ) {
5539 model.save( changed );
5543 * @param {Object} event
5545 removeFromLibrary: function( event ) {
5546 // Catch enter and space events
5547 if ( 'keydown' === event.type && 13 !== event.keyCode && 32 !== event.keyCode ) {
5551 // Stop propagation so the model isn't selected.
5552 event.stopPropagation();
5554 this.collection.remove( this.model );
5558 * Add the model if it isn't in the selection, if it is in the selection,
5561 * @param {[type]} event [description]
5562 * @return {[type]} [description]
5564 checkClickHandler: function ( event ) {
5565 var selection = this.options.selection;
5566 if ( ! selection ) {
5569 event.stopPropagation();
5570 if ( selection.where( { id: this.model.get( 'id' ) } ).length ) {
5571 selection.remove( this.model );
5572 // Move focus back to the attachment tile (from the check).
5575 selection.add( this.model );
5580 // Ensure settings remain in sync between attachment views.
5582 caption: '_syncCaption',
5583 title: '_syncTitle',
5584 artist: '_syncArtist',
5586 }, function( method, setting ) {
5588 * @param {Backbone.Model} model
5589 * @param {string} value
5590 * @returns {wp.media.view.Attachment} Returns itself to allow chaining
5592 media.view.Attachment.prototype[ method ] = function( model, value ) {
5593 var $setting = this.$('[data-setting="' + setting + '"]');
5595 if ( ! $setting.length ) {
5599 // If the updated value is in sync with the value in the DOM, there
5600 // is no need to re-render. If we're currently editing the value,
5601 // it will automatically be in sync, suppressing the re-render for
5602 // the view we're editing, while updating any others.
5603 if ( value === $setting.find('input, textarea, select, [value]').val() ) {
5607 return this.render();
5612 * wp.media.view.Attachment.Library
5615 * @augments wp.media.view.Attachment
5616 * @augments wp.media.View
5617 * @augments wp.Backbone.View
5618 * @augments Backbone.View
5620 media.view.Attachment.Library = media.view.Attachment.extend({
5627 * wp.media.view.Attachment.EditLibrary
5630 * @augments wp.media.view.Attachment
5631 * @augments wp.media.View
5632 * @augments wp.Backbone.View
5633 * @augments Backbone.View
5635 media.view.Attachment.EditLibrary = media.view.Attachment.extend({
5642 * wp.media.view.Attachments
5645 * @augments wp.media.View
5646 * @augments wp.Backbone.View
5647 * @augments Backbone.View
5649 media.view.Attachments = media.View.extend({
5651 className: 'attachments',
5657 initialize: function() {
5658 this.el.id = _.uniqueId('__attachments-view-');
5660 _.defaults( this.options, {
5661 refreshSensitivity: isTouchDevice ? 300 : 200,
5662 refreshThreshold: 3,
5663 AttachmentView: media.view.Attachment,
5666 idealColumnWidth: $( window ).width() < 640 ? 135 : 150
5669 this._viewsByCid = {};
5670 this.$window = $( window );
5671 this.resizeEvent = 'resize.media-modal-columns';
5673 this.collection.on( 'add', function( attachment ) {
5674 this.views.add( this.createAttachmentView( attachment ), {
5675 at: this.collection.indexOf( attachment )
5679 this.collection.on( 'remove', function( attachment ) {
5680 var view = this._viewsByCid[ attachment.cid ];
5681 delete this._viewsByCid[ attachment.cid ];
5688 this.collection.on( 'reset', this.render, this );
5690 this.listenTo( this.controller, 'library:selection:add', this.attachmentFocus );
5692 // Throttle the scroll handler and bind this.
5693 this.scroll = _.chain( this.scroll ).bind( this ).throttle( this.options.refreshSensitivity ).value();
5695 this.options.scrollElement = this.options.scrollElement || this.el;
5696 $( this.options.scrollElement ).on( 'scroll', this.scroll );
5698 this.initSortable();
5700 _.bindAll( this, 'setColumns' );
5702 if ( this.options.resize ) {
5703 this.on( 'ready', this.bindEvents );
5704 this.controller.on( 'open', this.setColumns );
5706 // Call this.setColumns() after this view has been rendered in the DOM so
5707 // attachments get proper width applied.
5708 _.defer( this.setColumns, this );
5712 bindEvents: function() {
5713 this.$window.off( this.resizeEvent ).on( this.resizeEvent, _.debounce( this.setColumns, 50 ) );
5716 attachmentFocus: function() {
5717 this.$( 'li:first' ).focus();
5720 restoreFocus: function() {
5721 this.$( 'li.selected:first' ).focus();
5724 arrowEvent: function( event ) {
5725 var attachments = this.$el.children( 'li' ),
5726 perRow = this.columns,
5727 index = attachments.filter( ':focus' ).index(),
5728 row = ( index + 1 ) <= perRow ? 1 : Math.ceil( ( index + 1 ) / perRow );
5730 if ( index === -1 ) {
5735 if ( 37 === event.keyCode ) {
5736 if ( 0 === index ) {
5739 attachments.eq( index - 1 ).focus();
5743 if ( 38 === event.keyCode ) {
5747 attachments.eq( index - perRow ).focus();
5751 if ( 39 === event.keyCode ) {
5752 if ( attachments.length === index ) {
5755 attachments.eq( index + 1 ).focus();
5759 if ( 40 === event.keyCode ) {
5760 if ( Math.ceil( attachments.length / perRow ) === row ) {
5763 attachments.eq( index + perRow ).focus();
5767 dispose: function() {
5768 this.collection.props.off( null, null, this );
5769 if ( this.options.resize ) {
5770 this.$window.off( this.resizeEvent );
5774 * call 'dispose' directly on the parent class
5776 media.View.prototype.dispose.apply( this, arguments );
5779 setColumns: function() {
5780 var prev = this.columns,
5781 width = this.$el.width();
5784 this.columns = Math.min( Math.round( width / this.options.idealColumnWidth ), 12 ) || 1;
5786 if ( ! prev || prev !== this.columns ) {
5787 this.$el.closest( '.media-frame-content' ).attr( 'data-columns', this.columns );
5792 initSortable: function() {
5793 var collection = this.collection;
5795 if ( isTouchDevice || ! this.options.sortable || ! $.fn.sortable ) {
5799 this.$el.sortable( _.extend({
5800 // If the `collection` has a `comparator`, disable sorting.
5801 disabled: !! collection.comparator,
5803 // Change the position of the attachment as soon as the
5804 // mouse pointer overlaps a thumbnail.
5805 tolerance: 'pointer',
5807 // Record the initial `index` of the dragged model.
5808 start: function( event, ui ) {
5809 ui.item.data('sortableIndexStart', ui.item.index());
5812 // Update the model's index in the collection.
5813 // Do so silently, as the view is already accurate.
5814 update: function( event, ui ) {
5815 var model = collection.at( ui.item.data('sortableIndexStart') ),
5816 comparator = collection.comparator;
5818 // Temporarily disable the comparator to prevent `add`
5820 delete collection.comparator;
5822 // Silently shift the model to its new index.
5823 collection.remove( model, {
5826 collection.add( model, {
5831 // Restore the comparator.
5832 collection.comparator = comparator;
5834 // Fire the `reset` event to ensure other collections sync.
5835 collection.trigger( 'reset', collection );
5837 // If the collection is sorted by menu order,
5838 // update the menu order.
5839 collection.saveMenuOrder();
5841 }, this.options.sortable ) );
5843 // If the `orderby` property is changed on the `collection`,
5844 // check to see if we have a `comparator`. If so, disable sorting.
5845 collection.props.on( 'change:orderby', function() {
5846 this.$el.sortable( 'option', 'disabled', !! collection.comparator );
5849 this.collection.props.on( 'change:orderby', this.refreshSortable, this );
5850 this.refreshSortable();
5853 refreshSortable: function() {
5854 if ( isTouchDevice || ! this.options.sortable || ! $.fn.sortable ) {
5858 // If the `collection` has a `comparator`, disable sorting.
5859 var collection = this.collection,
5860 orderby = collection.props.get('orderby'),
5861 enabled = 'menuOrder' === orderby || ! collection.comparator;
5863 this.$el.sortable( 'option', 'disabled', ! enabled );
5867 * @param {wp.media.model.Attachment} attachment
5868 * @returns {wp.media.View}
5870 createAttachmentView: function( attachment ) {
5871 var view = new this.options.AttachmentView({
5872 controller: this.controller,
5874 collection: this.collection,
5875 selection: this.options.selection
5878 return this._viewsByCid[ attachment.cid ] = view;
5881 prepare: function() {
5882 // Create all of the Attachment views, and replace
5883 // the list in a single DOM operation.
5884 if ( this.collection.length ) {
5885 this.views.set( this.collection.map( this.createAttachmentView, this ) );
5887 // If there are no elements, clear the views and load some.
5890 this.collection.more().done( this.scroll );
5895 // Trigger the scroll event to check if we're within the
5896 // threshold to query for additional attachments.
5900 scroll: function() {
5902 el = this.options.scrollElement,
5903 scrollTop = el.scrollTop,
5906 // The scroll event occurs on the document, but the element
5907 // that should be checked is the document body.
5908 if ( el == document ) {
5910 scrollTop = $(document).scrollTop();
5913 if ( ! $(el).is(':visible') || ! this.collection.hasMore() ) {
5917 toolbar = this.views.parent.toolbar;
5919 // Show the spinner only if we are close to the bottom.
5920 if ( el.scrollHeight - ( scrollTop + el.clientHeight ) < el.clientHeight / 3 ) {
5921 toolbar.get('spinner').show();
5924 if ( el.scrollHeight < scrollTop + ( el.clientHeight * this.options.refreshThreshold ) ) {
5925 this.collection.more().done(function() {
5927 toolbar.get('spinner').hide();
5934 * wp.media.view.Search
5937 * @augments wp.media.View
5938 * @augments wp.Backbone.View
5939 * @augments Backbone.View
5941 media.view.Search = media.View.extend({
5943 className: 'search',
5944 id: 'media-search-input',
5948 placeholder: l10n.search
5959 * @returns {wp.media.view.Search} Returns itself to allow chaining
5961 render: function() {
5962 this.el.value = this.model.escape('search');
5966 search: function( event ) {
5967 if ( event.target.value ) {
5968 this.model.set( 'search', event.target.value );
5970 this.model.unset('search');
5976 * wp.media.view.AttachmentFilters
5979 * @augments wp.media.View
5980 * @augments wp.Backbone.View
5981 * @augments Backbone.View
5983 media.view.AttachmentFilters = media.View.extend({
5985 className: 'attachment-filters',
5986 id: 'media-attachment-filters',
5994 initialize: function() {
5995 this.createFilters();
5996 _.extend( this.filters, this.options.filters );
5998 // Build `<option>` elements.
5999 this.$el.html( _.chain( this.filters ).map( function( filter, value ) {
6001 el: $( '<option></option>' ).val( value ).html( filter.text )[0],
6002 priority: filter.priority || 50
6004 }, this ).sortBy('priority').pluck('el').value() );
6006 this.model.on( 'change', this.select, this );
6013 createFilters: function() {
6018 * When the selected filter changes, update the Attachment Query properties to match.
6020 change: function() {
6021 var filter = this.filters[ this.el.value ];
6023 this.model.set( filter.props );
6027 select: function() {
6028 var model = this.model,
6030 props = model.toJSON();
6032 _.find( this.filters, function( filter, id ) {
6033 var equal = _.all( filter.props, function( prop, key ) {
6034 return prop === ( _.isUndefined( props[ key ] ) ? null : props[ key ] );
6042 this.$el.val( value );
6047 * A filter dropdown for month/dates.
6050 * @augments wp.media.view.AttachmentFilters
6051 * @augments wp.media.View
6052 * @augments wp.Backbone.View
6053 * @augments Backbone.View
6055 media.view.DateFilter = media.view.AttachmentFilters.extend({
6056 id: 'media-attachment-date-filters',
6058 createFilters: function() {
6060 _.each( media.view.settings.months || {}, function( value, index ) {
6061 filters[ index ] = {
6065 monthnum: value.month
6070 text: l10n.allDates,
6077 this.filters = filters;
6082 * wp.media.view.AttachmentFilters.Uploaded
6085 * @augments wp.media.view.AttachmentFilters
6086 * @augments wp.media.View
6087 * @augments wp.Backbone.View
6088 * @augments Backbone.View
6090 media.view.AttachmentFilters.Uploaded = media.view.AttachmentFilters.extend({
6091 createFilters: function() {
6092 var type = this.model.get('type'),
6093 types = media.view.settings.mimeTypes,
6096 if ( types && type ) {
6097 text = types[ type ];
6102 text: text || l10n.allMediaItems,
6112 text: l10n.uploadedToThisPost,
6114 uploadedTo: media.view.settings.post.id,
6115 orderby: 'menuOrder',
6122 text: l10n.unattached,
6125 orderby: 'menuOrder',
6135 * wp.media.view.AttachmentFilters.All
6138 * @augments wp.media.view.AttachmentFilters
6139 * @augments wp.media.View
6140 * @augments wp.Backbone.View
6141 * @augments Backbone.View
6143 media.view.AttachmentFilters.All = media.view.AttachmentFilters.extend({
6144 createFilters: function() {
6147 _.each( media.view.settings.mimeTypes || {}, function( text, key ) {
6161 text: l10n.allMediaItems,
6172 if ( media.view.settings.post.id ) {
6173 filters.uploaded = {
6174 text: l10n.uploadedToThisPost,
6178 uploadedTo: media.view.settings.post.id,
6179 orderby: 'menuOrder',
6186 filters.unattached = {
6187 text: l10n.unattached,
6192 orderby: 'menuOrder',
6198 if ( media.view.settings.mediaTrash &&
6199 this.controller.isModeActive( 'grid' ) ) {
6214 this.filters = filters;
6219 * wp.media.view.AttachmentsBrowser
6222 * @augments wp.media.View
6223 * @augments wp.Backbone.View
6224 * @augments Backbone.View
6226 * @param {object} options
6227 * @param {object} [options.filters=false] Which filters to show in the browser's toolbar.
6228 * Accepts 'uploaded' and 'all'.
6229 * @param {object} [options.search=true] Whether to show the search interface in the
6230 * browser's toolbar.
6231 * @param {object} [options.date=true] Whether to show the date filter in the
6232 * browser's toolbar.
6233 * @param {object} [options.display=false] Whether to show the attachments display settings
6234 * view in the sidebar.
6235 * @param {bool|string} [options.sidebar=true] Whether to create a sidebar for the browser.
6236 * Accepts true, false, and 'errors'.
6238 media.view.AttachmentsBrowser = media.View.extend({
6240 className: 'attachments-browser',
6242 initialize: function() {
6243 _.defaults( this.options, {
6249 AttachmentView: media.view.Attachment.Library
6252 this.listenTo( this.controller, 'toggle:upload:attachment', _.bind( this.toggleUploader, this ) );
6253 this.controller.on( 'edit:selection', this.editSelection );
6254 this.createToolbar();
6255 if ( this.options.sidebar ) {
6256 this.createSidebar();
6258 this.createUploader();
6259 this.createAttachments();
6260 this.updateContent();
6262 if ( ! this.options.sidebar || 'errors' === this.options.sidebar ) {
6263 this.$el.addClass( 'hide-sidebar' );
6265 if ( 'errors' === this.options.sidebar ) {
6266 this.$el.addClass( 'sidebar-for-errors' );
6270 this.collection.on( 'add remove reset', this.updateContent, this );
6273 editSelection: function( modal ) {
6274 modal.$( '.media-button-backToLibrary' ).focus();
6278 * @returns {wp.media.view.AttachmentsBrowser} Returns itself to allow chaining
6280 dispose: function() {
6281 this.options.selection.off( null, null, this );
6282 media.View.prototype.dispose.apply( this, arguments );
6286 createToolbar: function() {
6287 var LibraryViewSwitcher, Filters, toolbarOptions;
6290 controller: this.controller
6293 if ( this.controller.isModeActive( 'grid' ) ) {
6294 toolbarOptions.className = 'media-toolbar wp-filter';
6298 * @member {wp.media.view.Toolbar}
6300 this.toolbar = new media.view.Toolbar( toolbarOptions );
6302 this.views.add( this.toolbar );
6304 this.toolbar.set( 'spinner', new media.view.Spinner({
6308 if ( -1 !== $.inArray( this.options.filters, [ 'uploaded', 'all' ] ) ) {
6309 // "Filters" will return a <select>, need to render
6310 // screen reader text before
6311 this.toolbar.set( 'filtersLabel', new media.view.Label({
6312 value: l10n.filterByType,
6314 'for': 'media-attachment-filters'
6319 if ( 'uploaded' === this.options.filters ) {
6320 this.toolbar.set( 'filters', new media.view.AttachmentFilters.Uploaded({
6321 controller: this.controller,
6322 model: this.collection.props,
6326 Filters = new media.view.AttachmentFilters.All({
6327 controller: this.controller,
6328 model: this.collection.props,
6332 this.toolbar.set( 'filters', Filters.render() );
6336 // Feels odd to bring the global media library switcher into the Attachment
6337 // browser view. Is this a use case for doAction( 'add:toolbar-items:attachments-browser', this.toolbar );
6338 // which the controller can tap into and add this view?
6339 if ( this.controller.isModeActive( 'grid' ) ) {
6340 LibraryViewSwitcher = media.View.extend({
6341 className: 'view-switch media-grid-view-switch',
6342 template: media.template( 'media-library-view-switcher')
6345 this.toolbar.set( 'libraryViewSwitcher', new LibraryViewSwitcher({
6346 controller: this.controller,
6350 // DateFilter is a <select>, screen reader text needs to be rendered before
6351 this.toolbar.set( 'dateFilterLabel', new media.view.Label({
6352 value: l10n.filterByDate,
6354 'for': 'media-attachment-date-filters'
6358 this.toolbar.set( 'dateFilter', new media.view.DateFilter({
6359 controller: this.controller,
6360 model: this.collection.props,
6364 // BulkSelection is a <div> with subviews, including screen reader text
6365 this.toolbar.set( 'selectModeToggleButton', new media.view.SelectModeToggleButton({
6366 text: l10n.bulkSelect,
6367 controller: this.controller,
6371 this.toolbar.set( 'deleteSelectedButton', new media.view.DeleteSelectedButton({
6375 text: media.view.settings.mediaTrash ? l10n.trashSelected : l10n.deleteSelected,
6376 controller: this.controller,
6379 var changed = [], removed = [], self = this,
6380 selection = this.controller.state().get( 'selection' ),
6381 library = this.controller.state().get( 'library' );
6383 if ( ! selection.length ) {
6387 if ( ! media.view.settings.mediaTrash && ! confirm( l10n.warnBulkDelete ) ) {
6391 if ( media.view.settings.mediaTrash &&
6392 'trash' !== selection.at( 0 ).get( 'status' ) &&
6393 ! confirm( l10n.warnBulkTrash ) ) {
6398 selection.each( function( model ) {
6399 if ( ! model.get( 'nonces' )['delete'] ) {
6400 removed.push( model );
6404 if ( media.view.settings.mediaTrash && 'trash' === model.get( 'status' ) ) {
6405 model.set( 'status', 'inherit' );
6406 changed.push( model.save() );
6407 removed.push( model );
6408 } else if ( media.view.settings.mediaTrash ) {
6409 model.set( 'status', 'trash' );
6410 changed.push( model.save() );
6411 removed.push( model );
6413 model.destroy({wait: true});
6417 if ( changed.length ) {
6418 selection.remove( removed );
6420 $.when.apply( null, changed ).then( function() {
6421 library._requery( true );
6422 self.controller.trigger( 'selection:action:done' );
6425 this.controller.trigger( 'selection:action:done' );
6430 if ( media.view.settings.mediaTrash ) {
6431 this.toolbar.set( 'deleteSelectedPermanentlyButton', new media.view.DeleteSelectedPermanentlyButton({
6435 text: l10n.deleteSelected,
6436 controller: this.controller,
6439 var removed = [], selection = this.controller.state().get( 'selection' );
6441 if ( ! selection.length || ! confirm( l10n.warnBulkDelete ) ) {
6445 selection.each( function( model ) {
6446 if ( ! model.get( 'nonces' )['delete'] ) {
6447 removed.push( model );
6454 selection.remove( removed );
6455 this.controller.trigger( 'selection:action:done' );
6460 } else if ( this.options.date ) {
6461 // DateFilter is a <select>, screen reader text needs to be rendered before
6462 this.toolbar.set( 'dateFilterLabel', new media.view.Label({
6463 value: l10n.filterByDate,
6465 'for': 'media-attachment-date-filters'
6469 this.toolbar.set( 'dateFilter', new media.view.DateFilter({
6470 controller: this.controller,
6471 model: this.collection.props,
6476 if ( this.options.search ) {
6477 // Search is an input, screen reader text needs to be rendered before
6478 this.toolbar.set( 'searchLabel', new media.view.Label({
6479 value: l10n.searchMediaLabel,
6481 'for': 'media-search-input'
6485 this.toolbar.set( 'search', new media.view.Search({
6486 controller: this.controller,
6487 model: this.collection.props,
6492 if ( this.options.dragInfo ) {
6493 this.toolbar.set( 'dragInfo', new media.View({
6494 el: $( '<div class="instructions">' + l10n.dragInfo + '</div>' )[0],
6499 if ( this.options.suggestedWidth && this.options.suggestedHeight ) {
6500 this.toolbar.set( 'suggestedDimensions', new media.View({
6501 el: $( '<div class="instructions">' + l10n.suggestedDimensions + ' ' + this.options.suggestedWidth + ' × ' + this.options.suggestedHeight + '</div>' )[0],
6507 updateContent: function() {
6511 if ( this.controller.isModeActive( 'grid' ) ) {
6512 noItemsView = view.attachmentsNoResults;
6514 noItemsView = view.uploader;
6517 if ( ! this.collection.length ) {
6518 this.toolbar.get( 'spinner' ).show();
6519 this.dfd = this.collection.more().done( function() {
6520 if ( ! view.collection.length ) {
6521 noItemsView.$el.removeClass( 'hidden' );
6523 noItemsView.$el.addClass( 'hidden' );
6525 view.toolbar.get( 'spinner' ).hide();
6528 noItemsView.$el.addClass( 'hidden' );
6529 view.toolbar.get( 'spinner' ).hide();
6533 createUploader: function() {
6534 this.uploader = new media.view.UploaderInline({
6535 controller: this.controller,
6537 message: this.controller.isModeActive( 'grid' ) ? '' : l10n.noItemsFound,
6538 canClose: this.controller.isModeActive( 'grid' )
6541 this.uploader.hide();
6542 this.views.add( this.uploader );
6545 toggleUploader: function() {
6546 if ( this.uploader.$el.hasClass( 'hidden' ) ) {
6547 this.uploader.show();
6549 this.uploader.hide();
6553 createAttachments: function() {
6554 this.attachments = new media.view.Attachments({
6555 controller: this.controller,
6556 collection: this.collection,
6557 selection: this.options.selection,
6559 sortable: this.options.sortable,
6560 scrollElement: this.options.scrollElement,
6561 idealColumnWidth: this.options.idealColumnWidth,
6563 // The single `Attachment` view to be used in the `Attachments` view.
6564 AttachmentView: this.options.AttachmentView
6567 // Add keydown listener to the instance of the Attachments view
6568 this.attachments.listenTo( this.controller, 'attachment:keydown:arrow', this.attachments.arrowEvent );
6569 this.attachments.listenTo( this.controller, 'attachment:details:shift-tab', this.attachments.restoreFocus );
6571 this.views.add( this.attachments );
6574 if ( this.controller.isModeActive( 'grid' ) ) {
6575 this.attachmentsNoResults = new media.View({
6576 controller: this.controller,
6580 this.attachmentsNoResults.$el.addClass( 'hidden no-media' );
6581 this.attachmentsNoResults.$el.html( l10n.noMedia );
6583 this.views.add( this.attachmentsNoResults );
6587 createSidebar: function() {
6588 var options = this.options,
6589 selection = options.selection,
6590 sidebar = this.sidebar = new media.view.Sidebar({
6591 controller: this.controller
6594 this.views.add( sidebar );
6596 if ( this.controller.uploader ) {
6597 sidebar.set( 'uploads', new media.view.UploaderStatus({
6598 controller: this.controller,
6603 selection.on( 'selection:single', this.createSingle, this );
6604 selection.on( 'selection:unsingle', this.disposeSingle, this );
6606 if ( selection.single() ) {
6607 this.createSingle();
6611 createSingle: function() {
6612 var sidebar = this.sidebar,
6613 single = this.options.selection.single();
6615 sidebar.set( 'details', new media.view.Attachment.Details({
6616 controller: this.controller,
6621 sidebar.set( 'compat', new media.view.AttachmentCompat({
6622 controller: this.controller,
6627 if ( this.options.display ) {
6628 sidebar.set( 'display', new media.view.Settings.AttachmentDisplay({
6629 controller: this.controller,
6630 model: this.model.display( single ),
6633 userSettings: this.model.get('displayUserSettings')
6637 // Show the sidebar on mobile
6638 if ( this.model.id === 'insert' ) {
6639 sidebar.$el.addClass( 'visible' );
6643 disposeSingle: function() {
6644 var sidebar = this.sidebar;
6645 sidebar.unset('details');
6646 sidebar.unset('compat');
6647 sidebar.unset('display');
6648 // Hide the sidebar on mobile
6649 sidebar.$el.removeClass( 'visible' );
6654 * wp.media.view.Selection
6657 * @augments wp.media.View
6658 * @augments wp.Backbone.View
6659 * @augments Backbone.View
6661 media.view.Selection = media.View.extend({
6663 className: 'media-selection',
6664 template: media.template('media-selection'),
6667 'click .edit-selection': 'edit',
6668 'click .clear-selection': 'clear'
6671 initialize: function() {
6672 _.defaults( this.options, {
6678 * @member {wp.media.view.Attachments.Selection}
6680 this.attachments = new media.view.Attachments.Selection({
6681 controller: this.controller,
6682 collection: this.collection,
6683 selection: this.collection,
6684 model: new Backbone.Model()
6687 this.views.set( '.selection-view', this.attachments );
6688 this.collection.on( 'add remove reset', this.refresh, this );
6689 this.controller.on( 'content:activate', this.refresh, this );
6696 refresh: function() {
6697 // If the selection hasn't been rendered, bail.
6698 if ( ! this.$el.children().length ) {
6702 var collection = this.collection,
6703 editing = 'edit-selection' === this.controller.content.mode();
6705 // If nothing is selected, display nothing.
6706 this.$el.toggleClass( 'empty', ! collection.length );
6707 this.$el.toggleClass( 'one', 1 === collection.length );
6708 this.$el.toggleClass( 'editing', editing );
6710 this.$('.count').text( l10n.selected.replace('%d', collection.length) );
6713 edit: function( event ) {
6714 event.preventDefault();
6715 if ( this.options.editable ) {
6716 this.options.editable.call( this, this.collection );
6720 clear: function( event ) {
6721 event.preventDefault();
6722 this.collection.reset();
6724 // Keep focus inside media modal
6725 // after clear link is selected
6726 this.controller.modal.focusManager.focus();
6732 * wp.media.view.Attachment.Selection
6735 * @augments wp.media.view.Attachment
6736 * @augments wp.media.View
6737 * @augments wp.Backbone.View
6738 * @augments Backbone.View
6740 media.view.Attachment.Selection = media.view.Attachment.extend({
6741 className: 'attachment selection',
6743 // On click, just select the model, instead of removing the model from
6745 toggleSelection: function() {
6746 this.options.selection.single( this.model );
6751 * wp.media.view.Attachments.Selection
6754 * @augments wp.media.view.Attachments
6755 * @augments wp.media.View
6756 * @augments wp.Backbone.View
6757 * @augments Backbone.View
6759 media.view.Attachments.Selection = media.view.Attachments.extend({
6761 initialize: function() {
6762 _.defaults( this.options, {
6766 // The single `Attachment` view to be used in the `Attachments` view.
6767 AttachmentView: media.view.Attachment.Selection
6769 // Call 'initialize' directly on the parent class.
6770 return media.view.Attachments.prototype.initialize.apply( this, arguments );
6775 * wp.media.view.Attachments.EditSelection
6778 * @augments wp.media.view.Attachment.Selection
6779 * @augments wp.media.view.Attachment
6780 * @augments wp.media.View
6781 * @augments wp.Backbone.View
6782 * @augments Backbone.View
6784 media.view.Attachment.EditSelection = media.view.Attachment.Selection.extend({
6792 * wp.media.view.Settings
6795 * @augments wp.media.View
6796 * @augments wp.Backbone.View
6797 * @augments Backbone.View
6799 media.view.Settings = media.View.extend({
6801 'click button': 'updateHandler',
6802 'change input': 'updateHandler',
6803 'change select': 'updateHandler',
6804 'change textarea': 'updateHandler'
6807 initialize: function() {
6808 this.model = this.model || new Backbone.Model();
6809 this.model.on( 'change', this.updateChanges, this );
6812 prepare: function() {
6814 model: this.model.toJSON()
6818 * @returns {wp.media.view.Settings} Returns itself to allow chaining
6820 render: function() {
6821 media.View.prototype.render.apply( this, arguments );
6822 // Select the correct values.
6823 _( this.model.attributes ).chain().keys().each( this.update, this );
6827 * @param {string} key
6829 update: function( key ) {
6830 var value = this.model.get( key ),
6831 $setting = this.$('[data-setting="' + key + '"]'),
6834 // Bail if we didn't find a matching setting.
6835 if ( ! $setting.length ) {
6839 // Attempt to determine how the setting is rendered and update
6840 // the selected value.
6842 // Handle dropdowns.
6843 if ( $setting.is('select') ) {
6844 $value = $setting.find('[value="' + value + '"]');
6846 if ( $value.length ) {
6847 $setting.find('option').prop( 'selected', false );
6848 $value.prop( 'selected', true );
6850 // If we can't find the desired value, record what *is* selected.
6851 this.model.set( key, $setting.find(':selected').val() );
6854 // Handle button groups.
6855 } else if ( $setting.hasClass('button-group') ) {
6856 $buttons = $setting.find('button').removeClass('active');
6857 $buttons.filter( '[value="' + value + '"]' ).addClass('active');
6859 // Handle text inputs and textareas.
6860 } else if ( $setting.is('input[type="text"], textarea') ) {
6861 if ( ! $setting.is(':focus') ) {
6862 $setting.val( value );
6864 // Handle checkboxes.
6865 } else if ( $setting.is('input[type="checkbox"]') ) {
6866 $setting.prop( 'checked', !! value && 'false' !== value );
6870 * @param {Object} event
6872 updateHandler: function( event ) {
6873 var $setting = $( event.target ).closest('[data-setting]'),
6874 value = event.target.value,
6877 event.preventDefault();
6879 if ( ! $setting.length ) {
6883 // Use the correct value for checkboxes.
6884 if ( $setting.is('input[type="checkbox"]') ) {
6885 value = $setting[0].checked;
6888 // Update the corresponding setting.
6889 this.model.set( $setting.data('setting'), value );
6891 // If the setting has a corresponding user setting,
6892 // update that as well.
6893 if ( userSetting = $setting.data('userSetting') ) {
6894 setUserSetting( userSetting, value );
6898 updateChanges: function( model ) {
6899 if ( model.hasChanged() ) {
6900 _( model.changed ).chain().keys().each( this.update, this );
6906 * wp.media.view.Settings.AttachmentDisplay
6909 * @augments wp.media.view.Settings
6910 * @augments wp.media.View
6911 * @augments wp.Backbone.View
6912 * @augments Backbone.View
6914 media.view.Settings.AttachmentDisplay = media.view.Settings.extend({
6915 className: 'attachment-display-settings',
6916 template: media.template('attachment-display-settings'),
6918 initialize: function() {
6919 var attachment = this.options.attachment;
6921 _.defaults( this.options, {
6924 // Call 'initialize' directly on the parent class.
6925 media.view.Settings.prototype.initialize.apply( this, arguments );
6926 this.model.on( 'change:link', this.updateLinkTo, this );
6929 attachment.on( 'change:uploading', this.render, this );
6933 dispose: function() {
6934 var attachment = this.options.attachment;
6936 attachment.off( null, null, this );
6939 * call 'dispose' directly on the parent class
6941 media.view.Settings.prototype.dispose.apply( this, arguments );
6944 * @returns {wp.media.view.AttachmentDisplay} Returns itself to allow chaining
6946 render: function() {
6947 var attachment = this.options.attachment;
6949 _.extend( this.options, {
6950 sizes: attachment.get('sizes'),
6951 type: attachment.get('type')
6955 * call 'render' directly on the parent class
6957 media.view.Settings.prototype.render.call( this );
6958 this.updateLinkTo();
6962 updateLinkTo: function() {
6963 var linkTo = this.model.get('link'),
6964 $input = this.$('.link-to-custom'),
6965 attachment = this.options.attachment;
6967 if ( 'none' === linkTo || 'embed' === linkTo || ( ! attachment && 'custom' !== linkTo ) ) {
6968 $input.addClass( 'hidden' );
6973 if ( 'post' === linkTo ) {
6974 $input.val( attachment.get('link') );
6975 } else if ( 'file' === linkTo ) {
6976 $input.val( attachment.get('url') );
6977 } else if ( ! this.model.get('linkUrl') ) {
6978 $input.val('http://');
6981 $input.prop( 'readonly', 'custom' !== linkTo );
6984 $input.removeClass( 'hidden' );
6986 // If the input is visible, focus and select its contents.
6987 if ( ! isTouchDevice && $input.is(':visible') ) {
6988 $input.focus()[0].select();
6994 * wp.media.view.Settings.Gallery
6997 * @augments wp.media.view.Settings
6998 * @augments wp.media.View
6999 * @augments wp.Backbone.View
7000 * @augments Backbone.View
7002 media.view.Settings.Gallery = media.view.Settings.extend({
7003 className: 'collection-settings gallery-settings',
7004 template: media.template('gallery-settings')
7008 * wp.media.view.Settings.Playlist
7011 * @augments wp.media.view.Settings
7012 * @augments wp.media.View
7013 * @augments wp.Backbone.View
7014 * @augments Backbone.View
7016 media.view.Settings.Playlist = media.view.Settings.extend({
7017 className: 'collection-settings playlist-settings',
7018 template: media.template('playlist-settings')
7022 * wp.media.view.Attachment.Details
7025 * @augments wp.media.view.Attachment
7026 * @augments wp.media.View
7027 * @augments wp.Backbone.View
7028 * @augments Backbone.View
7030 media.view.Attachment.Details = media.view.Attachment.extend({
7032 className: 'attachment-details',
7033 template: media.template('attachment-details'),
7035 attributes: function() {
7038 'data-id': this.model.get( 'id' )
7043 'change [data-setting]': 'updateSetting',
7044 'change [data-setting] input': 'updateSetting',
7045 'change [data-setting] select': 'updateSetting',
7046 'change [data-setting] textarea': 'updateSetting',
7047 'click .delete-attachment': 'deleteAttachment',
7048 'click .trash-attachment': 'trashAttachment',
7049 'click .untrash-attachment': 'untrashAttachment',
7050 'click .edit-attachment': 'editAttachment',
7051 'click .refresh-attachment': 'refreshAttachment',
7052 'keydown': 'toggleSelectionHandler'
7055 initialize: function() {
7056 this.options = _.defaults( this.options, {
7057 rerenderOnModelChange: false
7060 this.on( 'ready', this.initialFocus );
7061 // Call 'initialize' directly on the parent class.
7062 media.view.Attachment.prototype.initialize.apply( this, arguments );
7065 initialFocus: function() {
7066 if ( ! isTouchDevice ) {
7067 this.$( ':input' ).eq( 0 ).focus();
7071 * @param {Object} event
7073 deleteAttachment: function( event ) {
7074 event.preventDefault();
7076 if ( confirm( l10n.warnDelete ) ) {
7077 this.model.destroy();
7078 // Keep focus inside media modal
7079 // after image is deleted
7080 this.controller.modal.focusManager.focus();
7084 * @param {Object} event
7086 trashAttachment: function( event ) {
7087 var library = this.controller.library;
7088 event.preventDefault();
7090 if ( media.view.settings.mediaTrash &&
7091 'edit-metadata' === this.controller.content.mode() ) {
7093 this.model.set( 'status', 'trash' );
7094 this.model.save().done( function() {
7095 library._requery( true );
7098 this.model.destroy();
7102 * @param {Object} event
7104 untrashAttachment: function( event ) {
7105 var library = this.controller.library;
7106 event.preventDefault();
7108 this.model.set( 'status', 'inherit' );
7109 this.model.save().done( function() {
7110 library._requery( true );
7114 * @param {Object} event
7116 editAttachment: function( event ) {
7117 var editState = this.controller.states.get( 'edit-image' );
7118 if ( window.imageEdit && editState ) {
7119 event.preventDefault();
7121 editState.set( 'image', this.model );
7122 this.controller.setState( 'edit-image' );
7124 this.$el.addClass('needs-refresh');
7128 * @param {Object} event
7130 refreshAttachment: function( event ) {
7131 this.$el.removeClass('needs-refresh');
7132 event.preventDefault();
7136 * When reverse tabbing(shift+tab) out of the right details panel, deliver
7137 * the focus to the item in the list that was being edited.
7139 * @param {Object} event
7141 toggleSelectionHandler: function( event ) {
7142 if ( 'keydown' === event.type && 9 === event.keyCode && event.shiftKey && event.target === this.$( ':tabbable' ).get( 0 ) ) {
7143 this.controller.trigger( 'attachment:details:shift-tab', event );
7147 if ( 37 === event.keyCode || 38 === event.keyCode || 39 === event.keyCode || 40 === event.keyCode ) {
7148 this.controller.trigger( 'attachment:keydown:arrow', event );
7155 * wp.media.view.AttachmentCompat
7157 * A view to display fields added via the `attachment_fields_to_edit` filter.
7160 * @augments wp.media.View
7161 * @augments wp.Backbone.View
7162 * @augments Backbone.View
7164 media.view.AttachmentCompat = media.View.extend({
7166 className: 'compat-item',
7169 'submit': 'preventDefault',
7170 'change input': 'save',
7171 'change select': 'save',
7172 'change textarea': 'save'
7175 initialize: function() {
7176 this.model.on( 'change:compat', this.render, this );
7179 * @returns {wp.media.view.AttachmentCompat} Returns itself to allow chaining
7181 dispose: function() {
7182 if ( this.$(':focus').length ) {
7186 * call 'dispose' directly on the parent class
7188 return media.View.prototype.dispose.apply( this, arguments );
7191 * @returns {wp.media.view.AttachmentCompat} Returns itself to allow chaining
7193 render: function() {
7194 var compat = this.model.get('compat');
7195 if ( ! compat || ! compat.item ) {
7199 this.views.detach();
7200 this.$el.html( compat.item );
7201 this.views.render();
7205 * @param {Object} event
7207 preventDefault: function( event ) {
7208 event.preventDefault();
7211 * @param {Object} event
7213 save: function( event ) {
7217 event.preventDefault();
7220 _.each( this.$el.serializeArray(), function( pair ) {
7221 data[ pair.name ] = pair.value;
7224 this.controller.trigger( 'attachment:compat:waiting', ['waiting'] );
7225 this.model.saveCompat( data ).always( _.bind( this.postSave, this ) );
7228 postSave: function() {
7229 this.controller.trigger( 'attachment:compat:ready', ['ready'] );
7234 * wp.media.view.Iframe
7237 * @augments wp.media.View
7238 * @augments wp.Backbone.View
7239 * @augments Backbone.View
7241 media.view.Iframe = media.View.extend({
7242 className: 'media-iframe',
7244 * @returns {wp.media.view.Iframe} Returns itself to allow chaining
7246 render: function() {
7247 this.views.detach();
7248 this.$el.html( '<iframe src="' + this.controller.state().get('src') + '" />' );
7249 this.views.render();
7255 * wp.media.view.Embed
7258 * @augments wp.media.View
7259 * @augments wp.Backbone.View
7260 * @augments Backbone.View
7262 media.view.Embed = media.View.extend({
7263 className: 'media-embed',
7265 initialize: function() {
7267 * @member {wp.media.view.EmbedUrl}
7269 this.url = new media.view.EmbedUrl({
7270 controller: this.controller,
7271 model: this.model.props
7274 this.views.set([ this.url ]);
7276 this.model.on( 'change:type', this.refresh, this );
7277 this.model.on( 'change:loading', this.loading, this );
7281 * @param {Object} view
7283 settings: function( view ) {
7284 if ( this._settings ) {
7285 this._settings.remove();
7287 this._settings = view;
7288 this.views.add( view );
7291 refresh: function() {
7292 var type = this.model.get('type'),
7295 if ( 'image' === type ) {
7296 constructor = media.view.EmbedImage;
7297 } else if ( 'link' === type ) {
7298 constructor = media.view.EmbedLink;
7303 this.settings( new constructor({
7304 controller: this.controller,
7305 model: this.model.props,
7310 loading: function() {
7311 this.$el.toggleClass( 'embed-loading', this.model.get('loading') );
7317 * @augments wp.media.View
7318 * @augments wp.Backbone.View
7319 * @augments Backbone.View
7321 media.view.Label = media.View.extend({
7323 className: 'screen-reader-text',
7325 initialize: function() {
7326 this.value = this.options.value;
7329 render: function() {
7330 this.$el.html( this.value );
7337 * wp.media.view.EmbedUrl
7340 * @augments wp.media.View
7341 * @augments wp.Backbone.View
7342 * @augments Backbone.View
7344 media.view.EmbedUrl = media.View.extend({
7346 className: 'embed-url',
7354 initialize: function() {
7357 this.$input = $('<input id="embed-url-field" type="url" />').val( this.model.get('url') );
7358 this.input = this.$input[0];
7360 this.spinner = $('<span class="spinner" />')[0];
7361 this.$el.append([ this.input, this.spinner ]);
7363 this.model.on( 'change:url', this.render, this );
7365 if ( this.model.get( 'url' ) ) {
7366 _.delay( function () {
7367 self.model.trigger( 'change:url' );
7372 * @returns {wp.media.view.EmbedUrl} Returns itself to allow chaining
7374 render: function() {
7375 var $input = this.$input;
7377 if ( $input.is(':focus') ) {
7381 this.input.value = this.model.get('url') || 'http://';
7383 * Call `render` directly on parent class with passed arguments
7385 media.View.prototype.render.apply( this, arguments );
7390 if ( ! isTouchDevice ) {
7395 url: function( event ) {
7396 this.model.set( 'url', event.target.value );
7400 * If the input is visible, focus and select its contents.
7403 var $input = this.$input;
7404 if ( $input.is(':visible') ) {
7405 $input.focus()[0].select();
7411 * wp.media.view.EmbedLink
7414 * @augments wp.media.view.Settings
7415 * @augments wp.media.View
7416 * @augments wp.Backbone.View
7417 * @augments Backbone.View
7419 media.view.EmbedLink = media.view.Settings.extend({
7420 className: 'embed-link-settings',
7421 template: media.template('embed-link-settings'),
7423 initialize: function() {
7424 this.spinner = $('<span class="spinner" />');
7425 this.$el.append( this.spinner[0] );
7426 this.listenTo( this.model, 'change:url', this.updateoEmbed );
7429 updateoEmbed: function() {
7430 var url = this.model.get( 'url' );
7432 this.$('.setting.title').show();
7433 // clear out previous results
7434 this.$('.embed-container').hide().find('.embed-preview').html('');
7436 // only proceed with embed if the field contains more than 6 characters
7437 if ( url && url.length < 6 ) {
7441 this.spinner.show();
7443 setTimeout( _.bind( this.fetch, this ), 500 );
7447 // check if they haven't typed in 500 ms
7448 if ( $('#embed-url-field').val() !== this.model.get('url') ) {
7452 wp.ajax.send( 'parse-embed', {
7454 post_ID: media.view.settings.post.id,
7455 shortcode: '[embed]' + this.model.get('url') + '[/embed]'
7457 } ).done( _.bind( this.renderoEmbed, this ) );
7460 renderoEmbed: function( response ) {
7461 var html = ( response && response.body ) || '';
7463 this.spinner.hide();
7465 this.$('.setting.title').hide();
7466 this.$('.embed-container').show().find('.embed-preview').html( html );
7471 * wp.media.view.EmbedImage
7474 * @augments wp.media.view.Settings.AttachmentDisplay
7475 * @augments wp.media.view.Settings
7476 * @augments wp.media.View
7477 * @augments wp.Backbone.View
7478 * @augments Backbone.View
7480 media.view.EmbedImage = media.view.Settings.AttachmentDisplay.extend({
7481 className: 'embed-media-settings',
7482 template: media.template('embed-image-settings'),
7484 initialize: function() {
7486 * Call `initialize` directly on parent class with passed arguments
7488 media.view.Settings.AttachmentDisplay.prototype.initialize.apply( this, arguments );
7489 this.model.on( 'change:url', this.updateImage, this );
7492 updateImage: function() {
7493 this.$('img').attr( 'src', this.model.get('url') );
7498 * wp.media.view.ImageDetails
7501 * @augments wp.media.view.Settings.AttachmentDisplay
7502 * @augments wp.media.view.Settings
7503 * @augments wp.media.View
7504 * @augments wp.Backbone.View
7505 * @augments Backbone.View
7507 media.view.ImageDetails = media.view.Settings.AttachmentDisplay.extend({
7508 className: 'image-details',
7509 template: media.template('image-details'),
7510 events: _.defaults( media.view.Settings.AttachmentDisplay.prototype.events, {
7511 'click .edit-attachment': 'editAttachment',
7512 'click .replace-attachment': 'replaceAttachment',
7513 'click .advanced-toggle': 'onToggleAdvanced',
7514 'change [data-setting="customWidth"]': 'onCustomSize',
7515 'change [data-setting="customHeight"]': 'onCustomSize',
7516 'keyup [data-setting="customWidth"]': 'onCustomSize',
7517 'keyup [data-setting="customHeight"]': 'onCustomSize'
7519 initialize: function() {
7520 // used in AttachmentDisplay.prototype.updateLinkTo
7521 this.options.attachment = this.model.attachment;
7522 this.listenTo( this.model, 'change:url', this.updateUrl );
7523 this.listenTo( this.model, 'change:link', this.toggleLinkSettings );
7524 this.listenTo( this.model, 'change:size', this.toggleCustomSize );
7526 media.view.Settings.AttachmentDisplay.prototype.initialize.apply( this, arguments );
7529 prepare: function() {
7530 var attachment = false;
7532 if ( this.model.attachment ) {
7533 attachment = this.model.attachment.toJSON();
7536 model: this.model.toJSON(),
7537 attachment: attachment
7541 render: function() {
7545 if ( this.model.attachment && 'pending' === this.model.dfd.state() ) {
7546 this.model.dfd.done( function() {
7547 media.view.Settings.AttachmentDisplay.prototype.render.apply( self, args );
7549 } ).fail( function() {
7550 self.model.attachment = false;
7551 media.view.Settings.AttachmentDisplay.prototype.render.apply( self, args );
7555 media.view.Settings.AttachmentDisplay.prototype.render.apply( this, arguments );
7562 postRender: function() {
7563 setTimeout( _.bind( this.resetFocus, this ), 10 );
7564 this.toggleLinkSettings();
7565 if ( getUserSetting( 'advImgDetails' ) === 'show' ) {
7566 this.toggleAdvanced( true );
7568 this.trigger( 'post-render' );
7571 resetFocus: function() {
7572 this.$( '.link-to-custom' ).blur();
7573 this.$( '.embed-media-settings' ).scrollTop( 0 );
7576 updateUrl: function() {
7577 this.$( '.image img' ).attr( 'src', this.model.get( 'url' ) );
7578 this.$( '.url' ).val( this.model.get( 'url' ) );
7581 toggleLinkSettings: function() {
7582 if ( this.model.get( 'link' ) === 'none' ) {
7583 this.$( '.link-settings' ).addClass('hidden');
7585 this.$( '.link-settings' ).removeClass('hidden');
7589 toggleCustomSize: function() {
7590 if ( this.model.get( 'size' ) !== 'custom' ) {
7591 this.$( '.custom-size' ).addClass('hidden');
7593 this.$( '.custom-size' ).removeClass('hidden');
7597 onCustomSize: function( event ) {
7598 var dimension = $( event.target ).data('setting'),
7599 num = $( event.target ).val(),
7602 // Ignore bogus input
7603 if ( ! /^\d+/.test( num ) || parseInt( num, 10 ) < 1 ) {
7604 event.preventDefault();
7608 if ( dimension === 'customWidth' ) {
7609 value = Math.round( 1 / this.model.get( 'aspectRatio' ) * num );
7610 this.model.set( 'customHeight', value, { silent: true } );
7611 this.$( '[data-setting="customHeight"]' ).val( value );
7613 value = Math.round( this.model.get( 'aspectRatio' ) * num );
7614 this.model.set( 'customWidth', value, { silent: true } );
7615 this.$( '[data-setting="customWidth"]' ).val( value );
7619 onToggleAdvanced: function( event ) {
7620 event.preventDefault();
7621 this.toggleAdvanced();
7624 toggleAdvanced: function( show ) {
7625 var $advanced = this.$el.find( '.advanced-section' ),
7628 if ( $advanced.hasClass('advanced-visible') || show === false ) {
7629 $advanced.removeClass('advanced-visible');
7630 $advanced.find('.advanced-settings').addClass('hidden');
7633 $advanced.addClass('advanced-visible');
7634 $advanced.find('.advanced-settings').removeClass('hidden');
7638 setUserSetting( 'advImgDetails', mode );
7641 editAttachment: function( event ) {
7642 var editState = this.controller.states.get( 'edit-image' );
7644 if ( window.imageEdit && editState ) {
7645 event.preventDefault();
7646 editState.set( 'image', this.model.attachment );
7647 this.controller.setState( 'edit-image' );
7651 replaceAttachment: function( event ) {
7652 event.preventDefault();
7653 this.controller.setState( 'replace-image' );
7658 * wp.media.view.Cropper
7660 * Uses the imgAreaSelect plugin to allow a user to crop an image.
7662 * Takes imgAreaSelect options from
7663 * wp.customize.HeaderControl.calculateImageSelectOptions via
7664 * wp.customize.HeaderControl.openMM.
7667 * @augments wp.media.View
7668 * @augments wp.Backbone.View
7669 * @augments Backbone.View
7671 media.view.Cropper = media.View.extend({
7672 className: 'crop-content',
7673 template: media.template('crop-content'),
7674 initialize: function() {
7675 _.bindAll(this, 'onImageLoad');
7678 this.controller.frame.on('content:error:crop', this.onError, this);
7679 this.$image = this.$el.find('.crop-image');
7680 this.$image.on('load', this.onImageLoad);
7681 $(window).on('resize.cropper', _.debounce(this.onImageLoad, 250));
7683 remove: function() {
7684 $(window).off('resize.cropper');
7687 wp.media.View.prototype.remove.apply(this, arguments);
7689 prepare: function() {
7691 title: l10n.cropYourImage,
7692 url: this.options.attachment.get('url')
7695 onImageLoad: function() {
7696 var imgOptions = this.controller.get('imgSelectOptions');
7697 if (typeof imgOptions === 'function') {
7698 imgOptions = imgOptions(this.options.attachment, this.controller);
7701 imgOptions = _.extend(imgOptions, {parent: this.$el});
7702 this.trigger('image-loaded');
7703 this.controller.imgSelect = this.$image.imgAreaSelect(imgOptions);
7705 onError: function() {
7706 var filename = this.options.attachment.get('filename');
7708 this.views.add( '.upload-errors', new media.view.UploaderStatusError({
7709 filename: media.view.UploaderStatus.prototype.filename(filename),
7710 message: _wpMediaViewsL10n.cropError
7715 media.view.EditImage = media.View.extend({
7717 className: 'image-editor',
7718 template: media.template('image-editor'),
7720 initialize: function( options ) {
7721 this.editor = window.imageEdit;
7722 this.controller = options.controller;
7723 media.View.prototype.initialize.apply( this, arguments );
7726 prepare: function() {
7727 return this.model.toJSON();
7730 render: function() {
7731 media.View.prototype.render.apply( this, arguments );
7735 loadEditor: function() {
7736 var dfd = this.editor.open( this.model.get('id'), this.model.get('nonces').edit, this );
7737 dfd.done( _.bind( this.focus, this ) );
7741 this.$( '.imgedit-submit .button' ).eq( 0 ).focus();
7745 var lastState = this.controller.lastState();
7746 this.controller.setState( lastState );
7749 refresh: function() {
7755 lastState = this.controller.lastState();
7757 this.model.fetch().done( function() {
7758 self.controller.setState( lastState );
7765 * wp.media.view.Spinner
7768 * @augments wp.media.View
7769 * @augments wp.Backbone.View
7770 * @augments Backbone.View
7772 media.view.Spinner = media.View.extend({
7774 className: 'spinner',
7775 spinnerTimeout: false,
7779 if ( ! this.spinnerTimeout ) {
7780 this.spinnerTimeout = _.delay(function( $el ) {
7782 }, this.delay, this.$el );
7790 this.spinnerTimeout = clearTimeout( this.spinnerTimeout );