5bf3716d5c7414ccff0dc91828d5e94d54adbafb
[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                 },
392
393                 initialize: function() {
394                         media.view.Frame.prototype.initialize.apply( this, arguments );
395
396                         _.defaults( this.options, {
397                                 modal: true,
398                                 state: 'edit-attachment'
399                         });
400
401                         this.controller = this.options.controller;
402                         this.gridRouter = this.controller.gridRouter;
403                         this.library = this.options.library;
404
405                         if ( this.options.model ) {
406                                 this.model = this.options.model;
407                         }
408
409                         this.bindHandlers();
410                         this.createStates();
411                         this.createModal();
412
413                         this.title.mode( 'default' );
414                         this.toggleNav();
415                 },
416
417                 bindHandlers: function() {
418                         // Bind default title creation.
419                         this.on( 'title:create:default', this.createTitle, this );
420
421                         // Close the modal if the attachment is deleted.
422                         this.listenTo( this.model, 'change:status destroy', this.close, this );
423
424                         this.on( 'content:create:edit-metadata', this.editMetadataMode, this );
425                         this.on( 'content:create:edit-image', this.editImageMode, this );
426                         this.on( 'content:render:edit-image', this.editImageModeRender, this );
427                         this.on( 'close', this.detach );
428                 },
429
430                 createModal: function() {
431                         var self = this;
432
433                         // Initialize modal container view.
434                         if ( this.options.modal ) {
435                                 this.modal = new media.view.Modal({
436                                         controller: this,
437                                         title:      this.options.title
438                                 });
439
440                                 this.modal.on( 'open', function () {
441                                         $( 'body' ).on( 'keydown.media-modal', _.bind( self.keyEvent, self ) );
442                                 } );
443
444                                 // Completely destroy the modal DOM element when closing it.
445                                 this.modal.on( 'close', function() {
446                                         self.modal.remove();
447                                         $( 'body' ).off( 'keydown.media-modal' ); /* remove the keydown event */
448                                         // Restore the original focus item if possible
449                                         $( 'li.attachment[data-id="' + self.model.get( 'id' ) +'"]' ).focus();
450                                         self.resetRoute();
451                                 } );
452
453                                 // Set this frame as the modal's content.
454                                 this.modal.content( this );
455                                 this.modal.open();
456                         }
457                 },
458
459                 /**
460                  * Add the default states to the frame.
461                  */
462                 createStates: function() {
463                         this.states.add([
464                                 new media.controller.EditAttachmentMetadata( { model: this.model } )
465                         ]);
466                 },
467
468                 /**
469                  * Content region rendering callback for the `edit-metadata` mode.
470                  *
471                  * @param {Object} contentRegion Basic object with a `view` property, which
472                  *                               should be set with the proper region view.
473                  */
474                 editMetadataMode: function( contentRegion ) {
475                         contentRegion.view = new media.view.Attachment.Details.TwoColumn({
476                                 controller: this,
477                                 model:      this.model
478                         });
479
480                         /**
481                          * Attach a subview to display fields added via the
482                          * `attachment_fields_to_edit` filter.
483                          */
484                         contentRegion.view.views.set( '.attachment-compat', new media.view.AttachmentCompat({
485                                 controller: this,
486                                 model:      this.model
487                         }) );
488
489                         // Update browser url when navigating media details
490                         if ( this.model ) {
491                                 this.gridRouter.navigate( this.gridRouter.baseUrl( '?item=' + this.model.id ) );
492                         }
493                 },
494
495                 /**
496                  * Render the EditImage view into the frame's content region.
497                  *
498                  * @param {Object} contentRegion Basic object with a `view` property, which
499                  *                               should be set with the proper region view.
500                  */
501                 editImageMode: function( contentRegion ) {
502                         var editImageController = new media.controller.EditImage( {
503                                 model: this.model,
504                                 frame: this
505                         } );
506                         // Noop some methods.
507                         editImageController._toolbar = function() {};
508                         editImageController._router = function() {};
509                         editImageController._menu = function() {};
510
511                         contentRegion.view = new media.view.EditImage.Details( {
512                                 model: this.model,
513                                 frame: this,
514                                 controller: editImageController
515                         } );
516                 },
517
518                 editImageModeRender: function( view ) {
519                         view.on( 'ready', view.loadEditor );
520                 },
521
522                 toggleNav: function() {
523                         this.$('.left').toggleClass( 'disabled', ! this.hasPrevious() );
524                         this.$('.right').toggleClass( 'disabled', ! this.hasNext() );
525                 },
526
527                 /**
528                  * Rerender the view.
529                  */
530                 rerender: function() {
531                         // Only rerender the `content` region.
532                         if ( this.content.mode() !== 'edit-metadata' ) {
533                                 this.content.mode( 'edit-metadata' );
534                         } else {
535                                 this.content.render();
536                         }
537
538                         this.toggleNav();
539                 },
540
541                 /**
542                  * Click handler to switch to the previous media item.
543                  */
544                 previousMediaItem: function() {
545                         if ( ! this.hasPrevious() ) {
546                                 this.$( '.left' ).blur();
547                                 return;
548                         }
549                         this.model = this.library.at( this.getCurrentIndex() - 1 );
550                         this.rerender();
551                         this.$( '.left' ).focus();
552                 },
553
554                 /**
555                  * Click handler to switch to the next media item.
556                  */
557                 nextMediaItem: function() {
558                         if ( ! this.hasNext() ) {
559                                 this.$( '.right' ).blur();
560                                 return;
561                         }
562                         this.model = this.library.at( this.getCurrentIndex() + 1 );
563                         this.rerender();
564                         this.$( '.right' ).focus();
565                 },
566
567                 getCurrentIndex: function() {
568                         return this.library.indexOf( this.model );
569                 },
570
571                 hasNext: function() {
572                         return ( this.getCurrentIndex() + 1 ) < this.library.length;
573                 },
574
575                 hasPrevious: function() {
576                         return ( this.getCurrentIndex() - 1 ) > -1;
577                 },
578                 /**
579                  * Respond to the keyboard events: right arrow, left arrow, except when
580                  * focus is in a textarea or input field.
581                  */
582                 keyEvent: function( event ) {
583                         if ( ( 'INPUT' === event.target.nodeName || 'TEXTAREA' === event.target.nodeName ) && ! ( 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                         // TODO: the Frame should be doing all of this.
634                         if ( this.controller.isModeActive( 'select' ) ) {
635                                 this.model.set( 'text', l10n.cancelSelection );
636                                 children.not( '.media-button' ).hide();
637                                 this.$el.show();
638                                 toolbar.$( '.delete-selected-button' ).removeClass( 'hidden' );
639                         } else {
640                                 this.model.set( 'text', l10n.bulkSelect );
641                                 this.controller.content.get().$el.removeClass( 'fixed' );
642                                 toolbar.$el.css( 'width', '' );
643                                 toolbar.$( '.delete-selected-button' ).addClass( 'hidden' );
644                                 children.not( '.spinner, .media-button' ).show();
645                                 this.controller.state().get( 'selection' ).reset();
646                         }
647                 }
648         });
649
650         /**
651          * A button that handles bulk Delete/Trash logic
652          *
653          * @constructor
654          * @augments wp.media.view.Button
655          * @augments wp.media.View
656          * @augments wp.Backbone.View
657          * @augments Backbone.View
658          */
659         media.view.DeleteSelectedButton = media.view.Button.extend({
660                 initialize: function() {
661                         media.view.Button.prototype.initialize.apply( this, arguments );
662                         if ( this.options.filters ) {
663                                 this.listenTo( this.options.filters.model, 'change', this.filterChange );
664                         }
665                         this.listenTo( this.controller, 'selection:toggle', this.toggleDisabled );
666                 },
667
668                 filterChange: function( model ) {
669                         if ( 'trash' === model.get( 'status' ) ) {
670                                 this.model.set( 'text', l10n.untrashSelected );
671                         } else if ( media.view.settings.mediaTrash ) {
672                                 this.model.set( 'text', l10n.trashSelected );
673                         } else {
674                                 this.model.set( 'text', l10n.deleteSelected );
675                         }
676                 },
677
678                 toggleDisabled: function() {
679                         this.model.set( 'disabled', ! this.controller.state().get( 'selection' ).length );
680                 },
681
682                 render: function() {
683                         media.view.Button.prototype.render.apply( this, arguments );
684                         if ( this.controller.isModeActive( 'select' ) ) {
685                                 this.$el.addClass( 'delete-selected-button' );
686                         } else {
687                                 this.$el.addClass( 'delete-selected-button hidden' );
688                         }
689                         this.toggleDisabled();
690                         return this;
691                 }
692         });
693
694         /**
695          * When MEDIA_TRASH is true, a button that handles bulk Delete Permanently logic
696          *
697          * @constructor
698          * @augments wp.media.view.DeleteSelectedButton
699          * @augments wp.media.view.Button
700          * @augments wp.media.View
701          * @augments wp.Backbone.View
702          * @augments Backbone.View
703          */
704         media.view.DeleteSelectedPermanentlyButton = media.view.DeleteSelectedButton.extend({
705                 initialize: function() {
706                         media.view.DeleteSelectedButton.prototype.initialize.apply( this, arguments );
707                         this.listenTo( this.controller, 'select:activate', this.selectActivate );
708                         this.listenTo( this.controller, 'select:deactivate', this.selectDeactivate );
709                 },
710
711                 filterChange: function( model ) {
712                         this.canShow = ( 'trash' === model.get( 'status' ) );
713                 },
714
715                 selectActivate: function() {
716                         this.toggleDisabled();
717                         this.$el.toggleClass( 'hidden', ! this.canShow );
718                 },
719
720                 selectDeactivate: function() {
721                         this.toggleDisabled();
722                         this.$el.addClass( 'hidden' );
723                 },
724
725                 render: function() {
726                         media.view.Button.prototype.render.apply( this, arguments );
727                         this.selectActivate();
728                         return this;
729                 }
730         });
731
732 }(jQuery, _, Backbone, wp));