/**
* The functions necessary for editing images.
*
* @since 2.9.0
* @output wp-admin/js/image-edit.js
*/
/* global ajaxurl, confirm */
(function($) {
var __ = wp.i18n.__;
/**
* Contains all the methods to initialize and control the image editor.
*
* @namespace imageEdit
*/
var imageEdit = window.imageEdit = {
iasapi : {},
hold : {},
postid : '',
_view : false,
/**
* Enable crop tool.
*/
toggleCropTool: function( postid, nonce, cropButton ) {
var img = $( '#image-preview-' + postid ),
selection = this.iasapi.getSelection();
imageEdit.toggleControls( cropButton );
var $el = $( cropButton );
var state = ( $el.attr( 'aria-expanded' ) === 'true' ) ? 'true' : 'false';
// Crop tools have been closed.
if ( 'false' === state ) {
// Cancel selection, but do not unset inputs.
this.iasapi.cancelSelection();
imageEdit.setDisabled($('.imgedit-crop-clear'), 0);
} else {
imageEdit.setDisabled($('.imgedit-crop-clear'), 1);
// Get values from inputs to restore previous selection.
var startX = ( $( '#imgedit-start-x-' + postid ).val() ) ? $('#imgedit-start-x-' + postid).val() : 0;
var startY = ( $( '#imgedit-start-y-' + postid ).val() ) ? $('#imgedit-start-y-' + postid).val() : 0;
var width = ( $( '#imgedit-sel-width-' + postid ).val() ) ? $('#imgedit-sel-width-' + postid).val() : img.innerWidth();
var height = ( $( '#imgedit-sel-height-' + postid ).val() ) ? $('#imgedit-sel-height-' + postid).val() : img.innerHeight();
// Ensure selection is available, otherwise reset to full image.
if ( isNaN( selection.x1 ) ) {
this.setCropSelection( postid, { 'x1': startX, 'y1': startY, 'x2': width, 'y2': height, 'width': width, 'height': height } );
selection = this.iasapi.getSelection();
}
// If we don't already have a selection, select the entire image.
if ( 0 === selection.x1 && 0 === selection.y1 && 0 === selection.x2 && 0 === selection.y2 ) {
this.iasapi.setSelection( 0, 0, img.innerWidth(), img.innerHeight(), true );
this.iasapi.setOptions( { show: true } );
this.iasapi.update();
} else {
this.iasapi.setSelection( startX, startY, width, height, true );
this.iasapi.setOptions( { show: true } );
this.iasapi.update();
}
}
},
/**
* Handle crop tool clicks.
*/
handleCropToolClick: function( postid, nonce, cropButton ) {
if ( cropButton.classList.contains( 'imgedit-crop-clear' ) ) {
this.iasapi.cancelSelection();
imageEdit.setDisabled($('.imgedit-crop-apply'), 0);
$('#imgedit-sel-width-' + postid).val('');
$('#imgedit-sel-height-' + postid).val('');
$('#imgedit-start-x-' + postid).val('0');
$('#imgedit-start-y-' + postid).val('0');
$('#imgedit-selection-' + postid).val('');
} else {
// Otherwise, perform the crop.
imageEdit.crop( postid, nonce , cropButton );
}
},
/**
* Converts a value to an integer.
*
* @since 2.9.0
*
* @memberof imageEdit
*
* @param {number} f The float value that should be converted.
*
* @return {number} The integer representation from the float value.
*/
intval : function(f) {
/*
* Bitwise OR operator: one of the obscure ways to truncate floating point figures,
* worth reminding JavaScript doesn't have a distinct "integer" type.
*/
return f | 0;
},
/**
* Adds the disabled attribute and class to a single form element or a field set.
*
* @since 2.9.0
*
* @memberof imageEdit
*
* @param {jQuery} el The element that should be modified.
* @param {boolean|number} s The state for the element. If set to true
* the element is disabled,
* otherwise the element is enabled.
* The function is sometimes called with a 0 or 1
* instead of true or false.
*
* @return {void}
*/
setDisabled : function( el, s ) {
/*
* `el` can be a single form element or a fieldset. Before #28864, the disabled state on
* some text fields was handled targeting $('input', el). Now we need to handle the
* disabled state on buttons too so we can just target `el` regardless if it's a single
* element or a fieldset because when a fieldset is disabled, its descendants are disabled too.
*/
if ( s ) {
el.removeClass( 'disabled' ).prop( 'disabled', false );
} else {
el.addClass( 'disabled' ).prop( 'disabled', true );
}
},
/**
* Initializes the image editor.
*
* @since 2.9.0
*
* @memberof imageEdit
*
* @param {number} postid The post ID.
*
* @return {void}
*/
init : function(postid) {
var t = this, old = $('#image-editor-' + t.postid),
x = t.intval( $('#imgedit-x-' + postid).val() ),
y = t.intval( $('#imgedit-y-' + postid).val() );
if ( t.postid !== postid && old.length ) {
t.close(t.postid);
}
t.hold.w = t.hold.ow = x;
t.hold.h = t.hold.oh = y;
t.hold.xy_ratio = x / y;
t.hold.sizer = parseFloat( $('#imgedit-sizer-' + postid).val() );
t.postid = postid;
$('#imgedit-response-' + postid).empty();
$('#imgedit-panel-' + postid).on( 'keypress', function(e) {
var nonce = $( '#imgedit-nonce-' + postid ).val();
if ( e.which === 26 && e.ctrlKey ) {
imageEdit.undo( postid, nonce );
}
if ( e.which === 25 && e.ctrlKey ) {
imageEdit.redo( postid, nonce );
}
});
$('#imgedit-panel-' + postid).on( 'keypress', 'input[type="text"]', function(e) {
var k = e.keyCode;
// Key codes 37 through 40 are the arrow keys.
if ( 36 < k && k < 41 ) {
$(this).trigger( 'blur' );
}
// The key code 13 is the Enter key.
if ( 13 === k ) {
e.preventDefault();
e.stopPropagation();
return false;
}
});
$( document ).on( 'image-editor-ui-ready', this.focusManager );
},
/**
* Toggles the wait/load icon in the editor.
*
* @since 2.9.0
* @since 5.5.0 Added the triggerUIReady parameter.
*
* @memberof imageEdit
*
* @param {number} postid The post ID.
* @param {number} toggle Is 0 or 1, fades the icon in when 1 and out when 0.
* @param {boolean} triggerUIReady Whether to trigger a custom event when the UI is ready. Default false.
*
* @return {void}
*/
toggleEditor: function( postid, toggle, triggerUIReady ) {
var wait = $('#imgedit-wait-' + postid);
if ( toggle ) {
wait.fadeIn( 'fast' );
} else {
wait.fadeOut( 'fast', function() {
if ( triggerUIReady ) {
$( document ).trigger( 'image-editor-ui-ready' );
}
} );
}
},
/**
* Shows or hides image menu popup.
*
* @since 6.3.0
*
* @memberof imageEdit
*
* @param {HTMLElement} el The activated control element.
*
* @return {boolean} Always returns false.
*/
togglePopup : function(el) {
var $el = $( el );
var $targetEl = $( el ).attr( 'aria-controls' );
var $target = $( '#' + $targetEl );
$el
.attr( 'aria-expanded', 'false' === $el.attr( 'aria-expanded' ) ? 'true' : 'false' );
// Open menu and set z-index to appear above image crop area if it is enabled.
$target
.toggleClass( 'imgedit-popup-menu-open' ).slideToggle( 'fast' ).css( { 'z-index' : 200000 } );
// Move focus to first item in menu when opening menu.
if ( 'true' === $el.attr( 'aria-expanded' ) ) {
$target.find( 'button' ).first().trigger( 'focus' );
}
return false;
},
/**
* Observes whether the popup should remain open based on focus position.
*
* @since 6.4.0
*
* @memberof imageEdit
*
* @param {HTMLElement} el The activated control element.
*
* @return {boolean} Always returns false.
*/
monitorPopup : function() {
var $parent = document.querySelector( '.imgedit-rotate-menu-container' );
var $toggle = document.querySelector( '.imgedit-rotate-menu-container .imgedit-rotate' );
setTimeout( function() {
var $focused = document.activeElement;
var $contains = $parent.contains( $focused );
// If $focused is defined and not inside the menu container, close the popup.
if ( $focused && ! $contains ) {
if ( 'true' === $toggle.getAttribute( 'aria-expanded' ) ) {
imageEdit.togglePopup( $toggle );
}
}
}, 100 );
return false;
},
/**
* Navigate popup menu by arrow keys.
*
* @since 6.3.0
*
* @memberof imageEdit
*
* @param {HTMLElement} el The current element.
*
* @return {boolean} Always returns false.
*/
browsePopup : function(el) {
var $el = $( el );
var $collection = $( el ).parent( '.imgedit-popup-menu' ).find( 'button' );
var $index = $collection.index( $el );
var $prev = $index - 1;
var $next = $index + 1;
var $last = $collection.length;
if ( $prev < 0 ) {
$prev = $last - 1;
}
if ( $next === $last ) {
$next = 0;
}
var $target = false;
if ( event.keyCode === 40 ) {
$target = $collection.get( $next );
} else if ( event.keyCode === 38 ) {
$target = $collection.get( $prev );
}
if ( $target ) {
$target.focus();
event.preventDefault();
}
return false;
},
/**
* Close popup menu and reset focus on feature activation.
*
* @since 6.3.0
*
* @memberof imageEdit
*
* @param {HTMLElement} el The current element.
*
* @return {boolean} Always returns false.
*/
closePopup : function(el) {
var $parent = $(el).parent( '.imgedit-popup-menu' );
var $controlledID = $parent.attr( 'id' );
var $target = $( 'button[aria-controls="' + $controlledID + '"]' );
$target
.attr( 'aria-expanded', 'false' ).trigger( 'focus' );
$parent
.toggleClass( 'imgedit-popup-menu-open' ).slideToggle( 'fast' );
return false;
},
/**
* Shows or hides the image edit help box.
*
* @since 2.9.0
*
* @memberof imageEdit
*
* @param {HTMLElement} el The element to create the help window in.
*
* @return {boolean} Always returns false.
*/
toggleHelp : function(el) {
var $el = $( el );
$el
.attr( 'aria-expanded', 'false' === $el.attr( 'aria-expanded' ) ? 'true' : 'false' )
.parents( '.imgedit-group-top' ).toggleClass( 'imgedit-help-toggled' ).find( '.imgedit-help' ).slideToggle( 'fast' );
return false;
},
/**
* Shows or hides image edit input fields when enabled.
*
* @since 6.3.0
*
* @memberof imageEdit
*
* @param {HTMLElement} el The element to trigger the edit panel.
*
* @return {boolean} Always returns false.
*/
toggleControls : function(el) {
var $el = $( el );
var $target = $( '#' + $el.attr( 'aria-controls' ) );
$el
.attr( 'aria-expanded', 'false' === $el.attr( 'aria-expanded' ) ? 'true' : 'false' );
$target
.parent( '.imgedit-group' ).toggleClass( 'imgedit-panel-active' );
return false;
},
/**
* Gets the value from the image edit target.
*
* The image edit target contains the image sizes where the (possible) changes
* have to be applied to.
*
* @since 2.9.0
*
* @memberof imageEdit
*
* @param {number} postid The post ID.
*
* @return {string} The value from the imagedit-save-target input field when available,
* 'full' when not selected, or 'all' if it doesn't exist.
*/
getTarget : function( postid ) {
var element = $( '#imgedit-save-target-' + postid );
if ( element.length ) {
return element.find( 'input[name="imgedit-target-' + postid + '"]:checked' ).val() || 'full';
}
return 'all';
},
/**
* Recalculates the height or width and keeps the original aspect ratio.
*
* If the original image size is exceeded a red exclamation mark is shown.
*
* @since 2.9.0
*
* @memberof imageEdit
*
* @param {number} postid The current post ID.
* @param {number} x Is 0 when it applies the y-axis
* and 1 when applicable for the x-axis.
* @param {jQuery} el Element.
*
* @return {void}
*/
scaleChanged : function( postid, x, el ) {
var w = $('#imgedit-scale-width-' + postid), h = $('#imgedit-scale-height-' + postid),
warn = $('#imgedit-scale-warn-' + postid), w1 = '', h1 = '',
scaleBtn = $('#imgedit-scale-button');
if ( false === this.validateNumeric( el ) ) {
return;
}
if ( x ) {
h1 = ( w.val() !== '' ) ? Math.round( w.val() / this.hold.xy_ratio ) : '';
h.val( h1 );
} else {
w1 = ( h.val() !== '' ) ? Math.round( h.val() * this.hold.xy_ratio ) : '';
w.val( w1 );
}
if ( ( h1 && h1 > this.hold.oh ) || ( w1 && w1 > this.hold.ow ) ) {
warn.css('visibility', 'visible');
scaleBtn.prop('disabled', true);
} else {
warn.css('visibility', 'hidden');
scaleBtn.prop('disabled', false);
}
},
/**
* Gets the selected aspect ratio.
*
* @since 2.9.0
*
* @memberof imageEdit
*
* @param {number} postid The post ID.
*
* @return {string} The aspect ratio.
*/
getSelRatio : function(postid) {
var x = this.hold.w, y = this.hold.h,
X = this.intval( $('#imgedit-crop-width-' + postid).val() ),
Y = this.intval( $('#imgedit-crop-height-' + postid).val() );
if ( X && Y ) {
return X + ':' + Y;
}
if ( x && y ) {
return x + ':' + y;
}
return '1:1';
},
/**
* Removes the last action from the image edit history.
* The history consist of (edit) actions performed on the image.
*
* @since 2.9.0
*
* @memberof imageEdit
*
* @param {number} postid The post ID.
* @param {number} setSize 0 or 1, when 1 the image resets to its original size.
*
* @return {string} JSON string containing the history or an empty string if no history exists.
*/
filterHistory : function(postid, setSize) {
// Apply undo state to history.
var history = $('#imgedit-history-' + postid).val(), pop, n, o, i, op = [];
if ( history !== '' ) {
// Read the JSON string with the image edit history.
history = JSON.parse(history);
pop = this.intval( $('#imgedit-undone-' + postid).val() );
if ( pop > 0 ) {
while ( pop > 0 ) {
history.pop();
pop--;
}
}
// Reset size to its original state.
if ( setSize ) {
if ( !history.length ) {
this.hold.w = this.hold.ow;
this.hold.h = this.hold.oh;
return '';
}
// Restore original 'o'.
o = history[history.length - 1];
// c = 'crop', r = 'rotate', f = 'flip'.
o = o.c || o.r || o.f || false;
if ( o ) {
// fw = Full image width.
this.hold.w = o.fw;
// fh = Full image height.
this.hold.h = o.fh;
}
}
// Filter the last step/action from the history.
for ( n in history ) {
i = history[n];
if ( i.hasOwnProperty('c') ) {
op[n] = { 'c': { 'x': i.c.x, 'y': i.c.y, 'w': i.c.w, 'h': i.c.h } };
} else if ( i.hasOwnProperty('r') ) {
op[n] = { 'r': i.r.r };
} else if ( i.hasOwnProperty('f') ) {
op[n] = { 'f': i.f.f };
}
}
return JSON.stringify(op);
}
return '';
},
/**
* Binds the necessary events to the image.
*
* When the image source is reloaded the image will be reloaded.
*
* @since 2.9.0
*
* @memberof imageEdit
*
* @param {number} postid The post ID.
* @param {string} nonce The nonce to verify the request.
* @param {function} callback Function to execute when the image is loaded.
*
* @return {void}
*/
refreshEditor : function(postid, nonce, callback) {
var t = this, data, img;
t.toggleEditor(postid, 1);
data = {
'action': 'imgedit-preview',
'_ajax_nonce': nonce,
'postid': postid,
'history': t.filterHistory(postid, 1),
'rand': t.intval(Math.random() * 1000000)
};
img = $( '' )
.on( 'load', { history: data.history }, function( event ) {
var max1, max2,
parent = $( '#imgedit-crop-' + postid ),
t = imageEdit,
historyObj;
// Checks if there already is some image-edit history.
if ( '' !== event.data.history ) {
historyObj = JSON.parse( event.data.history );
// If last executed action in history is a crop action.
if ( historyObj[historyObj.length - 1].hasOwnProperty( 'c' ) ) {
/*
* A crop action has completed and the crop button gets disabled
* ensure the undo button is enabled.
*/
t.setDisabled( $( '#image-undo-' + postid) , true );
// Move focus to the undo button to avoid a focus loss.
$( '#image-undo-' + postid ).trigger( 'focus' );
}
}
parent.empty().append(img);
// w, h are the new full size dimensions.
max1 = Math.max( t.hold.w, t.hold.h );
max2 = Math.max( $(img).width(), $(img).height() );
t.hold.sizer = max1 > max2 ? max2 / max1 : 1;
t.initCrop(postid, img, parent);
if ( (typeof callback !== 'undefined') && callback !== null ) {
callback();
}
if ( $('#imgedit-history-' + postid).val() && $('#imgedit-undone-' + postid).val() === '0' ) {
$('button.imgedit-submit-btn', '#imgedit-panel-' + postid).prop('disabled', false);
} else {
$('button.imgedit-submit-btn', '#imgedit-panel-' + postid).prop('disabled', true);
}
var successMessage = __( 'Image updated.' );
t.toggleEditor(postid, 0);
wp.a11y.speak( successMessage, 'assertive' );
})
.on( 'error', function() {
var errorMessage = __( 'Could not load the preview image. Please reload the page and try again.' );
$( '#imgedit-crop-' + postid )
.empty()
.append( '
' + errorMessage + '
' + response.data.error + '
' + response.data.msg + '
' + errorMessage + '
' + errorMessage + '