043702c35090a0dcd02984376c0126292ef1d2d0
[autoinstalls/wordpress.git] / wp-includes / js / media-grid.js
1 /* global _wpMediaViewsL10n, MediaElementPlayer, _wpMediaGridSettings */
2 (function($, _, Backbone, wp) {
3         // Local reference to the WordPress media namespace.
4         var media = wp.media, l10n;
5
6         // Link localized strings and settings.
7         if ( media.view.l10n ) {
8                 l10n = media.view.l10n;
9         } else {
10                 l10n = media.view.l10n = typeof _wpMediaViewsL10n === 'undefined' ? {} : _wpMediaViewsL10n;
11                 delete l10n.settings;
12         }
13
14         /**
15          * wp.media.controller.EditAttachmentMetadata
16          *
17          * A state for editing an attachment's metadata.
18          *
19          * @constructor
20          * @augments wp.media.controller.State
21          * @augments Backbone.Model
22          */
23         media.controller.EditAttachmentMetadata = media.controller.State.extend({
24                 defaults: {
25                         id:      'edit-attachment',
26                         // Title string passed to the frame's title region view.
27                         title:   l10n.attachmentDetails,
28                         // Region mode defaults.
29                         content: 'edit-metadata',
30                         menu:    false,
31                         toolbar: false,
32                         router:  false
33                 }
34         });
35
36         /**
37          * wp.media.view.MediaFrame.Manage
38          *
39          * A generic management frame workflow.
40          *
41          * Used in the media grid view.
42          *
43          * @constructor
44          * @augments wp.media.view.MediaFrame
45          * @augments wp.media.view.Frame
46          * @augments wp.media.View
47          * @augments wp.Backbone.View
48          * @augments Backbone.View
49          * @mixes wp.media.controller.StateMachine
50          */
51         media.view.MediaFrame.Manage = media.view.MediaFrame.extend({
52                 /**
53                  * @global wp.Uploader
54                  */
55                 initialize: function() {
56                         var self = this;
57                         _.defaults( this.options, {
58                                 title:     '',
59                                 modal:     false,
60                                 selection: [],
61                                 library:   {}, // Options hash for the query to the media library.
62                                 multiple:  'add',
63                                 state:     'library',
64                                 uploader:  true,
65                                 mode:      [ 'grid', 'edit' ]
66                         });
67
68                         this.$body = $( document.body );
69                         this.$window = $( window );
70                         this.$adminBar = $( '#wpadminbar' );
71                         this.$window.on( 'scroll resize', _.debounce( _.bind( this.fixPosition, this ), 15 ) );
72                         $( document ).on( 'click', '.add-new-h2', _.bind( this.addNewClickHandler, this ) );
73
74                         // Ensure core and media grid view UI is enabled.
75                         this.$el.addClass('wp-core-ui');
76
77                         // Force the uploader off if the upload limit has been exceeded or
78                         // if the browser isn't supported.
79                         if ( wp.Uploader.limitExceeded || ! wp.Uploader.browser.supported ) {
80                                 this.options.uploader = false;
81                         }
82
83                         // Initialize a window-wide uploader.
84                         if ( this.options.uploader ) {
85                                 this.uploader = new media.view.UploaderWindow({
86                                         controller: this,
87                                         uploader: {
88                                                 dropzone:  document.body,
89                                                 container: document.body
90                                         }
91                                 }).render();
92                                 this.uploader.ready();
93                                 $('body').append( this.uploader.el );
94
95                                 this.options.uploader = false;
96                         }
97
98                         this.gridRouter = new media.view.MediaFrame.Manage.Router();
99
100                         // Call 'initialize' directly on the parent class.
101                         media.view.MediaFrame.prototype.initialize.apply( this, arguments );
102
103                         // Append the frame view directly the supplied container.
104                         this.$el.appendTo( this.options.container );
105
106                         this.createStates();
107                         this.bindRegionModeHandlers();
108                         this.render();
109
110                         // Update the URL when entering search string (at most once per second)
111                         $( '#media-search-input' ).on( 'input', _.debounce( function(e) {
112                                 var val = $( e.currentTarget ).val(), url = '';
113                                 if ( val ) {
114                                         url += '?search=' + val;
115                                 }
116                                 self.gridRouter.navigate( self.gridRouter.baseUrl( url ) );
117                         }, 1000 ) );
118                 },
119
120                 /**
121                  * Create the default states for the frame.
122                  */
123                 createStates: function() {
124                         var options = this.options;
125
126                         if ( this.options.states ) {
127                                 return;
128                         }
129
130                         // Add the default states.
131                         this.states.add([
132                                 new media.controller.Library({
133                                         library:            media.query( options.library ),
134                                         multiple:           options.multiple,
135                                         title:              options.title,
136                                         content:            'browse',
137                                         toolbar:            'select',
138                                         contentUserSetting: false,
139                                         filterable:         'all',
140                                         autoSelect:         false
141                                 })
142                         ]);
143                 },
144
145                 /**
146                  * Bind region mode activation events to proper handlers.
147                  */
148                 bindRegionModeHandlers: function() {
149                         this.on( 'content:create:browse', this.browseContent, this );
150
151                         // Handle a frame-level event for editing an attachment.
152                         this.on( 'edit:attachment', this.openEditAttachmentModal, this );
153
154                         this.on( 'select:activate', this.bindKeydown, this );
155                         this.on( 'select:deactivate', this.unbindKeydown, this );
156                 },
157
158                 handleKeydown: function( e ) {
159                         if ( 27 === e.which ) {
160                                 e.preventDefault();
161                                 this.deactivateMode( 'select' ).activateMode( 'edit' );
162                         }
163                 },
164
165                 bindKeydown: function() {
166                         this.$body.on( 'keydown.select', _.bind( this.handleKeydown, this ) );
167                 },
168
169                 unbindKeydown: function() {
170                         this.$body.off( 'keydown.select' );
171                 },
172
173                 fixPosition: function() {
174                         var $browser, $toolbar;
175                         if ( ! this.isModeActive( 'select' ) ) {
176                                 return;
177                         }
178
179                         $browser = this.$('.attachments-browser');
180                         $toolbar = $browser.find('.media-toolbar');
181
182                         // Offset doesn't appear to take top margin into account, hence +16
183                         if ( ( $browser.offset().top + 16 ) < this.$window.scrollTop() + this.$adminBar.height() ) {
184                                 $browser.addClass( 'fixed' );
185                                 $toolbar.css('width', $browser.width() + 'px');
186                         } else {
187                                 $browser.removeClass( 'fixed' );
188                                 $toolbar.css('width', '');
189                         }
190                 },
191
192                 /**
193                  * Click handler for the `Add New` button.
194                  */
195                 addNewClickHandler: function( event ) {
196                         event.preventDefault();
197                         this.trigger( 'toggle:upload:attachment' );
198                 },
199
200                 /**
201                  * Open the Edit Attachment modal.
202                  */
203                 openEditAttachmentModal: function( model ) {
204                         // Create a new EditAttachment frame, passing along the library and the attachment model.
205                         wp.media( {
206                                 frame:       'edit-attachments',
207                                 controller:  this,
208                                 library:     this.state().get('library'),
209                                 model:       model
210                         } );
211                 },
212
213                 /**
214                  * Create an attachments browser view within the content region.
215                  *
216                  * @param {Object} contentRegion Basic object with a `view` property, which
217                  *                               should be set with the proper region view.
218                  * @this wp.media.controller.Region
219                  */
220                 browseContent: function( contentRegion ) {
221                         var state = this.state();
222
223                         // Browse our library of attachments.
224                         this.browserView = contentRegion.view = new media.view.AttachmentsBrowser({
225                                 controller: this,
226                                 collection: state.get('library'),
227                                 selection:  state.get('selection'),
228                                 model:      state,
229                                 sortable:   state.get('sortable'),
230                                 search:     state.get('searchable'),
231                                 filters:    state.get('filterable'),
232                                 display:    state.get('displaySettings'),
233                                 dragInfo:   state.get('dragInfo'),
234                                 sidebar:    'errors',
235
236                                 suggestedWidth:  state.get('suggestedWidth'),
237                                 suggestedHeight: state.get('suggestedHeight'),
238
239                                 AttachmentView: state.get('AttachmentView'),
240
241                                 scrollElement: document
242                         });
243                         this.browserView.on( 'ready', _.bind( this.bindDeferred, this ) );
244
245                         this.errors = wp.Uploader.errors;
246                         this.errors.on( 'add remove reset', this.sidebarVisibility, this );
247                 },
248
249                 sidebarVisibility: function() {
250                         this.browserView.$( '.media-sidebar' ).toggle( !! this.errors.length );
251                 },
252
253                 bindDeferred: function() {
254                         if ( ! this.browserView.dfd ) {
255                                 return;
256                         }
257                         this.browserView.dfd.done( _.bind( this.startHistory, this ) );
258                 },
259
260                 startHistory: function() {
261                         // Verify pushState support and activate
262                         if ( window.history && window.history.pushState ) {
263                                 Backbone.history.start( {
264                                         root: _wpMediaGridSettings.adminUrl,
265                                         pushState: true
266                                 } );
267                         }
268                 }
269         });
270
271         /**
272          * A similar view to media.view.Attachment.Details
273          * for use in the Edit Attachment modal.
274          *
275          * @constructor
276          * @augments wp.media.view.Attachment.Details
277          * @augments wp.media.view.Attachment
278          * @augments wp.media.View
279          * @augments wp.Backbone.View
280          * @augments Backbone.View
281          */
282         media.view.Attachment.Details.TwoColumn = media.view.Attachment.Details.extend({
283                 template: media.template( 'attachment-details-two-column' ),
284
285                 editAttachment: function( event ) {
286                         event.preventDefault();
287                         this.controller.content.mode( 'edit-image' );
288                 },
289
290                 /**
291                  * Noop this from parent class, doesn't apply here.
292                  */
293                 toggleSelectionHandler: function() {},
294
295                 render: function() {
296                         media.view.Attachment.Details.prototype.render.apply( this, arguments );
297
298                         media.mixin.removeAllPlayers();
299                         this.$( 'audio, video' ).each( function (i, elem) {
300                                 var el = media.view.MediaDetails.prepareSrc( elem );
301                                 new MediaElementPlayer( el, media.mixin.mejsSettings );
302                         } );
303                 }
304         });
305
306         /**
307          * A router for handling the browser history and application state.
308          *
309          * @constructor
310          * @augments Backbone.Router
311          */
312         media.view.MediaFrame.Manage.Router = Backbone.Router.extend({
313                 routes: {
314                         'upload.php?item=:slug':    'showItem',
315                         'upload.php?search=:query': 'search'
316                 },
317
318                 // Map routes against the page URL
319                 baseUrl: function( url ) {
320                         return 'upload.php' + url;
321                 },
322
323                 // Respond to the search route by filling the search field and trigggering the input event
324                 search: function( query ) {
325                         $( '#media-search-input' ).val( query ).trigger( 'input' );
326                 },
327
328                 // Show the modal with a specific item
329                 showItem: function( query ) {
330                         var library = media.frame.state().get('library'), item;
331
332                         // Trigger the media frame to open the correct item
333                         item = library.findWhere( { id: parseInt( query, 10 ) } );
334                         if ( item ) {
335                                 media.frame.trigger( 'edit:attachment', item );
336                         } else {
337                                 item = media.attachment( query );
338                                 media.frame.listenTo( item, 'change', function( model ) {
339                                         media.frame.stopListening( item );
340                                         media.frame.trigger( 'edit:attachment', model );
341                                 } );
342                                 item.fetch();
343                         }
344                 }
345         });
346
347         media.view.EditImage.Details = media.view.EditImage.extend({
348                 initialize: function( options ) {
349                         this.editor = window.imageEdit;
350                         this.frame = options.frame;
351                         this.controller = options.controller;
352                         media.View.prototype.initialize.apply( this, arguments );
353                 },
354
355                 back: function() {
356                         this.frame.content.mode( 'edit-metadata' );
357                 },
358
359                 save: function() {
360                         var self = this;
361
362                         this.model.fetch().done( function() {
363                                 self.frame.content.mode( 'edit-metadata' );
364                         });
365                 }
366         });
367
368         /**
369          * A frame for editing the details of a specific media item.
370          *
371          * Opens in a modal by default.
372          *
373          * Requires an attachment model to be passed in the options hash under `model`.
374          *
375          * @constructor
376          * @augments wp.media.view.Frame
377          * @augments wp.media.View
378          * @augments wp.Backbone.View
379          * @augments Backbone.View
380          * @mixes wp.media.controller.StateMachine
381          */
382         media.view.MediaFrame.EditAttachments = media.view.MediaFrame.extend({
383
384                 className: 'edit-attachment-frame',
385                 template: media.template( 'edit-attachment-frame' ),
386                 regions:   [ 'title', 'content' ],
387
388                 events: {
389                         'click .left':  'previousMediaItem',
390                         'click .right': 'nextMediaItem',
391                         'keydown':      'keyEvent'
392                 },
393
394                 initialize: function() {
395                         media.view.Frame.prototype.initialize.apply( this, arguments );
396
397                         _.defaults( this.options, {
398                                 modal: true,
399                                 state: 'edit-attachment'
400                         });
401
402                         this.controller = this.options.controller;
403                         this.gridRouter = this.controller.gridRouter;
404                         this.library = this.options.library;
405
406                         if ( this.options.model ) {
407                                 this.model = this.options.model;
408                         }
409
410                         this.bindHandlers();
411                         this.createStates();
412                         this.createModal();
413
414                         this.title.mode( 'default' );
415                         this.toggleNav();
416                 },
417
418                 bindHandlers: function() {
419                         // Bind default title creation.
420                         this.on( 'title:create:default', this.createTitle, this );
421
422                         // Close the modal if the attachment is deleted.
423                         this.listenTo( this.model, 'change:status destroy', this.close, this );
424
425                         this.on( 'content:create:edit-metadata', this.editMetadataMode, this );
426                         this.on( 'content:create:edit-image', this.editImageMode, this );
427                         this.on( 'content:render:edit-image', this.editImageModeRender, this );
428                         this.on( 'close', this.detach );
429                 },
430
431                 createModal: function() {
432                         var self = this;
433
434                         // Initialize modal container view.
435                         if ( this.options.modal ) {
436                                 this.modal = new media.view.Modal({
437                                         controller: this,
438                                         title:      this.options.title
439                                 });
440
441                                 this.modal.on( 'open', function () {
442                                         $( 'body' ).on( 'keydown.media-modal', _.bind( self.keyEvent, self ) );
443                                 } );
444
445                                 // Completely destroy the modal DOM element when closing it.
446                                 this.modal.on( 'close', function() {
447                                         self.modal.remove();
448                                         $( 'body' ).off( 'keydown.media-modal' ); /* remove the keydown event */
449                                         // Restore the original focus item if possible
450                                         $( 'li.attachment[data-id="' + self.model.get( 'id' ) +'"]' ).focus();
451                                         self.resetRoute();
452                                 } );
453
454                                 // Set this frame as the modal's content.
455                                 this.modal.content( this );
456                                 this.modal.open();
457                         }
458                 },
459
460                 /**
461                  * Add the default states to the frame.
462                  */
463                 createStates: function() {
464                         this.states.add([
465                                 new media.controller.EditAttachmentMetadata( { model: this.model } )
466                         ]);
467                 },
468
469                 /**
470                  * Content region rendering callback for the `edit-metadata` mode.
471                  *
472                  * @param {Object} contentRegion Basic object with a `view` property, which
473                  *                               should be set with the proper region view.
474                  */
475                 editMetadataMode: function( contentRegion ) {
476                         contentRegion.view = new media.view.Attachment.Details.TwoColumn({
477                                 controller: this,
478                                 model:      this.model
479                         });
480
481                         /**
482                          * Attach a subview to display fields added via the
483                          * `attachment_fields_to_edit` filter.
484                          */
485                         contentRegion.view.views.set( '.attachment-compat', new media.view.AttachmentCompat({
486                                 controller: this,
487                                 model:      this.model
488                         }) );
489
490                         // Update browser url when navigating media details
491                         if ( this.model ) {
492                                 this.gridRouter.navigate( this.gridRouter.baseUrl( '?item=' + this.model.id ) );
493                         }
494                 },
495
496                 /**
497                  * Render the EditImage view into the frame's content region.
498                  *
499                  * @param {Object} contentRegion Basic object with a `view` property, which
500                  *                               should be set with the proper region view.
501                  */
502                 editImageMode: function( contentRegion ) {
503                         var editImageController = new media.controller.EditImage( {
504                                 model: this.model,
505                                 frame: this
506                         } );
507                         // Noop some methods.
508                         editImageController._toolbar = function() {};
509                         editImageController._router = function() {};
510                         editImageController._menu = function() {};
511
512                         contentRegion.view = new media.view.EditImage.Details( {
513                                 model: this.model,
514                                 frame: this,
515                                 controller: editImageController
516                         } );
517                 },
518
519                 editImageModeRender: function( view ) {
520                         view.on( 'ready', view.loadEditor );
521                 },
522
523                 toggleNav: function() {
524                         this.$('.left').toggleClass( 'disabled', ! this.hasPrevious() );
525                         this.$('.right').toggleClass( 'disabled', ! this.hasNext() );
526                 },
527
528                 /**
529                  * Rerender the view.
530                  */
531                 rerender: function() {
532                         // Only rerender the `content` region.
533                         if ( this.content.mode() !== 'edit-metadata' ) {
534                                 this.content.mode( 'edit-metadata' );
535                         } else {
536                                 this.content.render();
537                         }
538
539                         this.toggleNav();
540                 },
541
542                 /**
543                  * Click handler to switch to the previous media item.
544                  */
545                 previousMediaItem: function() {
546                         if ( ! this.hasPrevious() ) {
547                                 this.$( '.left' ).blur();
548                                 return;
549                         }
550                         this.model = this.library.at( this.getCurrentIndex() - 1 );
551                         this.rerender();
552                         this.$( '.left' ).focus();
553                 },
554
555                 /**
556                  * Click handler to switch to the next media item.
557                  */
558                 nextMediaItem: function() {
559                         if ( ! this.hasNext() ) {
560                                 this.$( '.right' ).blur();
561                                 return;
562                         }
563                         this.model = this.library.at( this.getCurrentIndex() + 1 );
564                         this.rerender();
565                         this.$( '.right' ).focus();
566                 },
567
568                 getCurrentIndex: function() {
569                         return this.library.indexOf( this.model );
570                 },
571
572                 hasNext: function() {
573                         return ( this.getCurrentIndex() + 1 ) < this.library.length;
574                 },
575
576                 hasPrevious: function() {
577                         return ( this.getCurrentIndex() - 1 ) > -1;
578                 },
579                 /**
580                  * Respond to the keyboard events: right arrow, left arrow, escape.
581                  */
582                 keyEvent: function( event ) {
583                         if ( 'INPUT' === event.target.tagName && ! ( event.target.readOnly || event.target.disabled ) ) {
584                                 return;
585                         }
586
587                         // The right arrow key
588                         if ( 39 === event.keyCode ) {
589                                 this.nextMediaItem();
590                         }
591                         // The left arrow key
592                         if ( 37 === event.keyCode ) {
593                                 this.previousMediaItem();
594                         }
595                 },
596
597                 resetRoute: function() {
598                         this.gridRouter.navigate( this.gridRouter.baseUrl( '' ) );
599                 }
600         });
601
602         media.view.SelectModeToggleButton = media.view.Button.extend({
603                 initialize: function() {
604                         media.view.Button.prototype.initialize.apply( this, arguments );
605                         this.listenTo( this.controller, 'select:activate select:deactivate', this.toggleBulkEditHandler );
606                         this.listenTo( this.controller, 'selection:action:done', this.back );
607                 },
608
609                 back: function () {
610                         this.controller.deactivateMode( 'select' ).activateMode( 'edit' );
611                 },
612
613                 click: function() {
614                         media.view.Button.prototype.click.apply( this, arguments );
615                         if ( this.controller.isModeActive( 'select' ) ) {
616                                 this.back();
617                         } else {
618                                 this.controller.deactivateMode( 'edit' ).activateMode( 'select' );
619                         }
620                 },
621
622                 render: function() {
623                         media.view.Button.prototype.render.apply( this, arguments );
624                         this.$el.addClass( 'select-mode-toggle-button' );
625                         return this;
626                 },
627
628                 toggleBulkEditHandler: function() {
629                         var toolbar = this.controller.content.get().toolbar, children;
630
631                         children = toolbar.$( '.media-toolbar-secondary > *, .media-toolbar-primary > *');
632
633                         if ( this.controller.isModeActive( 'select' ) ) {
634                                 this.model.set( 'text', l10n.cancelSelection );
635                                 children.not( '.delete-selected-button' ).hide();
636                                 toolbar.$( '.select-mode-toggle-button' ).show();
637                                 toolbar.$( '.delete-selected-button' ).removeClass( 'hidden' );
638                         } else {
639                                 this.model.set( 'text', l10n.bulkSelect );
640                                 this.controller.content.get().$el.removeClass('fixed');
641                                 toolbar.$el.css('width', '');
642                                 toolbar.$( '.delete-selected-button' ).addClass( 'hidden' );
643                                 children.not( '.spinner, .delete-selected-button' ).show();
644                                 this.controller.state().get( 'selection' ).reset();
645                         }
646                 }
647         });
648
649         media.view.DeleteSelectedButton = media.view.Button.extend({
650                 initialize: function() {
651                         media.view.Button.prototype.initialize.apply( this, arguments );
652                         if ( this.options.filters ) {
653                                 this.listenTo( this.options.filters.model, 'change', this.filterChange );
654                         }
655                         this.listenTo( this.controller, 'selection:toggle', this.toggleDisabled );
656                 },
657
658                 filterChange: function( model ) {
659                         if ( 'trash' === model.get( 'status' ) ) {
660                                 this.model.set( 'text', l10n.untrashSelected );
661                         } else if ( media.view.settings.mediaTrash ) {
662                                 this.model.set( 'text', l10n.trashSelected );
663                         } else {
664                                 this.model.set( 'text', l10n.deleteSelected );
665                         }
666                 },
667
668                 toggleDisabled: function() {
669                         this.model.set( 'disabled', ! this.controller.state().get( 'selection' ).length );
670                 },
671
672                 render: function() {
673                         media.view.Button.prototype.render.apply( this, arguments );
674                         if ( this.controller.isModeActive( 'select' ) ) {
675                                 this.$el.addClass( 'delete-selected-button' );
676                         } else {
677                                 this.$el.addClass( 'delete-selected-button hidden' );
678                         }
679                         return this;
680                 }
681         });
682
683         /**
684          * A filter dropdown for month/dates.
685          */
686         media.view.DateFilter = media.view.AttachmentFilters.extend({
687                 id: 'media-attachment-date-filters',
688
689                 createFilters: function() {
690                         var filters = {};
691                         _.each( media.view.settings.months || {}, function( value, index ) {
692                                 filters[ index ] = {
693                                         text: value.text,
694                                         props: {
695                                                 year: value.year,
696                                                 monthnum: value.month
697                                         }
698                                 };
699                         });
700                         filters.all = {
701                                 text:  l10n.allDates,
702                                 props: {
703                                         monthnum: false,
704                                         year:  false
705                                 },
706                                 priority: 10
707                         };
708                         this.filters = filters;
709                 }
710         });
711
712 }(jQuery, _, Backbone, wp));