1 /* global imageEditL10n, ajaxurl, confirm */
4 var imageEdit = window.imageEdit = {
10 intval : function(f) {
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.
18 setDisabled : function( el, s ) {
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.
26 el.removeClass( 'disabled' ).prop( 'disabled', false );
28 el.addClass( 'disabled' ).prop( 'disabled', true );
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() );
37 if ( t.postid !== postid && old.length ) {
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() );
46 $('#imgedit-response-' + postid).empty();
48 $('input[type="text"]', '#imgedit-panel-' + postid).keypress(function(e) {
51 if ( 36 < k && k < 41 ) {
63 toggleEditor : function(postid, toggle) {
64 var wait = $('#imgedit-wait-' + postid);
67 wait.fadeIn( 'fast' );
73 toggleHelp : function(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' );
82 getTarget : function(postid) {
83 return $('input[name="imgedit-target-' + postid + '"]:checked', '#imgedit-save-target-' + postid).val() || 'full';
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 = '';
90 if ( false === this.validateNumeric( el ) ) {
95 h1 = ( w.val() !== '' ) ? Math.round( w.val() / this.hold.xy_ratio ) : '';
98 w1 = ( h.val() !== '' ) ? Math.round( h.val() * this.hold.xy_ratio ) : '';
102 if ( ( h1 && h1 > this.hold.oh ) || ( w1 && w1 > this.hold.ow ) ) {
103 warn.css('visibility', 'visible');
105 warn.css('visibility', 'hidden');
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() );
125 filterHistory : function(postid, setSize) {
126 // apply undo state to history
127 var history = $('#imgedit-history-' + postid).val(), pop, n, o, i, op = [];
129 if ( history !== '' ) {
130 history = JSON.parse(history);
131 pop = this.intval( $('#imgedit-undone-' + postid).val() );
140 if ( !history.length ) {
141 this.hold.w = this.hold.ow;
142 this.hold.h = this.hold.oh;
147 o = history[history.length - 1];
148 o = o.c || o.r || o.f || false;
157 for ( n in history ) {
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 };
167 return JSON.stringify(op);
172 refreshEditor : function(postid, nonce, callback) {
173 var t = this, data, img;
175 t.toggleEditor(postid, 1);
177 'action': 'imgedit-preview',
178 '_ajax_nonce': nonce,
180 'history': t.filterHistory(postid, 1),
181 'rand': t.intval(Math.random() * 1000000)
184 img = $( '<img id="image-preview-' + postid + '" alt="" />' )
185 .on( 'load', { history: data.history }, function( event ) {
187 parent = $( '#imgedit-crop-' + postid ),
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' ) ) {
196 * A crop action has completed and the crop button gets disabled
197 * ensure the undo button is enabled.
199 t.setDisabled( $( '#image-undo-' + postid) , true );
200 // Move focus to the undo button to avoid a focus loss.
201 $( '#image-undo-' + postid ).focus();
205 parent.empty().append(img);
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;
212 t.initCrop(postid, img, parent);
213 t.setCropSelection(postid, 0);
215 if ( (typeof callback !== 'undefined') && callback !== null ) {
219 if ( $('#imgedit-history-' + postid).val() && $('#imgedit-undone-' + postid).val() === '0' ) {
220 $('input.imgedit-submit-btn', '#imgedit-panel-' + postid).removeAttr('disabled');
222 $('input.imgedit-submit-btn', '#imgedit-panel-' + postid).prop('disabled', true);
225 t.toggleEditor(postid, 0);
227 .on('error', function() {
228 $('#imgedit-crop-' + postid).empty().append('<div class="error"><p>' + imageEditL10n.error + '</p></div>');
229 t.toggleEditor(postid, 0);
231 .attr('src', ajaxurl + '?' + $.param(data));
234 action : function(postid, nonce, action) {
235 var t = this, data, w, h, fw, fh;
237 if ( t.notsaved(postid) ) {
242 'action': 'image-editor',
243 '_ajax_nonce': nonce,
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());
256 } else if ( fh < 1 ) {
261 if ( fw === t.hold.ow || fh === t.hold.oh ) {
265 data['do'] = 'scale';
268 } else if ( 'restore' === action ) {
269 data['do'] = 'restore';
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
285 save : function(postid, nonce) {
287 target = this.getTarget(postid),
288 history = this.filterHistory(postid, 0),
291 if ( '' === history ) {
295 this.toggleEditor(postid, 1);
297 'action': 'image-editor',
298 '_ajax_nonce': nonce,
302 'context': $('#image-edit-context').length ? $('#image-edit-context').val() : null,
306 $.post(ajaxurl, data, function(r) {
307 var ret = JSON.parse(r);
310 $('#imgedit-response-' + postid).html('<div class="error"><p>' + ret.error + '</p></div>');
311 imageEdit.close(postid);
315 if ( ret.fw && ret.fh ) {
316 $('#media-dims-' + postid).html( ret.fw + ' × ' + ret.fh );
319 if ( ret.thumbnail ) {
320 $('.thumbnail', '#thumbnail-head-' + postid).attr('src', ''+ret.thumbnail);
324 $('#imgedit-response-' + postid).html('<div class="updated"><p>' + ret.msg + '</p></div>');
330 imageEdit.close(postid);
335 open : function( postid, nonce, view ) {
338 var dfd, data, elem = $('#image-editor-' + postid), head = $('#media-head-' + postid),
339 btn = $('#imgedit-open-btn-' + postid), spin = btn.siblings('.spinner');
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.
345 if ( btn.hasClass( 'button-activated' ) ) {
349 spin.addClass( 'is-active' );
352 'action': 'image-editor',
353 '_ajax_nonce': nonce,
362 beforeSend: function() {
363 btn.addClass( 'button-activated' );
365 }).done(function( html ) {
367 head.fadeOut('fast', function(){
369 btn.removeClass( 'button-activated' );
370 spin.removeClass( 'is-active' );
372 // Initialise the Image Editor now that everything is ready.
373 imageEdit.init( postid );
379 imgLoaded : function(postid) {
380 var img = $('#image-preview-' + postid), parent = $('#imgedit-crop-' + postid);
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();
389 initCrop : function(postid, image, parent) {
391 selW = $('#imgedit-sel-width-' + postid),
392 selH = $('#imgedit-sel-height-' + postid),
395 t.iasapi = $(image).imgAreaSelect({
403 onInit: function( img ) {
404 // Ensure that the imgareaselect wrapper elements are position:absolute
405 // (even if we're in a position:fixed modal)
407 $img.next().css( 'position', 'absolute' )
408 .nextAll( '.imgareaselect-outer' ).css( 'position', 'absolute' );
410 parent.children().mousedown(function(e){
411 var ratio = false, sel, defRatio;
414 sel = t.iasapi.getSelection();
415 defRatio = t.getSelRatio(postid);
416 ratio = ( sel && sel.width && sel.height ) ? sel.width + ':' + sel.height : defRatio;
419 t.iasapi.setOptions({
425 onSelectStart: function() {
426 imageEdit.setDisabled($('#imgedit-crop-sel-' + postid), 1);
429 onSelectEnd: function(img, c) {
430 imageEdit.setCropSelection(postid, c);
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) );
441 setCropSelection : function(postid, c) {
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('');
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) );
460 close : function(postid, warn) {
461 warn = warn || false;
463 if ( warn && this.notsaved(postid) ) {
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.
476 // In case we are not accessing the image editor in the context of a View, close the editor the old-skool way
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();
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() );
495 if ( pop < history.length ) {
496 if ( confirm( $('#imgedit-leaving-' + postid).html() ) ) {
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() );
514 undone.val(0); // reset
517 elem.val( JSON.stringify(history) );
519 t.refreshEditor(postid, nonce, function() {
520 t.setDisabled($('#image-undo-' + postid), true);
521 t.setDisabled($('#image-redo-' + postid), false);
525 rotate : function(angle, postid, nonce, t) {
526 if ( $(t).hasClass('disabled') ) {
530 this.addStep({ 'r': { 'r': angle, 'fw': this.hold.h, 'fh': this.hold.w }}, postid, nonce);
533 flip : function (axis, postid, nonce, t) {
534 if ( $(t).hasClass('disabled') ) {
538 this.addStep({ 'f': { 'f': axis, 'fw': this.hold.w, 'fh': this.hold.h }}, postid, nonce);
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() );
546 if ( $(t).hasClass('disabled') || sel === '' ) {
550 sel = JSON.parse(sel);
551 if ( sel.w > 0 && sel.h > 0 && w > 0 && h > 0 ) {
554 this.addStep({ 'c': sel }, postid, nonce);
558 undo : function (postid, nonce) {
559 var t = this, button = $('#image-undo-' + postid), elem = $('#imgedit-undone-' + postid),
560 pop = t.intval( elem.val() ) + 1;
562 if ( button.hasClass('disabled') ) {
567 t.refreshEditor(postid, nonce, function() {
568 var elem = $('#imgedit-history-' + postid),
569 history = ( elem.val() !== '' ) ? JSON.parse( elem.val() ) : [];
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();
580 redo : function(postid, nonce) {
581 var t = this, button = $('#image-redo-' + postid), elem = $('#imgedit-undone-' + postid),
582 pop = t.intval( elem.val() ) - 1;
584 if ( button.hasClass('disabled') ) {
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.
594 $( '#image-undo-' + postid ).focus();
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;
605 if ( false === this.validateNumeric( el ) ) {
619 if ( x && y && ( sel = ias.getSelection() ) ) {
620 x2 = sel.x1 + Math.round( x * sizer );
621 y2 = sel.y1 + Math.round( y * sizer );
628 elX.val( Math.round( x2 / sizer ) );
634 elY.val( Math.round( y2 / sizer ) );
637 ias.setSelection( x1, y1, x2, y2 );
639 this.setCropSelection(postid, ias.getSelection());
643 round : function(num) {
645 num = Math.round(num);
647 if ( this.hold.sizer > 0.6 ) {
651 s = num.toString().slice(-1);
655 } else if ( '9' === s ) {
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();
667 if ( false === this.validateNumeric( el ) ) {
672 this.iasapi.setOptions({
673 aspectRatio: x + ':' + y
676 if ( sel = this.iasapi.getSelection(true) ) {
677 r = Math.ceil( sel.y1 + ( ( sel.x2 - sel.x1 ) / ( x / y ) ) );
682 $('#imgedit-crop-height-' + postid).val('');
684 $('#imgedit-crop-width-' + postid).val('');
688 this.iasapi.setSelection( sel.x1, sel.y1, sel.x2, r );
689 this.iasapi.update();
694 validateNumeric: function( el ) {
695 if ( ! this.intval( $( el ).val() ) ) {