1 /* global _wpMediaViewsL10n, confirm, getUserSetting, setUserSetting */
4 Attachment = media.model.Attachment,
5 Attachments = media.model.Attachments,
8 // Link any localized strings.
9 l10n = media.view.l10n = typeof _wpMediaViewsL10n === 'undefined' ? {} : _wpMediaViewsL10n;
12 media.view.settings = l10n.settings || {};
15 // Copy the `post` setting over to the model settings.
16 media.model.settings.post = media.view.settings.post;
18 // Check if the browser supports CSS 3.0 transitions
19 $.support.transition = (function(){
20 var style = document.documentElement.style,
22 WebkitTransition: 'webkitTransitionEnd',
23 MozTransition: 'transitionend',
24 OTransition: 'oTransitionEnd otransitionend',
25 transition: 'transitionend'
28 transition = _.find( _.keys( transitions ), function( transition ) {
29 return ! _.isUndefined( style[ transition ] );
32 return transition && {
33 end: transitions[ transition ]
37 // Makes it easier to bind events using transitions.
38 media.transition = function( selector, sensitivity ) {
39 var deferred = $.Deferred();
41 sensitivity = sensitivity || 2000;
43 if ( $.support.transition ) {
44 if ( ! (selector instanceof $) )
45 selector = $( selector );
47 // Resolve the deferred when the first element finishes animating.
48 selector.first().one( $.support.transition.end, deferred.resolve );
50 // Just in case the event doesn't trigger, fire a callback.
51 _.delay( deferred.resolve, sensitivity );
53 // Otherwise, execute on the spot.
58 return deferred.promise();
62 * ========================================================================
64 * ========================================================================
68 * wp.media.controller.Region
70 media.controller.Region = function( options ) {
71 _.extend( this, _.pick( options || {}, 'id', 'view', 'selector' ) );
74 // Use Backbone's self-propagating `extend` inheritance method.
75 media.controller.Region.extend = Backbone.Model.extend;
77 _.extend( media.controller.Region.prototype, {
78 mode: function( mode ) {
82 // Bail if we're trying to change to the current mode.
83 if ( mode === this._mode )
86 this.trigger('deactivate');
89 this.trigger('activate');
93 render: function( mode ) {
94 // If no mode is provided, just re-render the current mode.
95 // If the provided mode isn't active, perform a full switch.
96 if ( mode && mode !== this._mode )
97 return this.mode( mode );
99 var set = { view: null },
102 this.trigger( 'create', set );
104 this.trigger( 'render', view );
111 return this.view.views.first( this.selector );
114 set: function( views, options ) {
117 return this.view.views.set( this.selector, views, options );
120 trigger: function( event ) {
126 args = _.toArray( arguments );
127 base = this.id + ':' + event;
129 // Trigger `region:action:mode` event.
130 args[0] = base + ':' + this._mode;
131 this.view.trigger.apply( this.view, args );
133 // Trigger `region:action` event.
135 this.view.trigger.apply( this.view, args );
141 * wp.media.controller.StateMachine
143 media.controller.StateMachine = function( states ) {
144 this.states = new Backbone.Collection( states );
147 // Use Backbone's self-propagating `extend` inheritance method.
148 media.controller.StateMachine.extend = Backbone.Model.extend;
150 // Add events to the `StateMachine`.
151 _.extend( media.controller.StateMachine.prototype, Backbone.Events, {
155 // If no `id` is provided, returns the active state.
157 // Implicitly creates states.
158 state: function( id ) {
159 // Ensure that the `states` collection exists so the `StateMachine`
160 // can be used as a mixin.
161 this.states = this.states || new Backbone.Collection();
163 // Default to the active state.
164 id = id || this._state;
166 if ( id && ! this.states.get( id ) )
167 this.states.add({ id: id });
168 return this.states.get( id );
171 // Sets the active state.
172 setState: function( id ) {
173 var previous = this.state();
175 // Bail if we're trying to select the current state, if we haven't
176 // created the `states` collection, or are trying to select a state
177 // that does not exist.
178 if ( ( previous && id === previous.id ) || ! this.states || ! this.states.get( id ) )
182 previous.trigger('deactivate');
183 this._lastState = previous.id;
187 this.state().trigger('activate');
192 // Returns the previous active state.
194 // Call the `state()` method with no parameters to retrieve the current
196 lastState: function() {
197 if ( this._lastState )
198 return this.state( this._lastState );
202 // Map methods from the `states` collection to the `StateMachine` itself.
203 _.each([ 'on', 'off', 'trigger' ], function( method ) {
204 media.controller.StateMachine.prototype[ method ] = function() {
205 // Ensure that the `states` collection exists so the `StateMachine`
206 // can be used as a mixin.
207 this.states = this.states || new Backbone.Collection();
208 // Forward the method to the `states` collection.
209 this.states[ method ].apply( this.states, arguments );
215 // wp.media.controller.State
216 // ---------------------------
217 media.controller.State = Backbone.Model.extend({
218 constructor: function() {
219 this.on( 'activate', this._preActivate, this );
220 this.on( 'activate', this.activate, this );
221 this.on( 'activate', this._postActivate, this );
222 this.on( 'deactivate', this._deactivate, this );
223 this.on( 'deactivate', this.deactivate, this );
224 this.on( 'reset', this.reset, this );
225 this.on( 'ready', this._ready, this );
226 this.on( 'ready', this.ready, this );
227 Backbone.Model.apply( this, arguments );
228 this.on( 'change:menu', this._updateMenu, this );
231 ready: function() {},
232 activate: function() {},
233 deactivate: function() {},
234 reset: function() {},
240 _preActivate: function() {
244 _postActivate: function() {
245 this.on( 'change:menu', this._menu, this );
246 this.on( 'change:titleMode', this._title, this );
247 this.on( 'change:content', this._content, this );
248 this.on( 'change:toolbar', this._toolbar, this );
250 this.frame.on( 'title:render:default', this._renderTitle, this );
260 _deactivate: function() {
263 this.frame.off( 'title:render:default', this._renderTitle, this );
265 this.off( 'change:menu', this._menu, this );
266 this.off( 'change:titleMode', this._title, this );
267 this.off( 'change:content', this._content, this );
268 this.off( 'change:toolbar', this._toolbar, this );
272 this.frame.title.render( this.get('titleMode') || 'default' );
275 _renderTitle: function( view ) {
276 view.$el.text( this.get('title') || '' );
279 _router: function() {
280 var router = this.frame.router,
281 mode = this.get('router'),
284 this.frame.$el.toggleClass( 'hide-router', ! mode );
288 this.frame.router.render( mode );
291 if ( view && view.select )
292 view.select( this.frame.content.mode() );
296 var menu = this.frame.menu,
297 mode = this.get('menu'),
306 if ( view && view.select )
307 view.select( this.id );
310 _updateMenu: function() {
311 var previous = this.previous('menu'),
312 menu = this.get('menu');
315 this.frame.off( 'menu:render:' + previous, this._renderMenu, this );
318 this.frame.on( 'menu:render:' + menu, this._renderMenu, this );
321 _renderMenu: function( view ) {
322 var menuItem = this.get('menuItem'),
323 title = this.get('title'),
324 priority = this.get('priority');
326 if ( ! menuItem && title ) {
327 menuItem = { text: title };
330 menuItem.priority = priority;
336 view.set( this.id, menuItem );
340 _.each(['toolbar','content'], function( region ) {
341 media.controller.State.prototype[ '_' + region ] = function() {
342 var mode = this.get( region );
344 this.frame[ region ].render( mode );
348 // wp.media.controller.Library
349 // ---------------------------
350 media.controller.Library = media.controller.State.extend({
353 multiple: false, // false, 'add', 'reset'
363 title: l10n.mediaLibraryTitle,
365 // Uses a user setting to override the content mode.
366 contentUserSetting: true,
368 // Sync the selection from the last state when 'multiple' matches.
372 initialize: function() {
373 var selection = this.get('selection'),
376 // If a library isn't provided, query all media items.
377 if ( ! this.get('library') )
378 this.set( 'library', media.query() );
380 // If a selection instance isn't provided, create one.
381 if ( ! (selection instanceof media.model.Selection) ) {
385 props = this.get('library').props.toJSON();
386 props = _.omit( props, 'orderby', 'query' );
389 // If the `selection` attribute is set to an object,
390 // it will use those values as the selection instance's
391 // `props` model. Otherwise, it will copy the library's
393 this.set( 'selection', new media.model.Selection( null, {
394 multiple: this.get('multiple'),
399 if ( ! this.get('edge') )
400 this.set( 'edge', 120 );
402 if ( ! this.get('gutter') )
403 this.set( 'gutter', 8 );
405 this.resetDisplays();
408 activate: function() {
409 this.syncSelection();
411 wp.Uploader.queue.on( 'add', this.uploading, this );
413 this.get('selection').on( 'add remove reset', this.refreshContent, this );
415 if ( this.get('contentUserSetting') ) {
416 this.frame.on( 'content:activate', this.saveContentMode, this );
417 this.set( 'content', getUserSetting( 'libraryContent', this.get('content') ) );
421 deactivate: function() {
422 this.recordSelection();
424 this.frame.off( 'content:activate', this.saveContentMode, this );
426 // Unbind all event handlers that use this state as the context
427 // from the selection.
428 this.get('selection').off( null, null, this );
430 wp.Uploader.queue.off( null, null, this );
434 this.get('selection').reset();
435 this.resetDisplays();
436 this.refreshContent();
439 resetDisplays: function() {
440 var defaultProps = media.view.settings.defaultProps;
442 this._defaultDisplaySettings = {
443 align: defaultProps.align || getUserSetting( 'align', 'none' ),
444 size: defaultProps.size || getUserSetting( 'imgsize', 'medium' ),
445 link: defaultProps.link || getUserSetting( 'urlbutton', 'file' )
449 display: function( attachment ) {
450 var displays = this._displays;
452 if ( ! displays[ attachment.cid ] )
453 displays[ attachment.cid ] = new Backbone.Model( this.defaultDisplaySettings( attachment ) );
455 return displays[ attachment.cid ];
458 defaultDisplaySettings: function( attachment ) {
459 var settings = this._defaultDisplaySettings;
460 if ( settings.canEmbed = this.canEmbed( attachment ) )
461 settings.link = 'embed';
465 canEmbed: function( attachment ) {
466 // If uploading, we know the filename but not the mime type.
467 if ( ! attachment.get('uploading') ) {
468 var type = attachment.get('type');
469 if ( type !== 'audio' && type !== 'video' )
473 return _.contains( media.view.settings.embedExts, attachment.get('filename').split('.').pop() );
476 syncSelection: function() {
477 var selection = this.get('selection'),
478 manager = this.frame._selection;
480 if ( ! this.get('syncSelection') || ! manager || ! selection )
483 // If the selection supports multiple items, validate the stored
484 // attachments based on the new selection's conditions. Record
485 // the attachments that are not included; we'll maintain a
486 // reference to those. Other attachments are considered in flux.
487 if ( selection.multiple ) {
488 selection.reset( [], { silent: true });
489 selection.validateAll( manager.attachments );
490 manager.difference = _.difference( manager.attachments.models, selection.models );
493 // Sync the selection's single item with the master.
494 selection.single( manager.single );
497 recordSelection: function() {
498 var selection = this.get('selection'),
499 manager = this.frame._selection;
501 if ( ! this.get('syncSelection') || ! manager || ! selection )
504 // Record the currently active attachments, which is a combination
505 // of the selection's attachments and the set of selected
506 // attachments that this specific selection considered invalid.
507 // Reset the difference and record the single attachment.
508 if ( selection.multiple ) {
509 manager.attachments.reset( selection.toArray().concat( manager.difference ) );
510 manager.difference = [];
512 manager.attachments.add( selection.toArray() );
515 manager.single = selection._single;
518 refreshContent: function() {
519 var selection = this.get('selection'),
521 router = frame.router.get(),
522 mode = frame.content.mode();
524 // If the state is active, no items are selected, and the current
525 // content mode is not an option in the state's router (provided
526 // the state has a router), reset the content mode to the default.
527 if ( this.active && ! selection.length && router && ! router.get( mode ) )
528 this.frame.content.render( this.get('content') );
531 uploading: function( attachment ) {
532 var content = this.frame.content;
534 // If the uploader was selected, navigate to the browser.
535 if ( 'upload' === content.mode() )
536 this.frame.content.mode('browse');
538 // Automatically select any uploading attachments.
540 // Selections that don't support multiple attachments automatically
541 // limit themselves to one attachment (in this case, the last
542 // attachment in the upload queue).
543 this.get('selection').add( attachment );
546 saveContentMode: function() {
547 // Only track the browse router on library states.
548 if ( 'browse' !== this.get('router') )
551 var mode = this.frame.content.mode(),
552 view = this.frame.router.get();
554 if ( view && view.get( mode ) )
555 setUserSetting( 'libraryContent', mode );
559 // wp.media.controller.GalleryEdit
560 // -------------------------------
561 media.controller.GalleryEdit = media.controller.Library.extend({
570 toolbar: 'gallery-edit',
572 title: l10n.editGalleryTitle,
576 // Don't sync the selection, as the Edit Gallery library
577 // *is* the selection.
581 initialize: function() {
582 // If we haven't been provided a `library`, create a `Selection`.
583 if ( ! this.get('library') )
584 this.set( 'library', new media.model.Selection() );
586 // The single `Attachment` view to be used in the `Attachments` view.
587 if ( ! this.get('AttachmentView') )
588 this.set( 'AttachmentView', media.view.Attachment.EditLibrary );
589 media.controller.Library.prototype.initialize.apply( this, arguments );
592 activate: function() {
593 var library = this.get('library');
595 // Limit the library to images only.
596 library.props.set( 'type', 'image' );
598 // Watch for uploaded attachments.
599 this.get('library').observe( wp.Uploader.queue );
601 this.frame.on( 'content:render:browse', this.gallerySettings, this );
603 media.controller.Library.prototype.activate.apply( this, arguments );
606 deactivate: function() {
607 // Stop watching for uploaded attachments.
608 this.get('library').unobserve( wp.Uploader.queue );
610 this.frame.off( 'content:render:browse', this.gallerySettings, this );
612 media.controller.Library.prototype.deactivate.apply( this, arguments );
615 gallerySettings: function( browser ) {
616 var library = this.get('library');
618 if ( ! library || ! browser )
621 library.gallery = library.gallery || new Backbone.Model();
623 browser.sidebar.set({
624 gallery: new media.view.Settings.Gallery({
626 model: library.gallery,
631 browser.toolbar.set( 'reverse', {
632 text: l10n.reverseOrder,
636 library.reset( library.toArray().reverse() );
642 // wp.media.controller.GalleryAdd
643 // ---------------------------------
644 media.controller.GalleryAdd = media.controller.Library.extend({
645 defaults: _.defaults({
646 id: 'gallery-library',
647 filterable: 'uploaded',
650 toolbar: 'gallery-add',
651 title: l10n.addToGalleryTitle,
654 // Don't sync the selection, as the Edit Gallery library
655 // *is* the selection.
657 }, media.controller.Library.prototype.defaults ),
659 initialize: function() {
660 // If we haven't been provided a `library`, create a `Selection`.
661 if ( ! this.get('library') )
662 this.set( 'library', media.query({ type: 'image' }) );
664 media.controller.Library.prototype.initialize.apply( this, arguments );
667 activate: function() {
668 var library = this.get('library'),
669 edit = this.frame.state('gallery-edit').get('library');
671 if ( this.editLibrary && this.editLibrary !== edit )
672 library.unobserve( this.editLibrary );
674 // Accepts attachments that exist in the original library and
675 // that do not exist in gallery's library.
676 library.validator = function( attachment ) {
677 return !! this.mirroring.get( attachment.cid ) && ! edit.get( attachment.cid ) && media.model.Selection.prototype.validator.apply( this, arguments );
680 // Reset the library to ensure that all attachments are re-added
681 // to the collection. Do so silently, as calling `observe` will
682 // trigger the `reset` event.
683 library.reset( library.mirroring.models, { silent: true });
684 library.observe( edit );
685 this.editLibrary = edit;
687 media.controller.Library.prototype.activate.apply( this, arguments );
691 // wp.media.controller.FeaturedImage
692 // ---------------------------------
693 media.controller.FeaturedImage = media.controller.Library.extend({
694 defaults: _.defaults({
695 id: 'featured-image',
696 filterable: 'uploaded',
698 toolbar: 'featured-image',
699 title: l10n.setFeaturedImageTitle,
703 }, media.controller.Library.prototype.defaults ),
705 initialize: function() {
706 var library, comparator;
708 // If we haven't been provided a `library`, create a `Selection`.
709 if ( ! this.get('library') )
710 this.set( 'library', media.query({ type: 'image' }) );
712 media.controller.Library.prototype.initialize.apply( this, arguments );
714 library = this.get('library');
715 comparator = library.comparator;
717 // Overload the library's comparator to push items that are not in
718 // the mirrored query to the front of the aggregate collection.
719 library.comparator = function( a, b ) {
720 var aInQuery = !! this.mirroring.get( a.cid ),
721 bInQuery = !! this.mirroring.get( b.cid );
723 if ( ! aInQuery && bInQuery )
725 else if ( aInQuery && ! bInQuery )
728 return comparator.apply( this, arguments );
731 // Add all items in the selection to the library, so any featured
732 // images that are not initially loaded still appear.
733 library.observe( this.get('selection') );
736 activate: function() {
737 this.updateSelection();
738 this.frame.on( 'open', this.updateSelection, this );
739 media.controller.Library.prototype.activate.apply( this, arguments );
742 deactivate: function() {
743 this.frame.off( 'open', this.updateSelection, this );
744 media.controller.Library.prototype.deactivate.apply( this, arguments );
747 updateSelection: function() {
748 var selection = this.get('selection'),
749 id = media.view.settings.post.featuredImageId,
752 if ( '' !== id && -1 !== id ) {
753 attachment = Attachment.get( id );
757 selection.reset( attachment ? [ attachment ] : [] );
762 // wp.media.controller.Embed
763 // -------------------------
764 media.controller.Embed = media.controller.State.extend({
770 toolbar: 'main-embed',
773 title: l10n.insertFromUrlTitle,
777 // The amount of time used when debouncing the scan.
780 initialize: function() {
781 this.debouncedScan = _.debounce( _.bind( this.scan, this ), this.sensitivity );
782 this.props = new Backbone.Model({ url: '' });
783 this.props.on( 'change:url', this.debouncedScan, this );
784 this.props.on( 'change:url', this.refresh, this );
785 this.on( 'scan', this.scanImage, this );
796 // Scan is triggered with the list of `attributes` to set on the
797 // state, useful for the 'type' attribute and 'scanners' attribute,
798 // an array of promise objects for asynchronous scan operations.
799 if ( this.props.get('url') )
800 this.trigger( 'scan', attributes );
802 if ( attributes.scanners.length ) {
803 scanners = attributes.scanners = $.when.apply( $, attributes.scanners );
804 scanners.always( function() {
805 if ( embed.get('scanners') === scanners )
806 embed.set( 'loading', false );
809 attributes.scanners = null;
812 attributes.loading = !! attributes.scanners;
813 this.set( attributes );
816 scanImage: function( attributes ) {
817 var frame = this.frame,
819 url = this.props.get('url'),
821 deferred = $.Deferred();
823 attributes.scanners.push( deferred.promise() );
825 // Try to load the image and find its width/height.
826 image.onload = function() {
829 if ( state !== frame.state() || url !== state.props.get('url') )
842 image.onerror = deferred.reject;
846 refresh: function() {
847 this.frame.toolbar.get().refresh();
851 this.props.clear().set({ url: '' });
859 * ========================================================================
861 * ========================================================================
867 // The base view class.
869 // Undelegating events, removing events from the model, and
870 // removing events from the controller mirror the code for
871 // `Backbone.View.dispose` in Backbone 0.9.8 development.
873 // This behavior has since been removed, and should not be used
874 // outside of the media manager.
875 media.View = wp.Backbone.View.extend({
876 constructor: function( options ) {
877 if ( options && options.controller )
878 this.controller = options.controller;
880 wp.Backbone.View.apply( this, arguments );
883 dispose: function() {
884 // Undelegating events, removing events from the model, and
885 // removing events from the controller mirror the code for
886 // `Backbone.View.dispose` in Backbone 0.9.8 development.
887 this.undelegateEvents();
889 if ( this.model && this.model.off )
890 this.model.off( null, null, this );
892 if ( this.collection && this.collection.off )
893 this.collection.off( null, null, this );
895 // Unbind controller events.
896 if ( this.controller && this.controller.off )
897 this.controller.off( null, null, this );
904 return wp.Backbone.View.prototype.remove.apply( this, arguments );
909 * wp.media.view.Frame
911 media.view.Frame = media.View.extend({
912 initialize: function() {
913 this._createRegions();
914 this._createStates();
917 _createRegions: function() {
918 // Clone the regions array.
919 this.regions = this.regions ? this.regions.slice() : [];
921 // Initialize regions.
922 _.each( this.regions, function( region ) {
923 this[ region ] = new media.controller.Region({
926 selector: '.media-frame-' + region
931 _createStates: function() {
932 // Create the default `states` collection.
933 this.states = new Backbone.Collection( null, {
934 model: media.controller.State
937 // Ensure states have a reference to the frame.
938 this.states.on( 'add', function( model ) {
940 model.trigger('ready');
943 if ( this.options.states )
944 this.states.add( this.options.states );
948 this.states.invoke( 'trigger', 'reset' );
953 // Make the `Frame` a `StateMachine`.
954 _.extend( media.view.Frame.prototype, media.controller.StateMachine.prototype );
957 * wp.media.view.MediaFrame
959 media.view.MediaFrame = media.view.Frame.extend({
960 className: 'media-frame',
961 template: media.template('media-frame'),
962 regions: ['menu','title','content','toolbar','router'],
964 initialize: function() {
965 media.view.Frame.prototype.initialize.apply( this, arguments );
967 _.defaults( this.options, {
973 // Ensure core UI is enabled.
974 this.$el.addClass('wp-core-ui');
976 // Initialize modal container view.
977 if ( this.options.modal ) {
978 this.modal = new media.view.Modal({
980 title: this.options.title
983 this.modal.content( this );
986 // Force the uploader off if the upload limit has been exceeded or
987 // if the browser isn't supported.
988 if ( wp.Uploader.limitExceeded || ! wp.Uploader.browser.supported )
989 this.options.uploader = false;
991 // Initialize window-wide uploader.
992 if ( this.options.uploader ) {
993 this.uploader = new media.view.UploaderWindow({
996 dropzone: this.modal ? this.modal.$el : this.$el,
1000 this.views.set( '.media-frame-uploader', this.uploader );
1003 this.on( 'attach', _.bind( this.views.ready, this.views ), this );
1005 // Bind default title creation.
1006 this.on( 'title:create:default', this.createTitle, this );
1007 this.title.mode('default');
1009 // Bind default menu.
1010 this.on( 'menu:create:default', this.createMenu, this );
1013 render: function() {
1014 // Activate the default state if no active state exists.
1015 if ( ! this.state() && this.options.state )
1016 this.setState( this.options.state );
1018 return media.view.Frame.prototype.render.apply( this, arguments );
1021 createTitle: function( title ) {
1022 title.view = new media.View({
1028 createMenu: function( menu ) {
1029 menu.view = new media.view.Menu({
1034 createToolbar: function( toolbar ) {
1035 toolbar.view = new media.view.Toolbar({
1040 createRouter: function( router ) {
1041 router.view = new media.view.Router({
1046 createIframeStates: function( options ) {
1047 var settings = media.view.settings,
1048 tabs = settings.tabs,
1049 tabUrl = settings.tabUrl,
1052 if ( ! tabs || ! tabUrl )
1055 // Add the post ID to the tab URL if it exists.
1056 $postId = $('#post_ID');
1057 if ( $postId.length )
1058 tabUrl += '&post_id=' + $postId.val();
1060 // Generate the tab states.
1061 _.each( tabs, function( title, id ) {
1062 this.state( 'iframe:' + id ).set( _.defaults({
1064 src: tabUrl + '&tab=' + id,
1071 this.on( 'content:create:iframe', this.iframeContent, this );
1072 this.on( 'menu:render:default', this.iframeMenu, this );
1073 this.on( 'open', this.hijackThickbox, this );
1074 this.on( 'close', this.restoreThickbox, this );
1077 iframeContent: function( content ) {
1078 this.$el.addClass('hide-toolbar');
1079 content.view = new media.view.Iframe({
1084 iframeMenu: function( view ) {
1090 _.each( media.view.settings.tabs, function( title, id ) {
1091 views[ 'iframe:' + id ] = {
1092 text: this.state( 'iframe:' + id ).get('title'),
1100 hijackThickbox: function() {
1103 if ( ! window.tb_remove || this._tb_remove )
1106 this._tb_remove = window.tb_remove;
1107 window.tb_remove = function() {
1110 frame.setState( frame.options.state );
1111 frame._tb_remove.call( window );
1115 restoreThickbox: function() {
1116 if ( ! this._tb_remove )
1119 window.tb_remove = this._tb_remove;
1120 delete this._tb_remove;
1124 // Map some of the modal's methods to the frame.
1125 _.each(['open','close','attach','detach','escape'], function( method ) {
1126 media.view.MediaFrame.prototype[ method ] = function() {
1128 this.modal[ method ].apply( this.modal, arguments );
1134 * wp.media.view.MediaFrame.Select
1136 media.view.MediaFrame.Select = media.view.MediaFrame.extend({
1137 initialize: function() {
1138 media.view.MediaFrame.prototype.initialize.apply( this, arguments );
1140 _.defaults( this.options, {
1147 this.createSelection();
1148 this.createStates();
1149 this.bindHandlers();
1152 createSelection: function() {
1153 var selection = this.options.selection;
1155 if ( ! (selection instanceof media.model.Selection) ) {
1156 this.options.selection = new media.model.Selection( selection, {
1157 multiple: this.options.multiple
1162 attachments: new Attachments(),
1167 createStates: function() {
1168 var options = this.options;
1170 if ( this.options.states )
1173 // Add the default states.
1176 new media.controller.Library({
1177 library: media.query( options.library ),
1178 multiple: options.multiple,
1179 title: options.title,
1185 bindHandlers: function() {
1186 this.on( 'router:create:browse', this.createRouter, this );
1187 this.on( 'router:render:browse', this.browseRouter, this );
1188 this.on( 'content:create:browse', this.browseContent, this );
1189 this.on( 'content:render:upload', this.uploadContent, this );
1190 this.on( 'toolbar:create:select', this.createSelectToolbar, this );
1194 browseRouter: function( view ) {
1197 text: l10n.uploadFilesTitle,
1201 text: l10n.mediaLibraryTitle,
1208 browseContent: function( content ) {
1209 var state = this.state();
1211 this.$el.removeClass('hide-toolbar');
1213 // Browse our library of attachments.
1214 content.view = new media.view.AttachmentsBrowser({
1216 collection: state.get('library'),
1217 selection: state.get('selection'),
1219 sortable: state.get('sortable'),
1220 search: state.get('searchable'),
1221 filters: state.get('filterable'),
1222 display: state.get('displaySettings'),
1223 dragInfo: state.get('dragInfo'),
1225 AttachmentView: state.get('AttachmentView')
1229 uploadContent: function() {
1230 this.$el.removeClass('hide-toolbar');
1231 this.content.set( new media.view.UploaderInline({
1237 createSelectToolbar: function( toolbar, options ) {
1238 options = options || this.options.button || {};
1239 options.controller = this;
1241 toolbar.view = new media.view.Toolbar.Select( options );
1246 * wp.media.view.MediaFrame.Post
1248 media.view.MediaFrame.Post = media.view.MediaFrame.Select.extend({
1249 initialize: function() {
1250 _.defaults( this.options, {
1256 media.view.MediaFrame.Select.prototype.initialize.apply( this, arguments );
1257 this.createIframeStates();
1260 createStates: function() {
1261 var options = this.options;
1263 // Add the default states.
1266 new media.controller.Library({
1268 title: l10n.insertMediaTitle,
1270 toolbar: 'main-insert',
1272 library: media.query( options.library ),
1273 multiple: options.multiple ? 'reset' : false,
1276 // If the user isn't allowed to edit fields,
1277 // can they still edit it locally?
1278 allowLocalEdits: true,
1280 // Show the attachment display settings.
1281 displaySettings: true,
1282 // Update user settings when users adjust the
1283 // attachment display settings.
1284 displayUserSettings: true
1287 new media.controller.Library({
1289 title: l10n.createGalleryTitle,
1291 toolbar: 'main-gallery',
1292 filterable: 'uploaded',
1296 library: media.query( _.defaults({
1298 }, options.library ) )
1302 new media.controller.Embed(),
1305 new media.controller.GalleryEdit({
1306 library: options.selection,
1307 editing: options.editing,
1311 new media.controller.GalleryAdd()
1315 if ( media.view.settings.post.featuredImageId ) {
1316 this.states.add( new media.controller.FeaturedImage() );
1320 bindHandlers: function() {
1321 media.view.MediaFrame.Select.prototype.bindHandlers.apply( this, arguments );
1322 this.on( 'menu:create:gallery', this.createMenu, this );
1323 this.on( 'toolbar:create:main-insert', this.createToolbar, this );
1324 this.on( 'toolbar:create:main-gallery', this.createToolbar, this );
1325 this.on( 'toolbar:create:featured-image', this.featuredImageToolbar, this );
1326 this.on( 'toolbar:create:main-embed', this.mainEmbedToolbar, this );
1330 'default': 'mainMenu',
1331 'gallery': 'galleryMenu'
1335 'embed': 'embedContent',
1336 'edit-selection': 'editSelectionContent'
1340 'main-insert': 'mainInsertToolbar',
1341 'main-gallery': 'mainGalleryToolbar',
1342 'gallery-edit': 'galleryEditToolbar',
1343 'gallery-add': 'galleryAddToolbar'
1347 _.each( handlers, function( regionHandlers, region ) {
1348 _.each( regionHandlers, function( callback, handler ) {
1349 this.on( region + ':render:' + handler, this[ callback ], this );
1355 mainMenu: function( view ) {
1357 'library-separator': new media.View({
1358 className: 'separator',
1364 galleryMenu: function( view ) {
1365 var lastState = this.lastState(),
1366 previous = lastState && lastState.id,
1371 text: l10n.cancelGalleryTitle,
1375 frame.setState( previous );
1380 separateCancel: new media.View({
1381 className: 'separator',
1388 embedContent: function() {
1389 var view = new media.view.Embed({
1394 this.content.set( view );
1398 editSelectionContent: function() {
1399 var state = this.state(),
1400 selection = state.get('selection'),
1403 view = new media.view.AttachmentsBrowser({
1405 collection: selection,
1406 selection: selection,
1412 AttachmentView: media.view.Attachment.EditSelection
1415 view.toolbar.set( 'backToLibrary', {
1416 text: l10n.returnToLibrary,
1420 this.controller.content.mode('browse');
1424 // Browse our library of attachments.
1425 this.content.set( view );
1429 selectionStatusToolbar: function( view ) {
1430 var editable = this.state().get('editable');
1432 view.set( 'selection', new media.view.Selection({
1434 collection: this.state().get('selection'),
1437 // If the selection is editable, pass the callback to
1438 // switch the content mode.
1439 editable: editable && function() {
1440 this.controller.content.mode('edit-selection');
1445 mainInsertToolbar: function( view ) {
1446 var controller = this;
1448 this.selectionStatusToolbar( view );
1450 view.set( 'insert', {
1453 text: l10n.insertIntoPost,
1454 requires: { selection: true },
1457 var state = controller.state(),
1458 selection = state.get('selection');
1461 state.trigger( 'insert', selection ).reset();
1466 mainGalleryToolbar: function( view ) {
1467 var controller = this;
1469 this.selectionStatusToolbar( view );
1471 view.set( 'gallery', {
1473 text: l10n.createNewGallery,
1475 requires: { selection: true },
1478 var selection = controller.state().get('selection'),
1479 edit = controller.state('gallery-edit'),
1480 models = selection.where({ type: 'image' });
1482 edit.set( 'library', new media.model.Selection( models, {
1483 props: selection.props.toJSON(),
1487 this.controller.setState('gallery-edit');
1492 featuredImageToolbar: function( toolbar ) {
1493 this.createSelectToolbar( toolbar, {
1494 text: l10n.setFeaturedImage,
1495 state: this.options.state
1499 mainEmbedToolbar: function( toolbar ) {
1500 toolbar.view = new media.view.Toolbar.Embed({
1505 galleryEditToolbar: function() {
1506 var editing = this.state().get('editing');
1507 this.toolbar.set( new media.view.Toolbar({
1512 text: editing ? l10n.updateGallery : l10n.insertGallery,
1514 requires: { library: true },
1517 var controller = this.controller,
1518 state = controller.state();
1521 state.trigger( 'update', state.get('library') );
1523 // Restore and reset the default state.
1524 controller.setState( controller.options.state );
1532 galleryAddToolbar: function() {
1533 this.toolbar.set( new media.view.Toolbar({
1538 text: l10n.addToGallery,
1540 requires: { selection: true },
1543 var controller = this.controller,
1544 state = controller.state(),
1545 edit = controller.state('gallery-edit');
1547 edit.get('library').add( state.get('selection').models );
1548 state.trigger('reset');
1549 controller.setState('gallery-edit');
1558 * wp.media.view.Modal
1560 media.view.Modal = media.View.extend({
1562 template: media.template('media-modal'),
1569 'click .media-modal-backdrop, .media-modal-close': 'escapeHandler',
1570 'keydown': 'keydown'
1573 initialize: function() {
1574 _.defaults( this.options, {
1575 container: document.body,
1582 prepare: function() {
1584 title: this.options.title
1588 attach: function() {
1589 if ( this.views.attached )
1592 if ( ! this.views.rendered )
1595 this.$el.appendTo( this.options.container );
1597 // Manually mark the view as attached and trigger ready.
1598 this.views.attached = true;
1601 return this.propagate('attach');
1604 detach: function() {
1605 if ( this.$el.is(':visible') )
1609 this.views.attached = false;
1610 return this.propagate('detach');
1615 options = this.options;
1617 if ( $el.is(':visible') )
1620 if ( ! this.views.attached )
1623 // If the `freeze` option is set, record the window's scroll position.
1624 if ( options.freeze ) {
1626 scrollTop: $( window ).scrollTop()
1631 return this.propagate('open');
1634 close: function( options ) {
1635 var freeze = this._freeze;
1637 if ( ! this.views.attached || ! this.$el.is(':visible') )
1641 this.propagate('close');
1643 // If the `freeze` option is set, restore the container's scroll position.
1645 $( window ).scrollTop( freeze.scrollTop );
1648 if ( options && options.escape )
1649 this.propagate('escape');
1654 escape: function() {
1655 return this.close({ escape: true });
1658 escapeHandler: function( event ) {
1659 event.preventDefault();
1663 content: function( content ) {
1664 this.views.set( '.media-modal-content', content );
1668 // Triggers a modal event and if the `propagate` option is set,
1669 // forwards events to the modal's controller.
1670 propagate: function( id ) {
1673 if ( this.options.propagate )
1674 this.controller.trigger( id );
1679 keydown: function( event ) {
1680 // Close the modal when escape is pressed.
1681 if ( 27 === event.which ) {
1682 event.preventDefault();
1689 // wp.media.view.FocusManager
1690 // ----------------------------
1691 media.view.FocusManager = media.View.extend({
1693 keydown: 'recordTab',
1694 focusin: 'updateIndex'
1698 if ( _.isUndefined( this.index ) )
1701 // Update our collection of `$tabbables`.
1702 this.$tabbables = this.$(':tabbable');
1704 // If tab is saved, focus it.
1705 this.$tabbables.eq( this.index ).focus();
1708 recordTab: function( event ) {
1709 // Look for the tab key.
1710 if ( 9 !== event.keyCode )
1713 // First try to update the index.
1714 if ( _.isUndefined( this.index ) )
1715 this.updateIndex( event );
1717 // If we still don't have an index, bail.
1718 if ( _.isUndefined( this.index ) )
1721 var index = this.index + ( event.shiftKey ? -1 : 1 );
1723 if ( index >= 0 && index < this.$tabbables.length )
1729 updateIndex: function( event ) {
1730 this.$tabbables = this.$(':tabbable');
1732 var index = this.$tabbables.index( event.target );
1741 // wp.media.view.UploaderWindow
1742 // ----------------------------
1743 media.view.UploaderWindow = media.View.extend({
1745 className: 'uploader-window',
1746 template: media.template('uploader-window'),
1748 initialize: function() {
1751 this.$browser = $('<a href="#" class="browser" />').hide().appendTo('body');
1753 uploader = this.options.uploader = _.defaults( this.options.uploader || {}, {
1755 browser: this.$browser,
1759 // Ensure the dropzone is a jQuery collection.
1760 if ( uploader.dropzone && ! (uploader.dropzone instanceof $) )
1761 uploader.dropzone = $( uploader.dropzone );
1763 this.controller.on( 'activate', this.refresh, this );
1766 refresh: function() {
1767 if ( this.uploader )
1768 this.uploader.refresh();
1772 var postId = media.view.settings.post.id,
1775 // If the uploader already exists, bail.
1776 if ( this.uploader )
1780 this.options.uploader.params.post_id = postId;
1782 this.uploader = new wp.Uploader( this.options.uploader );
1784 dropzone = this.uploader.dropzone;
1785 dropzone.on( 'dropzone:enter', _.bind( this.show, this ) );
1786 dropzone.on( 'dropzone:leave', _.bind( this.hide, this ) );
1790 var $el = this.$el.show();
1792 // Ensure that the animation is triggered by waiting until
1793 // the transparent element is painted into the DOM.
1794 _.defer( function() {
1795 $el.css({ opacity: 1 });
1800 var $el = this.$el.css({ opacity: 0 });
1802 media.transition( $el ).done( function() {
1803 // Transition end events are subject to race conditions.
1804 // Make sure that the value is set as intended.
1805 if ( '0' === $el.css('opacity') )
1811 media.view.UploaderInline = media.View.extend({
1813 className: 'uploader-inline',
1814 template: media.template('uploader-inline'),
1816 initialize: function() {
1817 _.defaults( this.options, {
1822 if ( ! this.options.$browser && this.controller.uploader )
1823 this.options.$browser = this.controller.uploader.$browser;
1825 if ( _.isUndefined( this.options.postId ) )
1826 this.options.postId = media.view.settings.post.id;
1828 if ( this.options.status ) {
1829 this.views.set( '.upload-inline-status', new media.view.UploaderStatus({
1830 controller: this.controller
1835 dispose: function() {
1836 if ( this.disposing )
1837 return media.View.prototype.dispose.apply( this, arguments );
1839 // Run remove on `dispose`, so we can be sure to refresh the
1840 // uploader with a view-less DOM. Track whether we're disposing
1841 // so we don't trigger an infinite loop.
1842 this.disposing = true;
1843 return this.remove();
1846 remove: function() {
1847 var result = media.View.prototype.remove.apply( this, arguments );
1849 _.defer( _.bind( this.refresh, this ) );
1853 refresh: function() {
1854 var uploader = this.controller.uploader;
1861 var $browser = this.options.$browser,
1864 if ( this.controller.uploader ) {
1865 $placeholder = this.$('.browser');
1867 // Check if we've already replaced the placeholder.
1868 if ( $placeholder[0] === $browser[0] )
1871 $browser.detach().text( $placeholder.text() );
1872 $browser[0].className = $placeholder[0].className;
1873 $placeholder.replaceWith( $browser.show() );
1882 * wp.media.view.UploaderStatus
1884 media.view.UploaderStatus = media.View.extend({
1885 className: 'media-uploader-status',
1886 template: media.template('uploader-status'),
1889 'click .upload-dismiss-errors': 'dismiss'
1892 initialize: function() {
1893 this.queue = wp.Uploader.queue;
1894 this.queue.on( 'add remove reset', this.visibility, this );
1895 this.queue.on( 'add remove reset change:percent', this.progress, this );
1896 this.queue.on( 'add remove reset change:uploading', this.info, this );
1898 this.errors = wp.Uploader.errors;
1899 this.errors.reset();
1900 this.errors.on( 'add remove reset', this.visibility, this );
1901 this.errors.on( 'add', this.error, this );
1904 dispose: function() {
1905 wp.Uploader.queue.off( null, null, this );
1906 media.View.prototype.dispose.apply( this, arguments );
1910 visibility: function() {
1911 this.$el.toggleClass( 'uploading', !! this.queue.length );
1912 this.$el.toggleClass( 'errors', !! this.errors.length );
1913 this.$el.toggle( !! this.queue.length || !! this.errors.length );
1918 '$bar': '.media-progress-bar div',
1919 '$index': '.upload-index',
1920 '$total': '.upload-total',
1921 '$filename': '.upload-filename'
1922 }, function( selector, key ) {
1923 this[ key ] = this.$( selector );
1931 progress: function() {
1932 var queue = this.queue,
1935 if ( ! $bar || ! queue.length )
1938 $bar.width( ( queue.reduce( function( memo, attachment ) {
1939 if ( ! attachment.get('uploading') )
1942 var percent = attachment.get('percent');
1943 return memo + ( _.isNumber( percent ) ? percent : 100 );
1944 }, 0 ) / queue.length ) + '%' );
1948 var queue = this.queue,
1951 if ( ! queue.length )
1954 active = this.queue.find( function( attachment, i ) {
1956 return attachment.get('uploading');
1959 this.$index.text( index + 1 );
1960 this.$total.text( queue.length );
1961 this.$filename.html( active ? this.filename( active.get('filename') ) : '' );
1964 filename: function( filename ) {
1965 return media.truncate( _.escape( filename ), 24 );
1968 error: function( error ) {
1969 this.views.add( '.upload-errors', new media.view.UploaderStatusError({
1970 filename: this.filename( error.get('file').name ),
1971 message: error.get('message')
1975 dismiss: function( event ) {
1976 var errors = this.views.get('.upload-errors');
1978 event.preventDefault();
1981 _.invoke( errors, 'remove' );
1982 wp.Uploader.errors.reset();
1986 media.view.UploaderStatusError = media.View.extend({
1987 className: 'upload-error',
1988 template: media.template('uploader-status-error')
1992 * wp.media.view.Toolbar
1994 media.view.Toolbar = media.View.extend({
1996 className: 'media-toolbar',
1998 initialize: function() {
1999 var state = this.controller.state(),
2000 selection = this.selection = state.get('selection'),
2001 library = this.library = state.get('library');
2005 // The toolbar is composed of two `PriorityList` views.
2006 this.primary = new media.view.PriorityList();
2007 this.secondary = new media.view.PriorityList();
2008 this.primary.$el.addClass('media-toolbar-primary');
2009 this.secondary.$el.addClass('media-toolbar-secondary');
2011 this.views.set([ this.secondary, this.primary ]);
2013 if ( this.options.items )
2014 this.set( this.options.items, { silent: true });
2016 if ( ! this.options.silent )
2020 selection.on( 'add remove reset', this.refresh, this );
2022 library.on( 'add remove reset', this.refresh, this );
2025 dispose: function() {
2026 if ( this.selection )
2027 this.selection.off( null, null, this );
2029 this.library.off( null, null, this );
2030 return media.View.prototype.dispose.apply( this, arguments );
2037 set: function( id, view, options ) {
2039 options = options || {};
2041 // Accept an object with an `id` : `view` mapping.
2042 if ( _.isObject( id ) ) {
2043 _.each( id, function( view, id ) {
2044 this.set( id, view, { silent: true });
2048 if ( ! ( view instanceof Backbone.View ) ) {
2049 view.classes = [ 'media-button-' + id ].concat( view.classes || [] );
2050 view = new media.view.Button( view ).render();
2053 view.controller = view.controller || this.controller;
2055 this._views[ id ] = view;
2057 list = view.options.priority < 0 ? 'secondary' : 'primary';
2058 this[ list ].set( id, view, options );
2061 if ( ! options.silent )
2067 get: function( id ) {
2068 return this._views[ id ];
2071 unset: function( id, options ) {
2072 delete this._views[ id ];
2073 this.primary.unset( id, options );
2074 this.secondary.unset( id, options );
2076 if ( ! options || ! options.silent )
2081 refresh: function() {
2082 var state = this.controller.state(),
2083 library = state.get('library'),
2084 selection = state.get('selection');
2086 _.each( this._views, function( button ) {
2087 if ( ! button.model || ! button.options || ! button.options.requires )
2090 var requires = button.options.requires,
2093 // Prevent insertion of attachments if any of them are still uploading
2094 disabled = _.some( selection.models, function( attachment ) {
2095 return attachment.get('uploading') === true;
2098 if ( requires.selection && selection && ! selection.length )
2100 else if ( requires.library && library && ! library.length )
2103 button.model.set( 'disabled', disabled );
2108 // wp.media.view.Toolbar.Select
2109 // ----------------------------
2110 media.view.Toolbar.Select = media.view.Toolbar.extend({
2111 initialize: function() {
2112 var options = this.options;
2114 _.bindAll( this, 'clickSelect' );
2116 _.defaults( options, {
2123 // Does the button rely on the selection?
2129 options.items = _.defaults( options.items || {}, {
2134 click: this.clickSelect,
2135 requires: options.requires
2139 media.view.Toolbar.prototype.initialize.apply( this, arguments );
2142 clickSelect: function() {
2143 var options = this.options,
2144 controller = this.controller;
2146 if ( options.close )
2149 if ( options.event )
2150 controller.state().trigger( options.event );
2152 if ( options.state )
2153 controller.setState( options.state );
2155 if ( options.reset )
2160 // wp.media.view.Toolbar.Embed
2161 // ---------------------------
2162 media.view.Toolbar.Embed = media.view.Toolbar.Select.extend({
2163 initialize: function() {
2164 _.defaults( this.options, {
2165 text: l10n.insertIntoPost,
2169 media.view.Toolbar.Select.prototype.initialize.apply( this, arguments );
2172 refresh: function() {
2173 var url = this.controller.state().props.get('url');
2174 this.get('select').model.set( 'disabled', ! url || url === 'http://' );
2176 media.view.Toolbar.Select.prototype.refresh.apply( this, arguments );
2181 * wp.media.view.Button
2183 media.view.Button = media.View.extend({
2185 className: 'media-button',
2186 attributes: { href: '#' },
2199 initialize: function() {
2200 // Create a model with the provided `defaults`.
2201 this.model = new Backbone.Model( this.defaults );
2203 // If any of the `options` have a key from `defaults`, apply its
2204 // value to the `model` and remove it from the `options object.
2205 _.each( this.defaults, function( def, key ) {
2206 var value = this.options[ key ];
2207 if ( _.isUndefined( value ) )
2210 this.model.set( key, value );
2211 delete this.options[ key ];
2214 this.model.on( 'change', this.render, this );
2217 render: function() {
2218 var classes = [ 'button', this.className ],
2219 model = this.model.toJSON();
2222 classes.push( 'button-' + model.style );
2225 classes.push( 'button-' + model.size );
2227 classes = _.uniq( classes.concat( this.options.classes ) );
2228 this.el.className = classes.join(' ');
2230 this.$el.attr( 'disabled', model.disabled );
2231 this.$el.text( this.model.get('text') );
2236 click: function( event ) {
2237 if ( '#' === this.attributes.href )
2238 event.preventDefault();
2240 if ( this.options.click && ! this.model.get('disabled') )
2241 this.options.click.apply( this, arguments );
2246 * wp.media.view.ButtonGroup
2248 media.view.ButtonGroup = media.View.extend({
2250 className: 'button-group button-large media-button-group',
2252 initialize: function() {
2253 this.buttons = _.map( this.options.buttons || [], function( button ) {
2254 if ( button instanceof Backbone.View )
2257 return new media.view.Button( button ).render();
2260 delete this.options.buttons;
2262 if ( this.options.classes )
2263 this.$el.addClass( this.options.classes );
2266 render: function() {
2267 this.$el.html( $( _.pluck( this.buttons, 'el' ) ).detach() );
2273 * wp.media.view.PriorityList
2276 media.view.PriorityList = media.View.extend({
2279 initialize: function() {
2282 this.set( _.extend( {}, this._views, this.options.views ), { silent: true });
2283 delete this.options.views;
2285 if ( ! this.options.silent )
2289 set: function( id, view, options ) {
2290 var priority, views, index;
2292 options = options || {};
2294 // Accept an object with an `id` : `view` mapping.
2295 if ( _.isObject( id ) ) {
2296 _.each( id, function( view, id ) {
2297 this.set( id, view );
2302 if ( ! (view instanceof Backbone.View) )
2303 view = this.toView( view, id, options );
2305 view.controller = view.controller || this.controller;
2309 priority = view.options.priority || 10;
2310 views = this.views.get() || [];
2312 _.find( views, function( existing, i ) {
2313 if ( existing.options.priority > priority ) {
2319 this._views[ id ] = view;
2320 this.views.add( view, {
2321 at: _.isNumber( index ) ? index : views.length || 0
2327 get: function( id ) {
2328 return this._views[ id ];
2331 unset: function( id ) {
2332 var view = this.get( id );
2337 delete this._views[ id ];
2341 toView: function( options ) {
2342 return new media.View( options );
2347 * wp.media.view.MenuItem
2349 media.view.MenuItem = media.View.extend({
2351 className: 'media-menu-item',
2361 _click: function( event ) {
2362 var clickOverride = this.options.click;
2365 event.preventDefault();
2367 if ( clickOverride )
2368 clickOverride.call( this );
2374 var state = this.options.state;
2376 this.controller.setState( state );
2379 render: function() {
2380 var options = this.options;
2383 this.$el.text( options.text );
2384 else if ( options.html )
2385 this.$el.html( options.html );
2392 * wp.media.view.Menu
2394 media.view.Menu = media.view.PriorityList.extend({
2396 className: 'media-menu',
2398 ItemView: media.view.MenuItem,
2401 toView: function( options, id ) {
2402 options = options || {};
2403 options[ this.property ] = options[ this.property ] || id;
2404 return new this.ItemView( options ).render();
2408 media.view.PriorityList.prototype.ready.apply( this, arguments );
2413 media.view.PriorityList.prototype.set.apply( this, arguments );
2418 media.view.PriorityList.prototype.unset.apply( this, arguments );
2422 visibility: function() {
2423 var region = this.region,
2424 view = this.controller[ region ].get(),
2425 views = this.views.get(),
2426 hide = ! views || views.length < 2;
2428 if ( this === view )
2429 this.controller.$el.toggleClass( 'hide-' + region, hide );
2432 select: function( id ) {
2433 var view = this.get( id );
2439 view.$el.addClass('active');
2442 deselect: function() {
2443 this.$el.children().removeClass('active');
2448 * wp.media.view.RouterItem
2450 media.view.RouterItem = media.view.MenuItem.extend({
2452 var contentMode = this.options.contentMode;
2454 this.controller.content.mode( contentMode );
2459 * wp.media.view.Router
2461 media.view.Router = media.view.Menu.extend({
2463 className: 'media-router',
2464 property: 'contentMode',
2465 ItemView: media.view.RouterItem,
2468 initialize: function() {
2469 this.controller.on( 'content:render', this.update, this );
2470 media.view.Menu.prototype.initialize.apply( this, arguments );
2473 update: function() {
2474 var mode = this.controller.content.mode();
2476 this.select( mode );
2482 * wp.media.view.Sidebar
2484 media.view.Sidebar = media.view.PriorityList.extend({
2485 className: 'media-sidebar'
2489 * wp.media.view.Attachment
2491 media.view.Attachment = media.View.extend({
2493 className: 'attachment',
2494 template: media.template('attachment'),
2497 'click .attachment-preview': 'toggleSelectionHandler',
2498 'change [data-setting]': 'updateSetting',
2499 'change [data-setting] input': 'updateSetting',
2500 'change [data-setting] select': 'updateSetting',
2501 'change [data-setting] textarea': 'updateSetting',
2502 'click .close': 'removeFromLibrary',
2503 'click .check': 'removeFromSelection',
2504 'click a': 'preventDefault'
2509 initialize: function() {
2510 var selection = this.options.selection;
2512 this.model.on( 'change:sizes change:uploading', this.render, this );
2513 this.model.on( 'change:title', this._syncTitle, this );
2514 this.model.on( 'change:caption', this._syncCaption, this );
2515 this.model.on( 'change:percent', this.progress, this );
2517 // Update the selection.
2518 this.model.on( 'add', this.select, this );
2519 this.model.on( 'remove', this.deselect, this );
2521 selection.on( 'reset', this.updateSelect, this );
2523 // Update the model's details view.
2524 this.model.on( 'selection:single selection:unsingle', this.details, this );
2525 this.details( this.model, this.controller.state().get('selection') );
2528 dispose: function() {
2529 var selection = this.options.selection;
2531 // Make sure all settings are saved before removing the view.
2535 selection.off( null, null, this );
2537 media.View.prototype.dispose.apply( this, arguments );
2541 render: function() {
2542 var options = _.defaults( this.model.toJSON(), {
2543 orientation: 'landscape',
2559 options.buttons = this.buttons;
2560 options.describe = this.controller.state().get('describe');
2562 if ( 'image' === options.type )
2563 options.size = this.imageSize();
2566 if ( options.nonces ) {
2567 options.can.remove = !! options.nonces['delete'];
2568 options.can.save = !! options.nonces.update;
2571 if ( this.controller.state().get('allowLocalEdits') )
2572 options.allowLocalEdits = true;
2574 this.views.detach();
2575 this.$el.html( this.template( options ) );
2577 this.$el.toggleClass( 'uploading', options.uploading );
2578 if ( options.uploading )
2579 this.$bar = this.$('.media-progress-bar div');
2583 // Check if the model is selected.
2584 this.updateSelect();
2586 // Update the save status.
2589 this.views.render();
2594 progress: function() {
2595 if ( this.$bar && this.$bar.length )
2596 this.$bar.width( this.model.get('percent') + '%' );
2599 toggleSelectionHandler: function( event ) {
2602 if ( event.shiftKey )
2604 else if ( event.ctrlKey || event.metaKey )
2607 this.toggleSelection({
2612 toggleSelection: function( options ) {
2613 var collection = this.collection,
2614 selection = this.options.selection,
2616 method = options && options.method,
2617 single, models, singleIndex, modelIndex;
2622 single = selection.single();
2623 method = _.isUndefined( method ) ? selection.multiple : method;
2625 // If the `method` is set to `between`, select all models that
2626 // exist between the current and the selected model.
2627 if ( 'between' === method && single && selection.multiple ) {
2628 // If the models are the same, short-circuit.
2629 if ( single === model )
2632 singleIndex = collection.indexOf( single );
2633 modelIndex = collection.indexOf( this.model );
2635 if ( singleIndex < modelIndex )
2636 models = collection.models.slice( singleIndex, modelIndex + 1 );
2638 models = collection.models.slice( modelIndex, singleIndex + 1 );
2640 selection.add( models ).single( model );
2643 // If the `method` is set to `toggle`, just flip the selection
2644 // status, regardless of whether the model is the single model.
2645 } else if ( 'toggle' === method ) {
2646 selection[ this.selected() ? 'remove' : 'add' ]( model ).single( model );
2650 if ( method !== 'add' )
2653 if ( this.selected() ) {
2654 // If the model is the single model, remove it.
2655 // If it is not the same as the single model,
2656 // it now becomes the single model.
2657 selection[ single === model ? 'remove' : 'single' ]( model );
2659 // If the model is not selected, run the `method` on the
2660 // selection. By default, we `reset` the selection, but the
2661 // `method` can be set to `add` the model to the selection.
2662 selection[ method ]( model ).single( model );
2666 updateSelect: function() {
2667 this[ this.selected() ? 'select' : 'deselect' ]();
2670 selected: function() {
2671 var selection = this.options.selection;
2673 return !! selection.get( this.model.cid );
2676 select: function( model, collection ) {
2677 var selection = this.options.selection;
2679 // Check if a selection exists and if it's the collection provided.
2680 // If they're not the same collection, bail; we're in another
2681 // selection's event loop.
2682 if ( ! selection || ( collection && collection !== selection ) )
2685 this.$el.addClass('selected');
2688 deselect: function( model, collection ) {
2689 var selection = this.options.selection;
2691 // Check if a selection exists and if it's the collection provided.
2692 // If they're not the same collection, bail; we're in another
2693 // selection's event loop.
2694 if ( ! selection || ( collection && collection !== selection ) )
2697 this.$el.removeClass('selected');
2700 details: function( model, collection ) {
2701 var selection = this.options.selection,
2704 if ( selection !== collection )
2707 details = selection.single();
2708 this.$el.toggleClass( 'details', details === this.model );
2711 preventDefault: function( event ) {
2712 event.preventDefault();
2715 imageSize: function( size ) {
2716 var sizes = this.model.get('sizes');
2718 size = size || 'medium';
2720 // Use the provided image size if possible.
2721 if ( sizes && sizes[ size ] ) {
2722 return _.clone( sizes[ size ] );
2725 url: this.model.get('url'),
2726 width: this.model.get('width'),
2727 height: this.model.get('height'),
2728 orientation: this.model.get('orientation')
2733 updateSetting: function( event ) {
2734 var $setting = $( event.target ).closest('[data-setting]'),
2737 if ( ! $setting.length )
2740 setting = $setting.data('setting');
2741 value = event.target.value;
2743 if ( this.model.get( setting ) !== value )
2744 this.save( setting, value );
2747 // Pass all the arguments to the model's save method.
2749 // Records the aggregate status of all save requests and updates the
2750 // view's classes accordingly.
2753 save = this._save = this._save || { status: 'ready' },
2754 request = this.model.save.apply( this.model, arguments ),
2755 requests = save.requests ? $.when( request, save.requests ) : request;
2757 // If we're waiting to remove 'Saved.', stop.
2758 if ( save.savedTimer )
2759 clearTimeout( save.savedTimer );
2761 this.updateSave('waiting');
2762 save.requests = requests;
2763 requests.always( function() {
2764 // If we've performed another request since this one, bail.
2765 if ( save.requests !== requests )
2768 view.updateSave( requests.state() === 'resolved' ? 'complete' : 'error' );
2769 save.savedTimer = setTimeout( function() {
2770 view.updateSave('ready');
2771 delete save.savedTimer;
2777 updateSave: function( status ) {
2778 var save = this._save = this._save || { status: 'ready' };
2780 if ( status && status !== save.status ) {
2781 this.$el.removeClass( 'save-' + save.status );
2782 save.status = status;
2785 this.$el.addClass( 'save-' + save.status );
2789 updateAll: function() {
2790 var $settings = this.$('[data-setting]'),
2794 changed = _.chain( $settings ).map( function( el ) {
2795 var $input = $('input, textarea, select, [value]', el ),
2798 if ( ! $input.length )
2801 setting = $(el).data('setting');
2802 value = $input.val();
2804 // Record the value if it changed.
2805 if ( model.get( setting ) !== value )
2806 return [ setting, value ];
2807 }).compact().object().value();
2809 if ( ! _.isEmpty( changed ) )
2810 model.save( changed );
2813 removeFromLibrary: function( event ) {
2814 // Stop propagation so the model isn't selected.
2815 event.stopPropagation();
2817 this.collection.remove( this.model );
2820 removeFromSelection: function( event ) {
2821 var selection = this.options.selection;
2825 // Stop propagation so the model isn't selected.
2826 event.stopPropagation();
2828 selection.remove( this.model );
2832 // Ensure settings remain in sync between attachment views.
2834 caption: '_syncCaption',
2836 }, function( method, setting ) {
2837 media.view.Attachment.prototype[ method ] = function( model, value ) {
2838 var $setting = this.$('[data-setting="' + setting + '"]');
2840 if ( ! $setting.length )
2843 // If the updated value is in sync with the value in the DOM, there
2844 // is no need to re-render. If we're currently editing the value,
2845 // it will automatically be in sync, suppressing the re-render for
2846 // the view we're editing, while updating any others.
2847 if ( value === $setting.find('input, textarea, select, [value]').val() )
2850 return this.render();
2855 * wp.media.view.Attachment.Library
2857 media.view.Attachment.Library = media.view.Attachment.extend({
2864 * wp.media.view.Attachment.EditLibrary
2866 media.view.Attachment.EditLibrary = media.view.Attachment.extend({
2873 * wp.media.view.Attachments
2875 media.view.Attachments = media.View.extend({
2877 className: 'attachments',
2879 cssTemplate: media.template('attachments-css'),
2885 initialize: function() {
2886 this.el.id = _.uniqueId('__attachments-view-');
2888 _.defaults( this.options, {
2889 refreshSensitivity: 200,
2890 refreshThreshold: 3,
2891 AttachmentView: media.view.Attachment,
2896 this._viewsByCid = {};
2898 this.collection.on( 'add', function( attachment ) {
2899 this.views.add( this.createAttachmentView( attachment ), {
2900 at: this.collection.indexOf( attachment )
2904 this.collection.on( 'remove', function( attachment ) {
2905 var view = this._viewsByCid[ attachment.cid ];
2906 delete this._viewsByCid[ attachment.cid ];
2912 this.collection.on( 'reset', this.render, this );
2914 // Throttle the scroll handler.
2915 this.scroll = _.chain( this.scroll ).bind( this ).throttle( this.options.refreshSensitivity ).value();
2917 this.initSortable();
2919 _.bindAll( this, 'css' );
2920 this.model.on( 'change:edge change:gutter', this.css, this );
2921 this._resizeCss = _.debounce( _.bind( this.css, this ), this.refreshSensitivity );
2922 if ( this.options.resize )
2923 $(window).on( 'resize.attachments', this._resizeCss );
2927 dispose: function() {
2928 this.collection.props.off( null, null, this );
2929 $(window).off( 'resize.attachments', this._resizeCss );
2930 media.View.prototype.dispose.apply( this, arguments );
2934 var $css = $( '#' + this.el.id + '-css' );
2939 media.view.Attachments.$head().append( this.cssTemplate({
2942 gutter: this.model.get('gutter')
2947 var edge = this.model.get('edge'),
2948 gutter, width, columns;
2950 if ( ! this.$el.is(':visible') )
2953 gutter = this.model.get('gutter') * 2;
2954 width = this.$el.width() - gutter;
2955 columns = Math.ceil( width / ( edge + gutter ) );
2956 edge = Math.floor( ( width - ( columns * gutter ) ) / columns );
2960 initSortable: function() {
2961 var collection = this.collection;
2963 if ( ! this.options.sortable || ! $.fn.sortable )
2966 this.$el.sortable( _.extend({
2967 // If the `collection` has a `comparator`, disable sorting.
2968 disabled: !! collection.comparator,
2970 // Prevent attachments from being dragged outside the bounding
2972 containment: this.$el,
2974 // Change the position of the attachment as soon as the
2975 // mouse pointer overlaps a thumbnail.
2976 tolerance: 'pointer',
2978 // Record the initial `index` of the dragged model.
2979 start: function( event, ui ) {
2980 ui.item.data('sortableIndexStart', ui.item.index());
2983 // Update the model's index in the collection.
2984 // Do so silently, as the view is already accurate.
2985 update: function( event, ui ) {
2986 var model = collection.at( ui.item.data('sortableIndexStart') ),
2987 comparator = collection.comparator;
2989 // Temporarily disable the comparator to prevent `add`
2991 delete collection.comparator;
2993 // Silently shift the model to its new index.
2994 collection.remove( model, {
3001 // Restore the comparator.
3002 collection.comparator = comparator;
3004 // Fire the `reset` event to ensure other collections sync.
3005 collection.trigger( 'reset', collection );
3007 // If the collection is sorted by menu order,
3008 // update the menu order.
3009 collection.saveMenuOrder();
3011 }, this.options.sortable ) );
3013 // If the `orderby` property is changed on the `collection`,
3014 // check to see if we have a `comparator`. If so, disable sorting.
3015 collection.props.on( 'change:orderby', function() {
3016 this.$el.sortable( 'option', 'disabled', !! collection.comparator );
3019 this.collection.props.on( 'change:orderby', this.refreshSortable, this );
3020 this.refreshSortable();
3023 refreshSortable: function() {
3024 if ( ! this.options.sortable || ! $.fn.sortable )
3027 // If the `collection` has a `comparator`, disable sorting.
3028 var collection = this.collection,
3029 orderby = collection.props.get('orderby'),
3030 enabled = 'menuOrder' === orderby || ! collection.comparator;
3032 this.$el.sortable( 'option', 'disabled', ! enabled );
3035 createAttachmentView: function( attachment ) {
3036 var view = new this.options.AttachmentView({
3037 controller: this.controller,
3039 collection: this.collection,
3040 selection: this.options.selection
3043 return this._viewsByCid[ attachment.cid ] = view;
3046 prepare: function() {
3047 // Create all of the Attachment views, and replace
3048 // the list in a single DOM operation.
3049 if ( this.collection.length ) {
3050 this.views.set( this.collection.map( this.createAttachmentView, this ) );
3052 // If there are no elements, clear the views and load some.
3055 this.collection.more().done( this.scroll );
3060 // Trigger the scroll event to check if we're within the
3061 // threshold to query for additional attachments.
3065 scroll: function() {
3066 // @todo: is this still necessary?
3067 if ( ! this.$el.is(':visible') )
3070 if ( this.collection.hasMore() && this.el.scrollHeight < this.el.scrollTop + ( this.el.clientHeight * this.options.refreshThreshold ) ) {
3071 this.collection.more().done( this.scroll );
3075 $head: (function() {
3078 return $head = $head || $('head');
3084 * wp.media.view.Search
3086 media.view.Search = media.View.extend({
3088 className: 'search',
3092 placeholder: l10n.search
3102 render: function() {
3103 this.el.value = this.model.escape('search');
3107 search: function( event ) {
3108 if ( event.target.value )
3109 this.model.set( 'search', event.target.value );
3111 this.model.unset('search');
3116 * wp.media.view.AttachmentFilters
3118 media.view.AttachmentFilters = media.View.extend({
3120 className: 'attachment-filters',
3128 initialize: function() {
3129 this.createFilters();
3130 _.extend( this.filters, this.options.filters );
3132 // Build `<option>` elements.
3133 this.$el.html( _.chain( this.filters ).map( function( filter, value ) {
3135 el: $('<option></option>').val(value).text(filter.text)[0],
3136 priority: filter.priority || 50
3138 }, this ).sortBy('priority').pluck('el').value() );
3140 this.model.on( 'change', this.select, this );
3144 createFilters: function() {
3148 change: function() {
3149 var filter = this.filters[ this.el.value ];
3152 this.model.set( filter.props );
3155 select: function() {
3156 var model = this.model,
3158 props = model.toJSON();
3160 _.find( this.filters, function( filter, id ) {
3161 var equal = _.all( filter.props, function( prop, key ) {
3162 return prop === ( _.isUndefined( props[ key ] ) ? null : props[ key ] );
3169 this.$el.val( value );
3173 media.view.AttachmentFilters.Uploaded = media.view.AttachmentFilters.extend({
3174 createFilters: function() {
3175 var type = this.model.get('type'),
3176 types = media.view.settings.mimeTypes,
3179 if ( types && type )
3180 text = types[ type ];
3184 text: text || l10n.allMediaItems,
3194 text: l10n.uploadedToThisPost,
3196 uploadedTo: media.view.settings.post.id,
3197 orderby: 'menuOrder',
3206 media.view.AttachmentFilters.All = media.view.AttachmentFilters.extend({
3207 createFilters: function() {
3210 _.each( media.view.settings.mimeTypes || {}, function( text, key ) {
3223 text: l10n.allMediaItems,
3233 filters.uploaded = {
3234 text: l10n.uploadedToThisPost,
3237 uploadedTo: media.view.settings.post.id,
3238 orderby: 'menuOrder',
3244 this.filters = filters;
3251 * wp.media.view.AttachmentsBrowser
3253 media.view.AttachmentsBrowser = media.View.extend({
3255 className: 'attachments-browser',
3257 initialize: function() {
3258 _.defaults( this.options, {
3263 AttachmentView: media.view.Attachment.Library
3266 this.createToolbar();
3267 this.updateContent();
3268 this.createSidebar();
3270 this.collection.on( 'add remove reset', this.updateContent, this );
3273 dispose: function() {
3274 this.options.selection.off( null, null, this );
3275 media.View.prototype.dispose.apply( this, arguments );
3279 createToolbar: function() {
3280 var filters, FiltersConstructor;
3282 this.toolbar = new media.view.Toolbar({
3283 controller: this.controller
3286 this.views.add( this.toolbar );
3288 filters = this.options.filters;
3289 if ( 'uploaded' === filters )
3290 FiltersConstructor = media.view.AttachmentFilters.Uploaded;
3291 else if ( 'all' === filters )
3292 FiltersConstructor = media.view.AttachmentFilters.All;
3294 if ( FiltersConstructor ) {
3295 this.toolbar.set( 'filters', new FiltersConstructor({
3296 controller: this.controller,
3297 model: this.collection.props,
3302 if ( this.options.search ) {
3303 this.toolbar.set( 'search', new media.view.Search({
3304 controller: this.controller,
3305 model: this.collection.props,
3310 if ( this.options.dragInfo ) {
3311 this.toolbar.set( 'dragInfo', new media.View({
3312 el: $( '<div class="instructions">' + l10n.dragInfo + '</div>' )[0],
3318 updateContent: function() {
3321 if( ! this.attachments )
3322 this.createAttachments();
3324 if ( ! this.collection.length ) {
3325 this.collection.more().done( function() {
3326 if ( ! view.collection.length )
3327 view.createUploader();
3332 removeContent: function() {
3333 _.each(['attachments','uploader'], function( key ) {
3334 if ( this[ key ] ) {
3335 this[ key ].remove();
3341 createUploader: function() {
3342 this.removeContent();
3344 this.uploader = new media.view.UploaderInline({
3345 controller: this.controller,
3347 message: l10n.noItemsFound
3350 this.views.add( this.uploader );
3353 createAttachments: function() {
3354 this.removeContent();
3356 this.attachments = new media.view.Attachments({
3357 controller: this.controller,
3358 collection: this.collection,
3359 selection: this.options.selection,
3361 sortable: this.options.sortable,
3363 // The single `Attachment` view to be used in the `Attachments` view.
3364 AttachmentView: this.options.AttachmentView
3367 this.views.add( this.attachments );
3370 createSidebar: function() {
3371 var options = this.options,
3372 selection = options.selection,
3373 sidebar = this.sidebar = new media.view.Sidebar({
3374 controller: this.controller
3377 this.views.add( sidebar );
3379 if ( this.controller.uploader ) {
3380 sidebar.set( 'uploads', new media.view.UploaderStatus({
3381 controller: this.controller,
3386 selection.on( 'selection:single', this.createSingle, this );
3387 selection.on( 'selection:unsingle', this.disposeSingle, this );
3389 if ( selection.single() )
3390 this.createSingle();
3393 createSingle: function() {
3394 var sidebar = this.sidebar,
3395 single = this.options.selection.single();
3397 sidebar.set( 'details', new media.view.Attachment.Details({
3398 controller: this.controller,
3403 sidebar.set( 'compat', new media.view.AttachmentCompat({
3404 controller: this.controller,
3409 if ( this.options.display ) {
3410 sidebar.set( 'display', new media.view.Settings.AttachmentDisplay({
3411 controller: this.controller,
3412 model: this.model.display( single ),
3415 userSettings: this.model.get('displayUserSettings')
3420 disposeSingle: function() {
3421 var sidebar = this.sidebar;
3422 sidebar.unset('details');
3423 sidebar.unset('compat');
3424 sidebar.unset('display');
3429 * wp.media.view.Selection
3431 media.view.Selection = media.View.extend({
3433 className: 'media-selection',
3434 template: media.template('media-selection'),
3437 'click .edit-selection': 'edit',
3438 'click .clear-selection': 'clear'
3441 initialize: function() {
3442 _.defaults( this.options, {
3447 this.attachments = new media.view.Attachments.Selection({
3448 controller: this.controller,
3449 collection: this.collection,
3450 selection: this.collection,
3451 model: new Backbone.Model({
3457 this.views.set( '.selection-view', this.attachments );
3458 this.collection.on( 'add remove reset', this.refresh, this );
3459 this.controller.on( 'content:activate', this.refresh, this );
3466 refresh: function() {
3467 // If the selection hasn't been rendered, bail.
3468 if ( ! this.$el.children().length )
3471 var collection = this.collection,
3472 editing = 'edit-selection' === this.controller.content.mode();
3474 // If nothing is selected, display nothing.
3475 this.$el.toggleClass( 'empty', ! collection.length );
3476 this.$el.toggleClass( 'one', 1 === collection.length );
3477 this.$el.toggleClass( 'editing', editing );
3479 this.$('.count').text( l10n.selected.replace('%d', collection.length) );
3482 edit: function( event ) {
3483 event.preventDefault();
3484 if ( this.options.editable )
3485 this.options.editable.call( this, this.collection );
3488 clear: function( event ) {
3489 event.preventDefault();
3490 this.collection.reset();
3496 * wp.media.view.Attachment.Selection
3498 media.view.Attachment.Selection = media.view.Attachment.extend({
3499 className: 'attachment selection',
3501 // On click, just select the model, instead of removing the model from
3503 toggleSelection: function() {
3504 this.options.selection.single( this.model );
3509 * wp.media.view.Attachments.Selection
3511 media.view.Attachments.Selection = media.view.Attachments.extend({
3513 initialize: function() {
3514 _.defaults( this.options, {
3518 // The single `Attachment` view to be used in the `Attachments` view.
3519 AttachmentView: media.view.Attachment.Selection
3521 return media.view.Attachments.prototype.initialize.apply( this, arguments );
3526 * wp.media.view.Attachments.EditSelection
3528 media.view.Attachment.EditSelection = media.view.Attachment.Selection.extend({
3536 * wp.media.view.Settings
3538 media.view.Settings = media.View.extend({
3540 'click button': 'updateHandler',
3541 'change input': 'updateHandler',
3542 'change select': 'updateHandler',
3543 'change textarea': 'updateHandler'
3546 initialize: function() {
3547 this.model = this.model || new Backbone.Model();
3548 this.model.on( 'change', this.updateChanges, this );
3551 prepare: function() {
3553 model: this.model.toJSON()
3557 render: function() {
3558 media.View.prototype.render.apply( this, arguments );
3559 // Select the correct values.
3560 _( this.model.attributes ).chain().keys().each( this.update, this );
3564 update: function( key ) {
3565 var value = this.model.get( key ),
3566 $setting = this.$('[data-setting="' + key + '"]'),
3569 // Bail if we didn't find a matching setting.
3570 if ( ! $setting.length )
3573 // Attempt to determine how the setting is rendered and update
3574 // the selected value.
3576 // Handle dropdowns.
3577 if ( $setting.is('select') ) {
3578 $value = $setting.find('[value="' + value + '"]');
3580 if ( $value.length ) {
3581 $setting.find('option').prop( 'selected', false );
3582 $value.prop( 'selected', true );
3584 // If we can't find the desired value, record what *is* selected.
3585 this.model.set( key, $setting.find(':selected').val() );
3589 // Handle button groups.
3590 } else if ( $setting.hasClass('button-group') ) {
3591 $buttons = $setting.find('button').removeClass('active');
3592 $buttons.filter( '[value="' + value + '"]' ).addClass('active');
3594 // Handle text inputs and textareas.
3595 } else if ( $setting.is('input[type="text"], textarea') ) {
3596 if ( ! $setting.is(':focus') )
3597 $setting.val( value );
3599 // Handle checkboxes.
3600 } else if ( $setting.is('input[type="checkbox"]') ) {
3601 $setting.attr( 'checked', !! value );
3605 updateHandler: function( event ) {
3606 var $setting = $( event.target ).closest('[data-setting]'),
3607 value = event.target.value,
3610 event.preventDefault();
3612 if ( ! $setting.length )
3615 // Use the correct value for checkboxes.
3616 if ( $setting.is('input[type="checkbox"]') )
3617 value = $setting[0].checked;
3619 // Update the corresponding setting.
3620 this.model.set( $setting.data('setting'), value );
3622 // If the setting has a corresponding user setting,
3623 // update that as well.
3624 if ( userSetting = $setting.data('userSetting') )
3625 setUserSetting( userSetting, value );
3628 updateChanges: function( model ) {
3629 if ( model.hasChanged() )
3630 _( model.changed ).chain().keys().each( this.update, this );
3635 * wp.media.view.Settings.AttachmentDisplay
3637 media.view.Settings.AttachmentDisplay = media.view.Settings.extend({
3638 className: 'attachment-display-settings',
3639 template: media.template('attachment-display-settings'),
3641 initialize: function() {
3642 var attachment = this.options.attachment;
3644 _.defaults( this.options, {
3648 media.view.Settings.prototype.initialize.apply( this, arguments );
3649 this.model.on( 'change:link', this.updateLinkTo, this );
3652 attachment.on( 'change:uploading', this.render, this );
3655 dispose: function() {
3656 var attachment = this.options.attachment;
3658 attachment.off( null, null, this );
3660 media.view.Settings.prototype.dispose.apply( this, arguments );
3663 render: function() {
3664 var attachment = this.options.attachment;
3666 _.extend( this.options, {
3667 sizes: attachment.get('sizes'),
3668 type: attachment.get('type')
3672 media.view.Settings.prototype.render.call( this );
3673 this.updateLinkTo();
3677 updateLinkTo: function() {
3678 var linkTo = this.model.get('link'),
3679 $input = this.$('.link-to-custom'),
3680 attachment = this.options.attachment;
3682 if ( 'none' === linkTo || 'embed' === linkTo || ( ! attachment && 'custom' !== linkTo ) ) {
3688 if ( 'post' === linkTo ) {
3689 $input.val( attachment.get('link') );
3690 } else if ( 'file' === linkTo ) {
3691 $input.val( attachment.get('url') );
3692 } else if ( ! this.model.get('linkUrl') ) {
3693 $input.val('http://');
3696 $input.prop( 'readonly', 'custom' !== linkTo );
3701 // If the input is visible, focus and select its contents.
3702 if ( $input.is(':visible') )
3703 $input.focus()[0].select();
3708 * wp.media.view.Settings.Gallery
3710 media.view.Settings.Gallery = media.view.Settings.extend({
3711 className: 'gallery-settings',
3712 template: media.template('gallery-settings')
3716 * wp.media.view.Attachment.Details
3718 media.view.Attachment.Details = media.view.Attachment.extend({
3720 className: 'attachment-details',
3721 template: media.template('attachment-details'),
3724 'change [data-setting]': 'updateSetting',
3725 'change [data-setting] input': 'updateSetting',
3726 'change [data-setting] select': 'updateSetting',
3727 'change [data-setting] textarea': 'updateSetting',
3728 'click .delete-attachment': 'deleteAttachment',
3729 'click .edit-attachment': 'editAttachment',
3730 'click .refresh-attachment': 'refreshAttachment'
3733 initialize: function() {
3734 this.focusManager = new media.view.FocusManager({
3738 media.view.Attachment.prototype.initialize.apply( this, arguments );
3741 render: function() {
3742 media.view.Attachment.prototype.render.apply( this, arguments );
3743 this.focusManager.focus();
3747 deleteAttachment: function( event ) {
3748 event.preventDefault();
3750 if ( confirm( l10n.warnDelete ) )
3751 this.model.destroy();
3754 editAttachment: function() {
3755 this.$el.addClass('needs-refresh');
3758 refreshAttachment: function( event ) {
3759 this.$el.removeClass('needs-refresh');
3760 event.preventDefault();
3766 * wp.media.view.AttachmentCompat
3768 media.view.AttachmentCompat = media.View.extend({
3770 className: 'compat-item',
3773 'submit': 'preventDefault',
3774 'change input': 'save',
3775 'change select': 'save',
3776 'change textarea': 'save'
3779 initialize: function() {
3780 this.focusManager = new media.view.FocusManager({
3784 this.model.on( 'change:compat', this.render, this );
3787 dispose: function() {
3788 if ( this.$(':focus').length )
3791 return media.View.prototype.dispose.apply( this, arguments );
3794 render: function() {
3795 var compat = this.model.get('compat');
3796 if ( ! compat || ! compat.item )
3799 this.views.detach();
3800 this.$el.html( compat.item );
3801 this.views.render();
3803 this.focusManager.focus();
3807 preventDefault: function( event ) {
3808 event.preventDefault();
3811 save: function( event ) {
3815 event.preventDefault();
3817 _.each( this.$el.serializeArray(), function( pair ) {
3818 data[ pair.name ] = pair.value;
3821 this.model.saveCompat( data );
3826 * wp.media.view.Iframe
3828 media.view.Iframe = media.View.extend({
3829 className: 'media-iframe',
3831 render: function() {
3832 this.views.detach();
3833 this.$el.html( '<iframe src="' + this.controller.state().get('src') + '" />' );
3834 this.views.render();
3840 * wp.media.view.Embed
3842 media.view.Embed = media.View.extend({
3843 className: 'media-embed',
3845 initialize: function() {
3846 this.url = new media.view.EmbedUrl({
3847 controller: this.controller,
3848 model: this.model.props
3851 this.views.set([ this.url ]);
3853 this.model.on( 'change:type', this.refresh, this );
3854 this.model.on( 'change:loading', this.loading, this );
3857 settings: function( view ) {
3858 if ( this._settings )
3859 this._settings.remove();
3860 this._settings = view;
3861 this.views.add( view );
3864 refresh: function() {
3865 var type = this.model.get('type'),
3868 if ( 'image' === type )
3869 constructor = media.view.EmbedImage;
3870 else if ( 'link' === type )
3871 constructor = media.view.EmbedLink;
3875 this.settings( new constructor({
3876 controller: this.controller,
3877 model: this.model.props,
3882 loading: function() {
3883 this.$el.toggleClass( 'embed-loading', this.model.get('loading') );
3888 * wp.media.view.EmbedUrl
3890 media.view.EmbedUrl = media.View.extend({
3892 className: 'embed-url',
3900 initialize: function() {
3901 this.$input = $('<input/>').attr( 'type', 'text' ).val( this.model.get('url') );
3902 this.input = this.$input[0];
3904 this.spinner = $('<span class="spinner" />')[0];
3905 this.$el.append([ this.input, this.spinner ]);
3907 this.model.on( 'change:url', this.render, this );
3910 render: function() {
3911 var $input = this.$input;
3913 if ( $input.is(':focus') )
3916 this.input.value = this.model.get('url') || 'http://';
3917 media.View.prototype.render.apply( this, arguments );
3925 url: function( event ) {
3926 this.model.set( 'url', event.target.value );
3930 var $input = this.$input;
3931 // If the input is visible, focus and select its contents.
3932 if ( $input.is(':visible') )
3933 $input.focus()[0].select();
3938 * wp.media.view.EmbedLink
3940 media.view.EmbedLink = media.view.Settings.extend({
3941 className: 'embed-link-settings',
3942 template: media.template('embed-link-settings')
3946 * wp.media.view.EmbedImage
3948 media.view.EmbedImage = media.view.Settings.AttachmentDisplay.extend({
3949 className: 'embed-image-settings',
3950 template: media.template('embed-image-settings'),
3952 initialize: function() {
3953 media.view.Settings.AttachmentDisplay.prototype.initialize.apply( this, arguments );
3954 this.model.on( 'change:url', this.updateImage, this );
3957 updateImage: function() {
3958 this.$('img').attr( 'src', this.model.get('url') );