]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-admin/js/image-edit.js
WordPress 4.7.2-scripts
[autoinstalls/wordpress.git] / wp-admin / js / image-edit.js
1 /* global imageEditL10n, ajaxurl, confirm */
2
3 (function($) {
4 var imageEdit = window.imageEdit = {
5         iasapi : {},
6         hold : {},
7         postid : '',
8         _view : false,
9
10         intval : function(f) {
11                 /*
12                  * Bitwise OR operator: one of the obscure ways to truncate floating point figures,
13                  * worth reminding JavaScript doesn't have a distinct "integer" type.
14                  */
15                 return f | 0;
16         },
17
18         setDisabled : function( el, s ) {
19                 /*
20                  * `el` can be a single form element or a fieldset. Before #28864, the disabled state on
21                  * some text fields  was handled targeting $('input', el). Now we need to handle the
22                  * disabled state on buttons too so we can just target `el` regardless if it's a single
23                  * element or a fieldset because when a fieldset is disabled, its descendants are disabled too.
24                  */
25                 if ( s ) {
26                         el.removeClass( 'disabled' ).prop( 'disabled', false );
27                 } else {
28                         el.addClass( 'disabled' ).prop( 'disabled', true );
29                 }
30         },
31
32         init : function(postid) {
33                 var t = this, old = $('#image-editor-' + t.postid),
34                         x = t.intval( $('#imgedit-x-' + postid).val() ),
35                         y = t.intval( $('#imgedit-y-' + postid).val() );
36
37                 if ( t.postid !== postid && old.length ) {
38                         t.close(t.postid);
39                 }
40
41                 t.hold.w = t.hold.ow = x;
42                 t.hold.h = t.hold.oh = y;
43                 t.hold.xy_ratio = x / y;
44                 t.hold.sizer = parseFloat( $('#imgedit-sizer-' + postid).val() );
45                 t.postid = postid;
46                 $('#imgedit-response-' + postid).empty();
47
48                 $('input[type="text"]', '#imgedit-panel-' + postid).keypress(function(e) {
49                         var k = e.keyCode;
50
51                         if ( 36 < k && k < 41 ) {
52                                 $(this).blur();
53                         }
54
55                         if ( 13 === k ) {
56                                 e.preventDefault();
57                                 e.stopPropagation();
58                                 return false;
59                         }
60                 });
61         },
62
63         toggleEditor : function(postid, toggle) {
64                 var wait = $('#imgedit-wait-' + postid);
65
66                 if ( toggle ) {
67                         wait.fadeIn( 'fast' );
68                 } else {
69                         wait.fadeOut('fast');
70                 }
71         },
72
73         toggleHelp : function(el) {
74                 var $el = $( el );
75                 $el
76                         .attr( 'aria-expanded', 'false' === $el.attr( 'aria-expanded' ) ? 'true' : 'false' )
77                         .parents( '.imgedit-group-top' ).toggleClass( 'imgedit-help-toggled' ).find( '.imgedit-help' ).slideToggle( 'fast' );
78
79                 return false;
80         },
81
82         getTarget : function(postid) {
83                 return $('input[name="imgedit-target-' + postid + '"]:checked', '#imgedit-save-target-' + postid).val() || 'full';
84         },
85
86         scaleChanged : function( postid, x, el ) {
87                 var w = $('#imgedit-scale-width-' + postid), h = $('#imgedit-scale-height-' + postid),
88                 warn = $('#imgedit-scale-warn-' + postid), w1 = '', h1 = '';
89
90                 if ( false === this.validateNumeric( el ) ) {
91                         return;
92                 }
93
94                 if ( x ) {
95                         h1 = ( w.val() !== '' ) ? Math.round( w.val() / this.hold.xy_ratio ) : '';
96                         h.val( h1 );
97                 } else {
98                         w1 = ( h.val() !== '' ) ? Math.round( h.val() * this.hold.xy_ratio ) : '';
99                         w.val( w1 );
100                 }
101
102                 if ( ( h1 && h1 > this.hold.oh ) || ( w1 && w1 > this.hold.ow ) ) {
103                         warn.css('visibility', 'visible');
104                 } else {
105                         warn.css('visibility', 'hidden');
106                 }
107         },
108
109         getSelRatio : function(postid) {
110                 var x = this.hold.w, y = this.hold.h,
111                         X = this.intval( $('#imgedit-crop-width-' + postid).val() ),
112                         Y = this.intval( $('#imgedit-crop-height-' + postid).val() );
113
114                 if ( X && Y ) {
115                         return X + ':' + Y;
116                 }
117
118                 if ( x && y ) {
119                         return x + ':' + y;
120                 }
121
122                 return '1:1';
123         },
124
125         filterHistory : function(postid, setSize) {
126                 // apply undo state to history
127                 var history = $('#imgedit-history-' + postid).val(), pop, n, o, i, op = [];
128
129                 if ( history !== '' ) {
130                         history = JSON.parse(history);
131                         pop = this.intval( $('#imgedit-undone-' + postid).val() );
132                         if ( pop > 0 ) {
133                                 while ( pop > 0 ) {
134                                         history.pop();
135                                         pop--;
136                                 }
137                         }
138
139                         if ( setSize ) {
140                                 if ( !history.length ) {
141                                         this.hold.w = this.hold.ow;
142                                         this.hold.h = this.hold.oh;
143                                         return '';
144                                 }
145
146                                 // restore
147                                 o = history[history.length - 1];
148                                 o = o.c || o.r || o.f || false;
149
150                                 if ( o ) {
151                                         this.hold.w = o.fw;
152                                         this.hold.h = o.fh;
153                                 }
154                         }
155
156                         // filter the values
157                         for ( n in history ) {
158                                 i = history[n];
159                                 if ( i.hasOwnProperty('c') ) {
160                                         op[n] = { 'c': { 'x': i.c.x, 'y': i.c.y, 'w': i.c.w, 'h': i.c.h } };
161                                 } else if ( i.hasOwnProperty('r') ) {
162                                         op[n] = { 'r': i.r.r };
163                                 } else if ( i.hasOwnProperty('f') ) {
164                                         op[n] = { 'f': i.f.f };
165                                 }
166                         }
167                         return JSON.stringify(op);
168                 }
169                 return '';
170         },
171
172         refreshEditor : function(postid, nonce, callback) {
173                 var t = this, data, img;
174
175                 t.toggleEditor(postid, 1);
176                 data = {
177                         'action': 'imgedit-preview',
178                         '_ajax_nonce': nonce,
179                         'postid': postid,
180                         'history': t.filterHistory(postid, 1),
181                         'rand': t.intval(Math.random() * 1000000)
182                 };
183
184                 img = $( '<img id="image-preview-' + postid + '" alt="" />' )
185                         .on( 'load', { history: data.history }, function( event ) {
186                                 var max1, max2,
187                                         parent = $( '#imgedit-crop-' + postid ),
188                                         t = imageEdit,
189                                         historyObj;
190
191                                 if ( '' !== event.data.history ) {
192                                         historyObj = JSON.parse( event.data.history );
193                                         // If last executed action in history is a crop action.
194                                         if ( historyObj[historyObj.length - 1].hasOwnProperty( 'c' ) ) {
195                                                 /*
196                                                  * A crop action has completed and the crop button gets disabled
197                                                  * ensure the undo button is enabled.
198                                                  */
199                                                 t.setDisabled( $( '#image-undo-' + postid) , true );
200                                                 // Move focus to the undo button to avoid a focus loss.
201                                                 $( '#image-undo-' + postid ).focus();
202                                         }
203                                 }
204
205                                 parent.empty().append(img);
206
207                                 // w, h are the new full size dims
208                                 max1 = Math.max( t.hold.w, t.hold.h );
209                                 max2 = Math.max( $(img).width(), $(img).height() );
210                                 t.hold.sizer = max1 > max2 ? max2 / max1 : 1;
211
212                                 t.initCrop(postid, img, parent);
213                                 t.setCropSelection(postid, 0);
214
215                                 if ( (typeof callback !== 'undefined') && callback !== null ) {
216                                         callback();
217                                 }
218
219                                 if ( $('#imgedit-history-' + postid).val() && $('#imgedit-undone-' + postid).val() === '0' ) {
220                                         $('input.imgedit-submit-btn', '#imgedit-panel-' + postid).removeAttr('disabled');
221                                 } else {
222                                         $('input.imgedit-submit-btn', '#imgedit-panel-' + postid).prop('disabled', true);
223                                 }
224
225                                 t.toggleEditor(postid, 0);
226                         })
227                         .on('error', function() {
228                                 $('#imgedit-crop-' + postid).empty().append('<div class="error"><p>' + imageEditL10n.error + '</p></div>');
229                                 t.toggleEditor(postid, 0);
230                         })
231                         .attr('src', ajaxurl + '?' + $.param(data));
232         },
233
234         action : function(postid, nonce, action) {
235                 var t = this, data, w, h, fw, fh;
236
237                 if ( t.notsaved(postid) ) {
238                         return false;
239                 }
240
241                 data = {
242                         'action': 'image-editor',
243                         '_ajax_nonce': nonce,
244                         'postid': postid
245                 };
246
247                 if ( 'scale' === action ) {
248                         w = $('#imgedit-scale-width-' + postid),
249                         h = $('#imgedit-scale-height-' + postid),
250                         fw = t.intval(w.val()),
251                         fh = t.intval(h.val());
252
253                         if ( fw < 1 ) {
254                                 w.focus();
255                                 return false;
256                         } else if ( fh < 1 ) {
257                                 h.focus();
258                                 return false;
259                         }
260
261                         if ( fw === t.hold.ow || fh === t.hold.oh ) {
262                                 return false;
263                         }
264
265                         data['do'] = 'scale';
266                         data.fwidth = fw;
267                         data.fheight = fh;
268                 } else if ( 'restore' === action ) {
269                         data['do'] = 'restore';
270                 } else {
271                         return false;
272                 }
273
274                 t.toggleEditor(postid, 1);
275                 $.post(ajaxurl, data, function(r) {
276                         $('#image-editor-' + postid).empty().append(r);
277                         t.toggleEditor(postid, 0);
278                         // refresh the attachment model so that changes propagate
279                         if ( t._view ) {
280                                 t._view.refresh();
281                         }
282                 });
283         },
284
285         save : function(postid, nonce) {
286                 var data,
287                         target = this.getTarget(postid),
288                         history = this.filterHistory(postid, 0),
289                         self = this;
290
291                 if ( '' === history ) {
292                         return false;
293                 }
294
295                 this.toggleEditor(postid, 1);
296                 data = {
297                         'action': 'image-editor',
298                         '_ajax_nonce': nonce,
299                         'postid': postid,
300                         'history': history,
301                         'target': target,
302                         'context': $('#image-edit-context').length ? $('#image-edit-context').val() : null,
303                         'do': 'save'
304                 };
305
306                 $.post(ajaxurl, data, function(r) {
307                         var ret = JSON.parse(r);
308
309                         if ( ret.error ) {
310                                 $('#imgedit-response-' + postid).html('<div class="error"><p>' + ret.error + '</p></div>');
311                                 imageEdit.close(postid);
312                                 return;
313                         }
314
315                         if ( ret.fw && ret.fh ) {
316                                 $('#media-dims-' + postid).html( ret.fw + ' &times; ' + ret.fh );
317                         }
318
319                         if ( ret.thumbnail ) {
320                                 $('.thumbnail', '#thumbnail-head-' + postid).attr('src', ''+ret.thumbnail);
321                         }
322
323                         if ( ret.msg ) {
324                                 $('#imgedit-response-' + postid).html('<div class="updated"><p>' + ret.msg + '</p></div>');
325                         }
326
327                         if ( self._view ) {
328                                 self._view.save();
329                         } else {
330                                 imageEdit.close(postid);
331                         }
332                 });
333         },
334
335         open : function( postid, nonce, view ) {
336                 this._view = view;
337
338                 var dfd, data, elem = $('#image-editor-' + postid), head = $('#media-head-' + postid),
339                         btn = $('#imgedit-open-btn-' + postid), spin = btn.siblings('.spinner');
340
341                 /*
342                  * Instead of disabling the button, which causes a focus loss and makes screen
343                  * readers announce "unavailable", return if the button was already clicked.
344                  */
345                 if ( btn.hasClass( 'button-activated' ) ) {
346                         return;
347                 }
348
349                 spin.addClass( 'is-active' );
350
351                 data = {
352                         'action': 'image-editor',
353                         '_ajax_nonce': nonce,
354                         'postid': postid,
355                         'do': 'open'
356                 };
357
358                 dfd = $.ajax({
359                         url:  ajaxurl,
360                         type: 'post',
361                         data: data,
362                         beforeSend: function() {
363                                 btn.addClass( 'button-activated' );
364                         }
365                 }).done(function( html ) {
366                         elem.html( html );
367                         head.fadeOut('fast', function(){
368                                 elem.fadeIn('fast');
369                                 btn.removeClass( 'button-activated' );
370                                 spin.removeClass( 'is-active' );
371                         });
372                         // Initialise the Image Editor now that everything is ready.
373                         imageEdit.init( postid );
374                 });
375
376                 return dfd;
377         },
378
379         imgLoaded : function(postid) {
380                 var img = $('#image-preview-' + postid), parent = $('#imgedit-crop-' + postid);
381
382                 this.initCrop(postid, img, parent);
383                 this.setCropSelection(postid, 0);
384                 this.toggleEditor(postid, 0);
385                 // Editor is ready, move focus to the first focusable element.
386                 $( '.imgedit-wrap .imgedit-help-toggle' ).eq( 0 ).focus();
387         },
388
389         initCrop : function(postid, image, parent) {
390                 var t = this,
391                         selW = $('#imgedit-sel-width-' + postid),
392                         selH = $('#imgedit-sel-height-' + postid),
393                         $img;
394
395                 t.iasapi = $(image).imgAreaSelect({
396                         parent: parent,
397                         instance: true,
398                         handles: true,
399                         keys: true,
400                         minWidth: 3,
401                         minHeight: 3,
402
403                         onInit: function( img ) {
404                                 // Ensure that the imgareaselect wrapper elements are position:absolute
405                                 // (even if we're in a position:fixed modal)
406                                 $img = $( img );
407                                 $img.next().css( 'position', 'absolute' )
408                                         .nextAll( '.imgareaselect-outer' ).css( 'position', 'absolute' );
409
410                                 parent.children().mousedown(function(e){
411                                         var ratio = false, sel, defRatio;
412
413                                         if ( e.shiftKey ) {
414                                                 sel = t.iasapi.getSelection();
415                                                 defRatio = t.getSelRatio(postid);
416                                                 ratio = ( sel && sel.width && sel.height ) ? sel.width + ':' + sel.height : defRatio;
417                                         }
418
419                                         t.iasapi.setOptions({
420                                                 aspectRatio: ratio
421                                         });
422                                 });
423                         },
424
425                         onSelectStart: function() {
426                                 imageEdit.setDisabled($('#imgedit-crop-sel-' + postid), 1);
427                         },
428
429                         onSelectEnd: function(img, c) {
430                                 imageEdit.setCropSelection(postid, c);
431                         },
432
433                         onSelectChange: function(img, c) {
434                                 var sizer = imageEdit.hold.sizer;
435                                 selW.val( imageEdit.round(c.width / sizer) );
436                                 selH.val( imageEdit.round(c.height / sizer) );
437                         }
438                 });
439         },
440
441         setCropSelection : function(postid, c) {
442                 var sel;
443
444                 c = c || 0;
445
446                 if ( !c || ( c.width < 3 && c.height < 3 ) ) {
447                         this.setDisabled($('.imgedit-crop', '#imgedit-panel-' + postid), 0);
448                         this.setDisabled($('#imgedit-crop-sel-' + postid), 0);
449                         $('#imgedit-sel-width-' + postid).val('');
450                         $('#imgedit-sel-height-' + postid).val('');
451                         $('#imgedit-selection-' + postid).val('');
452                         return false;
453                 }
454
455                 sel = { 'x': c.x1, 'y': c.y1, 'w': c.width, 'h': c.height };
456                 this.setDisabled($('.imgedit-crop', '#imgedit-panel-' + postid), 1);
457                 $('#imgedit-selection-' + postid).val( JSON.stringify(sel) );
458         },
459
460         close : function(postid, warn) {
461                 warn = warn || false;
462
463                 if ( warn && this.notsaved(postid) ) {
464                         return false;
465                 }
466
467                 this.iasapi = {};
468                 this.hold = {};
469
470                 // If we've loaded the editor in the context of a Media Modal, then switch to the previous view,
471                 // whatever that might have been.
472                 if ( this._view ){
473                         this._view.back();
474                 }
475
476                 // In case we are not accessing the image editor in the context of a View, close the editor the old-skool way
477                 else {
478                         $('#image-editor-' + postid).fadeOut('fast', function() {
479                                 $( '#media-head-' + postid ).fadeIn( 'fast', function() {
480                                         // Move focus back to the Edit Image button. Runs also when saving.
481                                         $( '#imgedit-open-btn-' + postid ).focus();
482                                 });
483                                 $(this).empty();
484                         });
485                 }
486
487
488         },
489
490         notsaved : function(postid) {
491                 var h = $('#imgedit-history-' + postid).val(),
492                         history = ( h !== '' ) ? JSON.parse(h) : [],
493                         pop = this.intval( $('#imgedit-undone-' + postid).val() );
494
495                 if ( pop < history.length ) {
496                         if ( confirm( $('#imgedit-leaving-' + postid).html() ) ) {
497                                 return false;
498                         }
499                         return true;
500                 }
501                 return false;
502         },
503
504         addStep : function(op, postid, nonce) {
505                 var t = this, elem = $('#imgedit-history-' + postid),
506                         history = ( elem.val() !== '' ) ? JSON.parse( elem.val() ) : [],
507                         undone = $( '#imgedit-undone-' + postid ),
508                         pop = t.intval( undone.val() );
509
510                 while ( pop > 0 ) {
511                         history.pop();
512                         pop--;
513                 }
514                 undone.val(0); // reset
515
516                 history.push(op);
517                 elem.val( JSON.stringify(history) );
518
519                 t.refreshEditor(postid, nonce, function() {
520                         t.setDisabled($('#image-undo-' + postid), true);
521                         t.setDisabled($('#image-redo-' + postid), false);
522                 });
523         },
524
525         rotate : function(angle, postid, nonce, t) {
526                 if ( $(t).hasClass('disabled') ) {
527                         return false;
528                 }
529
530                 this.addStep({ 'r': { 'r': angle, 'fw': this.hold.h, 'fh': this.hold.w }}, postid, nonce);
531         },
532
533         flip : function (axis, postid, nonce, t) {
534                 if ( $(t).hasClass('disabled') ) {
535                         return false;
536                 }
537
538                 this.addStep({ 'f': { 'f': axis, 'fw': this.hold.w, 'fh': this.hold.h }}, postid, nonce);
539         },
540
541         crop : function (postid, nonce, t) {
542                 var sel = $('#imgedit-selection-' + postid).val(),
543                         w = this.intval( $('#imgedit-sel-width-' + postid).val() ),
544                         h = this.intval( $('#imgedit-sel-height-' + postid).val() );
545
546                 if ( $(t).hasClass('disabled') || sel === '' ) {
547                         return false;
548                 }
549
550                 sel = JSON.parse(sel);
551                 if ( sel.w > 0 && sel.h > 0 && w > 0 && h > 0 ) {
552                         sel.fw = w;
553                         sel.fh = h;
554                         this.addStep({ 'c': sel }, postid, nonce);
555                 }
556         },
557
558         undo : function (postid, nonce) {
559                 var t = this, button = $('#image-undo-' + postid), elem = $('#imgedit-undone-' + postid),
560                         pop = t.intval( elem.val() ) + 1;
561
562                 if ( button.hasClass('disabled') ) {
563                         return;
564                 }
565
566                 elem.val(pop);
567                 t.refreshEditor(postid, nonce, function() {
568                         var elem = $('#imgedit-history-' + postid),
569                                 history = ( elem.val() !== '' ) ? JSON.parse( elem.val() ) : [];
570
571                         t.setDisabled($('#image-redo-' + postid), true);
572                         t.setDisabled(button, pop < history.length);
573                         // When undo gets disabled, move focus to the redo button to avoid a focus loss.
574                         if ( history.length === pop ) {
575                                 $( '#image-redo-' + postid ).focus();
576                         }
577                 });
578         },
579
580         redo : function(postid, nonce) {
581                 var t = this, button = $('#image-redo-' + postid), elem = $('#imgedit-undone-' + postid),
582                         pop = t.intval( elem.val() ) - 1;
583
584                 if ( button.hasClass('disabled') ) {
585                         return;
586                 }
587
588                 elem.val(pop);
589                 t.refreshEditor(postid, nonce, function() {
590                         t.setDisabled($('#image-undo-' + postid), true);
591                         t.setDisabled(button, pop > 0);
592                         // When redo gets disabled, move focus to the undo button to avoid a focus loss.
593                         if ( 0 === pop ) {
594                                 $( '#image-undo-' + postid ).focus();
595                         }
596                 });
597         },
598
599         setNumSelection : function( postid, el ) {
600                 var sel, elX = $('#imgedit-sel-width-' + postid), elY = $('#imgedit-sel-height-' + postid),
601                         x = this.intval( elX.val() ), y = this.intval( elY.val() ),
602                         img = $('#image-preview-' + postid), imgh = img.height(), imgw = img.width(),
603                         sizer = this.hold.sizer, x1, y1, x2, y2, ias = this.iasapi;
604
605                 if ( false === this.validateNumeric( el ) ) {
606                         return;
607                 }
608
609                 if ( x < 1 ) {
610                         elX.val('');
611                         return false;
612                 }
613
614                 if ( y < 1 ) {
615                         elY.val('');
616                         return false;
617                 }
618
619                 if ( x && y && ( sel = ias.getSelection() ) ) {
620                         x2 = sel.x1 + Math.round( x * sizer );
621                         y2 = sel.y1 + Math.round( y * sizer );
622                         x1 = sel.x1;
623                         y1 = sel.y1;
624
625                         if ( x2 > imgw ) {
626                                 x1 = 0;
627                                 x2 = imgw;
628                                 elX.val( Math.round( x2 / sizer ) );
629                         }
630
631                         if ( y2 > imgh ) {
632                                 y1 = 0;
633                                 y2 = imgh;
634                                 elY.val( Math.round( y2 / sizer ) );
635                         }
636
637                         ias.setSelection( x1, y1, x2, y2 );
638                         ias.update();
639                         this.setCropSelection(postid, ias.getSelection());
640                 }
641         },
642
643         round : function(num) {
644                 var s;
645                 num = Math.round(num);
646
647                 if ( this.hold.sizer > 0.6 ) {
648                         return num;
649                 }
650
651                 s = num.toString().slice(-1);
652
653                 if ( '1' === s ) {
654                         return num - 1;
655                 } else if ( '9' === s ) {
656                         return num + 1;
657                 }
658
659                 return num;
660         },
661
662         setRatioSelection : function(postid, n, el) {
663                 var sel, r, x = this.intval( $('#imgedit-crop-width-' + postid).val() ),
664                         y = this.intval( $('#imgedit-crop-height-' + postid).val() ),
665                         h = $('#image-preview-' + postid).height();
666
667                 if ( false === this.validateNumeric( el ) ) {
668                         return;
669                 }
670
671                 if ( x && y ) {
672                         this.iasapi.setOptions({
673                                 aspectRatio: x + ':' + y
674                         });
675
676                         if ( sel = this.iasapi.getSelection(true) ) {
677                                 r = Math.ceil( sel.y1 + ( ( sel.x2 - sel.x1 ) / ( x / y ) ) );
678
679                                 if ( r > h ) {
680                                         r = h;
681                                         if ( n ) {
682                                                 $('#imgedit-crop-height-' + postid).val('');
683                                         } else {
684                                                 $('#imgedit-crop-width-' + postid).val('');
685                                         }
686                                 }
687
688                                 this.iasapi.setSelection( sel.x1, sel.y1, sel.x2, r );
689                                 this.iasapi.update();
690                         }
691                 }
692         },
693
694         validateNumeric: function( el ) {
695                 if ( ! this.intval( $( el ).val() ) ) {
696                         $( el ).val( '' );
697                         return false;
698                 }
699         }
700 };
701 })(jQuery);