image-edit.js 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237
  1. /**
  2. * The functions necessary for editing images.
  3. *
  4. * @since 2.9.0
  5. * @output wp-admin/js/image-edit.js
  6. */
  7. /* global ajaxurl, confirm */
  8. (function($) {
  9. var __ = wp.i18n.__;
  10. /**
  11. * Contains all the methods to initialise and control the image editor.
  12. *
  13. * @namespace imageEdit
  14. */
  15. var imageEdit = window.imageEdit = {
  16. iasapi : {},
  17. hold : {},
  18. postid : '',
  19. _view : false,
  20. /**
  21. * Handle crop tool clicks.
  22. */
  23. handleCropToolClick: function( postid, nonce, cropButton ) {
  24. var img = $( '#image-preview-' + postid ),
  25. selection = this.iasapi.getSelection();
  26. // Ensure selection is available, otherwise reset to full image.
  27. if ( isNaN( selection.x1 ) ) {
  28. this.setCropSelection( postid, { 'x1': 0, 'y1': 0, 'x2': img.innerWidth(), 'y2': img.innerHeight(), 'width': img.innerWidth(), 'height': img.innerHeight() } );
  29. selection = this.iasapi.getSelection();
  30. }
  31. // If we don't already have a selection, select the entire image.
  32. if ( 0 === selection.x1 && 0 === selection.y1 && 0 === selection.x2 && 0 === selection.y2 ) {
  33. this.iasapi.setSelection( 0, 0, img.innerWidth(), img.innerHeight(), true );
  34. this.iasapi.setOptions( { show: true } );
  35. this.iasapi.update();
  36. } else {
  37. // Otherwise, perform the crop.
  38. imageEdit.crop( postid, nonce , cropButton );
  39. }
  40. },
  41. /**
  42. * Converts a value to an integer.
  43. *
  44. * @since 2.9.0
  45. *
  46. * @memberof imageEdit
  47. *
  48. * @param {number} f The float value that should be converted.
  49. *
  50. * @return {number} The integer representation from the float value.
  51. */
  52. intval : function(f) {
  53. /*
  54. * Bitwise OR operator: one of the obscure ways to truncate floating point figures,
  55. * worth reminding JavaScript doesn't have a distinct "integer" type.
  56. */
  57. return f | 0;
  58. },
  59. /**
  60. * Adds the disabled attribute and class to a single form element or a field set.
  61. *
  62. * @since 2.9.0
  63. *
  64. * @memberof imageEdit
  65. *
  66. * @param {jQuery} el The element that should be modified.
  67. * @param {boolean|number} s The state for the element. If set to true
  68. * the element is disabled,
  69. * otherwise the element is enabled.
  70. * The function is sometimes called with a 0 or 1
  71. * instead of true or false.
  72. *
  73. * @return {void}
  74. */
  75. setDisabled : function( el, s ) {
  76. /*
  77. * `el` can be a single form element or a fieldset. Before #28864, the disabled state on
  78. * some text fields was handled targeting $('input', el). Now we need to handle the
  79. * disabled state on buttons too so we can just target `el` regardless if it's a single
  80. * element or a fieldset because when a fieldset is disabled, its descendants are disabled too.
  81. */
  82. if ( s ) {
  83. el.removeClass( 'disabled' ).prop( 'disabled', false );
  84. } else {
  85. el.addClass( 'disabled' ).prop( 'disabled', true );
  86. }
  87. },
  88. /**
  89. * Initializes the image editor.
  90. *
  91. * @since 2.9.0
  92. *
  93. * @memberof imageEdit
  94. *
  95. * @param {number} postid The post ID.
  96. *
  97. * @return {void}
  98. */
  99. init : function(postid) {
  100. var t = this, old = $('#image-editor-' + t.postid),
  101. x = t.intval( $('#imgedit-x-' + postid).val() ),
  102. y = t.intval( $('#imgedit-y-' + postid).val() );
  103. if ( t.postid !== postid && old.length ) {
  104. t.close(t.postid);
  105. }
  106. t.hold.w = t.hold.ow = x;
  107. t.hold.h = t.hold.oh = y;
  108. t.hold.xy_ratio = x / y;
  109. t.hold.sizer = parseFloat( $('#imgedit-sizer-' + postid).val() );
  110. t.postid = postid;
  111. $('#imgedit-response-' + postid).empty();
  112. $('#imgedit-panel-' + postid).on( 'keypress', 'input[type="text"]', function(e) {
  113. var k = e.keyCode;
  114. // Key codes 37 through 40 are the arrow keys.
  115. if ( 36 < k && k < 41 ) {
  116. $(this).trigger( 'blur' );
  117. }
  118. // The key code 13 is the Enter key.
  119. if ( 13 === k ) {
  120. e.preventDefault();
  121. e.stopPropagation();
  122. return false;
  123. }
  124. });
  125. $( document ).on( 'image-editor-ui-ready', this.focusManager );
  126. },
  127. /**
  128. * Toggles the wait/load icon in the editor.
  129. *
  130. * @since 2.9.0
  131. * @since 5.5.0 Added the triggerUIReady parameter.
  132. *
  133. * @memberof imageEdit
  134. *
  135. * @param {number} postid The post ID.
  136. * @param {number} toggle Is 0 or 1, fades the icon in when 1 and out when 0.
  137. * @param {boolean} triggerUIReady Whether to trigger a custom event when the UI is ready. Default false.
  138. *
  139. * @return {void}
  140. */
  141. toggleEditor: function( postid, toggle, triggerUIReady ) {
  142. var wait = $('#imgedit-wait-' + postid);
  143. if ( toggle ) {
  144. wait.fadeIn( 'fast' );
  145. } else {
  146. wait.fadeOut( 'fast', function() {
  147. if ( triggerUIReady ) {
  148. $( document ).trigger( 'image-editor-ui-ready' );
  149. }
  150. } );
  151. }
  152. },
  153. /**
  154. * Shows or hides the image edit help box.
  155. *
  156. * @since 2.9.0
  157. *
  158. * @memberof imageEdit
  159. *
  160. * @param {HTMLElement} el The element to create the help window in.
  161. *
  162. * @return {boolean} Always returns false.
  163. */
  164. toggleHelp : function(el) {
  165. var $el = $( el );
  166. $el
  167. .attr( 'aria-expanded', 'false' === $el.attr( 'aria-expanded' ) ? 'true' : 'false' )
  168. .parents( '.imgedit-group-top' ).toggleClass( 'imgedit-help-toggled' ).find( '.imgedit-help' ).slideToggle( 'fast' );
  169. return false;
  170. },
  171. /**
  172. * Gets the value from the image edit target.
  173. *
  174. * The image edit target contains the image sizes where the (possible) changes
  175. * have to be applied to.
  176. *
  177. * @since 2.9.0
  178. *
  179. * @memberof imageEdit
  180. *
  181. * @param {number} postid The post ID.
  182. *
  183. * @return {string} The value from the imagedit-save-target input field when available,
  184. * or 'full' when not available.
  185. */
  186. getTarget : function(postid) {
  187. return $('input[name="imgedit-target-' + postid + '"]:checked', '#imgedit-save-target-' + postid).val() || 'full';
  188. },
  189. /**
  190. * Recalculates the height or width and keeps the original aspect ratio.
  191. *
  192. * If the original image size is exceeded a red exclamation mark is shown.
  193. *
  194. * @since 2.9.0
  195. *
  196. * @memberof imageEdit
  197. *
  198. * @param {number} postid The current post ID.
  199. * @param {number} x Is 0 when it applies the y-axis
  200. * and 1 when applicable for the x-axis.
  201. * @param {jQuery} el Element.
  202. *
  203. * @return {void}
  204. */
  205. scaleChanged : function( postid, x, el ) {
  206. var w = $('#imgedit-scale-width-' + postid), h = $('#imgedit-scale-height-' + postid),
  207. warn = $('#imgedit-scale-warn-' + postid), w1 = '', h1 = '';
  208. if ( false === this.validateNumeric( el ) ) {
  209. return;
  210. }
  211. if ( x ) {
  212. h1 = ( w.val() !== '' ) ? Math.round( w.val() / this.hold.xy_ratio ) : '';
  213. h.val( h1 );
  214. } else {
  215. w1 = ( h.val() !== '' ) ? Math.round( h.val() * this.hold.xy_ratio ) : '';
  216. w.val( w1 );
  217. }
  218. if ( ( h1 && h1 > this.hold.oh ) || ( w1 && w1 > this.hold.ow ) ) {
  219. warn.css('visibility', 'visible');
  220. } else {
  221. warn.css('visibility', 'hidden');
  222. }
  223. },
  224. /**
  225. * Gets the selected aspect ratio.
  226. *
  227. * @since 2.9.0
  228. *
  229. * @memberof imageEdit
  230. *
  231. * @param {number} postid The post ID.
  232. *
  233. * @return {string} The aspect ratio.
  234. */
  235. getSelRatio : function(postid) {
  236. var x = this.hold.w, y = this.hold.h,
  237. X = this.intval( $('#imgedit-crop-width-' + postid).val() ),
  238. Y = this.intval( $('#imgedit-crop-height-' + postid).val() );
  239. if ( X && Y ) {
  240. return X + ':' + Y;
  241. }
  242. if ( x && y ) {
  243. return x + ':' + y;
  244. }
  245. return '1:1';
  246. },
  247. /**
  248. * Removes the last action from the image edit history.
  249. * The history consist of (edit) actions performed on the image.
  250. *
  251. * @since 2.9.0
  252. *
  253. * @memberof imageEdit
  254. *
  255. * @param {number} postid The post ID.
  256. * @param {number} setSize 0 or 1, when 1 the image resets to its original size.
  257. *
  258. * @return {string} JSON string containing the history or an empty string if no history exists.
  259. */
  260. filterHistory : function(postid, setSize) {
  261. // Apply undo state to history.
  262. var history = $('#imgedit-history-' + postid).val(), pop, n, o, i, op = [];
  263. if ( history !== '' ) {
  264. // Read the JSON string with the image edit history.
  265. history = JSON.parse(history);
  266. pop = this.intval( $('#imgedit-undone-' + postid).val() );
  267. if ( pop > 0 ) {
  268. while ( pop > 0 ) {
  269. history.pop();
  270. pop--;
  271. }
  272. }
  273. // Reset size to its original state.
  274. if ( setSize ) {
  275. if ( !history.length ) {
  276. this.hold.w = this.hold.ow;
  277. this.hold.h = this.hold.oh;
  278. return '';
  279. }
  280. // Restore original 'o'.
  281. o = history[history.length - 1];
  282. // c = 'crop', r = 'rotate', f = 'flip'.
  283. o = o.c || o.r || o.f || false;
  284. if ( o ) {
  285. // fw = Full image width.
  286. this.hold.w = o.fw;
  287. // fh = Full image height.
  288. this.hold.h = o.fh;
  289. }
  290. }
  291. // Filter the last step/action from the history.
  292. for ( n in history ) {
  293. i = history[n];
  294. if ( i.hasOwnProperty('c') ) {
  295. op[n] = { 'c': { 'x': i.c.x, 'y': i.c.y, 'w': i.c.w, 'h': i.c.h } };
  296. } else if ( i.hasOwnProperty('r') ) {
  297. op[n] = { 'r': i.r.r };
  298. } else if ( i.hasOwnProperty('f') ) {
  299. op[n] = { 'f': i.f.f };
  300. }
  301. }
  302. return JSON.stringify(op);
  303. }
  304. return '';
  305. },
  306. /**
  307. * Binds the necessary events to the image.
  308. *
  309. * When the image source is reloaded the image will be reloaded.
  310. *
  311. * @since 2.9.0
  312. *
  313. * @memberof imageEdit
  314. *
  315. * @param {number} postid The post ID.
  316. * @param {string} nonce The nonce to verify the request.
  317. * @param {function} callback Function to execute when the image is loaded.
  318. *
  319. * @return {void}
  320. */
  321. refreshEditor : function(postid, nonce, callback) {
  322. var t = this, data, img;
  323. t.toggleEditor(postid, 1);
  324. data = {
  325. 'action': 'imgedit-preview',
  326. '_ajax_nonce': nonce,
  327. 'postid': postid,
  328. 'history': t.filterHistory(postid, 1),
  329. 'rand': t.intval(Math.random() * 1000000)
  330. };
  331. img = $( '<img id="image-preview-' + postid + '" alt="" />' )
  332. .on( 'load', { history: data.history }, function( event ) {
  333. var max1, max2,
  334. parent = $( '#imgedit-crop-' + postid ),
  335. t = imageEdit,
  336. historyObj;
  337. // Checks if there already is some image-edit history.
  338. if ( '' !== event.data.history ) {
  339. historyObj = JSON.parse( event.data.history );
  340. // If last executed action in history is a crop action.
  341. if ( historyObj[historyObj.length - 1].hasOwnProperty( 'c' ) ) {
  342. /*
  343. * A crop action has completed and the crop button gets disabled
  344. * ensure the undo button is enabled.
  345. */
  346. t.setDisabled( $( '#image-undo-' + postid) , true );
  347. // Move focus to the undo button to avoid a focus loss.
  348. $( '#image-undo-' + postid ).trigger( 'focus' );
  349. }
  350. }
  351. parent.empty().append(img);
  352. // w, h are the new full size dimensions.
  353. max1 = Math.max( t.hold.w, t.hold.h );
  354. max2 = Math.max( $(img).width(), $(img).height() );
  355. t.hold.sizer = max1 > max2 ? max2 / max1 : 1;
  356. t.initCrop(postid, img, parent);
  357. if ( (typeof callback !== 'undefined') && callback !== null ) {
  358. callback();
  359. }
  360. if ( $('#imgedit-history-' + postid).val() && $('#imgedit-undone-' + postid).val() === '0' ) {
  361. $('input.imgedit-submit-btn', '#imgedit-panel-' + postid).prop('disabled', false);
  362. } else {
  363. $('input.imgedit-submit-btn', '#imgedit-panel-' + postid).prop('disabled', true);
  364. }
  365. t.toggleEditor(postid, 0);
  366. })
  367. .on( 'error', function() {
  368. var errorMessage = __( 'Could not load the preview image. Please reload the page and try again.' );
  369. $( '#imgedit-crop-' + postid )
  370. .empty()
  371. .append( '<div class="notice notice-error" tabindex="-1" role="alert"><p>' + errorMessage + '</p></div>' );
  372. t.toggleEditor( postid, 0, true );
  373. wp.a11y.speak( errorMessage, 'assertive' );
  374. } )
  375. .attr('src', ajaxurl + '?' + $.param(data));
  376. },
  377. /**
  378. * Performs an image edit action.
  379. *
  380. * @since 2.9.0
  381. *
  382. * @memberof imageEdit
  383. *
  384. * @param {number} postid The post ID.
  385. * @param {string} nonce The nonce to verify the request.
  386. * @param {string} action The action to perform on the image.
  387. * The possible actions are: "scale" and "restore".
  388. *
  389. * @return {boolean|void} Executes a post request that refreshes the page
  390. * when the action is performed.
  391. * Returns false if a invalid action is given,
  392. * or when the action cannot be performed.
  393. */
  394. action : function(postid, nonce, action) {
  395. var t = this, data, w, h, fw, fh;
  396. if ( t.notsaved(postid) ) {
  397. return false;
  398. }
  399. data = {
  400. 'action': 'image-editor',
  401. '_ajax_nonce': nonce,
  402. 'postid': postid
  403. };
  404. if ( 'scale' === action ) {
  405. w = $('#imgedit-scale-width-' + postid),
  406. h = $('#imgedit-scale-height-' + postid),
  407. fw = t.intval(w.val()),
  408. fh = t.intval(h.val());
  409. if ( fw < 1 ) {
  410. w.trigger( 'focus' );
  411. return false;
  412. } else if ( fh < 1 ) {
  413. h.trigger( 'focus' );
  414. return false;
  415. }
  416. if ( fw === t.hold.ow || fh === t.hold.oh ) {
  417. return false;
  418. }
  419. data['do'] = 'scale';
  420. data.fwidth = fw;
  421. data.fheight = fh;
  422. } else if ( 'restore' === action ) {
  423. data['do'] = 'restore';
  424. } else {
  425. return false;
  426. }
  427. t.toggleEditor(postid, 1);
  428. $.post( ajaxurl, data, function( response ) {
  429. $( '#image-editor-' + postid ).empty().append( response.data.html );
  430. t.toggleEditor( postid, 0, true );
  431. // Refresh the attachment model so that changes propagate.
  432. if ( t._view ) {
  433. t._view.refresh();
  434. }
  435. } ).done( function( response ) {
  436. // Whether the executed action was `scale` or `restore`, the response does have a message.
  437. if ( response && response.data.message.msg ) {
  438. wp.a11y.speak( response.data.message.msg );
  439. return;
  440. }
  441. if ( response && response.data.message.error ) {
  442. wp.a11y.speak( response.data.message.error );
  443. }
  444. } );
  445. },
  446. /**
  447. * Stores the changes that are made to the image.
  448. *
  449. * @since 2.9.0
  450. *
  451. * @memberof imageEdit
  452. *
  453. * @param {number} postid The post ID to get the image from the database.
  454. * @param {string} nonce The nonce to verify the request.
  455. *
  456. * @return {boolean|void} If the actions are successfully saved a response message is shown.
  457. * Returns false if there is no image editing history,
  458. * thus there are not edit-actions performed on the image.
  459. */
  460. save : function(postid, nonce) {
  461. var data,
  462. target = this.getTarget(postid),
  463. history = this.filterHistory(postid, 0),
  464. self = this;
  465. if ( '' === history ) {
  466. return false;
  467. }
  468. this.toggleEditor(postid, 1);
  469. data = {
  470. 'action': 'image-editor',
  471. '_ajax_nonce': nonce,
  472. 'postid': postid,
  473. 'history': history,
  474. 'target': target,
  475. 'context': $('#image-edit-context').length ? $('#image-edit-context').val() : null,
  476. 'do': 'save'
  477. };
  478. // Post the image edit data to the backend.
  479. $.post( ajaxurl, data, function( response ) {
  480. // If a response is returned, close the editor and show an error.
  481. if ( response.data.error ) {
  482. $( '#imgedit-response-' + postid )
  483. .html( '<div class="notice notice-error" tabindex="-1" role="alert"><p>' + response.data.error + '</p></div>' );
  484. imageEdit.close(postid);
  485. wp.a11y.speak( response.data.error );
  486. return;
  487. }
  488. if ( response.data.fw && response.data.fh ) {
  489. $( '#media-dims-' + postid ).html( response.data.fw + ' &times; ' + response.data.fh );
  490. }
  491. if ( response.data.thumbnail ) {
  492. $( '.thumbnail', '#thumbnail-head-' + postid ).attr( 'src', '' + response.data.thumbnail );
  493. }
  494. if ( response.data.msg ) {
  495. $( '#imgedit-response-' + postid )
  496. .html( '<div class="notice notice-success" tabindex="-1" role="alert"><p>' + response.data.msg + '</p></div>' );
  497. wp.a11y.speak( response.data.msg );
  498. }
  499. if ( self._view ) {
  500. self._view.save();
  501. } else {
  502. imageEdit.close(postid);
  503. }
  504. });
  505. },
  506. /**
  507. * Creates the image edit window.
  508. *
  509. * @since 2.9.0
  510. *
  511. * @memberof imageEdit
  512. *
  513. * @param {number} postid The post ID for the image.
  514. * @param {string} nonce The nonce to verify the request.
  515. * @param {Object} view The image editor view to be used for the editing.
  516. *
  517. * @return {void|promise} Either returns void if the button was already activated
  518. * or returns an instance of the image editor, wrapped in a promise.
  519. */
  520. open : function( postid, nonce, view ) {
  521. this._view = view;
  522. var dfd, data,
  523. elem = $( '#image-editor-' + postid ),
  524. head = $( '#media-head-' + postid ),
  525. btn = $( '#imgedit-open-btn-' + postid ),
  526. spin = btn.siblings( '.spinner' );
  527. /*
  528. * Instead of disabling the button, which causes a focus loss and makes screen
  529. * readers announce "unavailable", return if the button was already clicked.
  530. */
  531. if ( btn.hasClass( 'button-activated' ) ) {
  532. return;
  533. }
  534. spin.addClass( 'is-active' );
  535. data = {
  536. 'action': 'image-editor',
  537. '_ajax_nonce': nonce,
  538. 'postid': postid,
  539. 'do': 'open'
  540. };
  541. dfd = $.ajax( {
  542. url: ajaxurl,
  543. type: 'post',
  544. data: data,
  545. beforeSend: function() {
  546. btn.addClass( 'button-activated' );
  547. }
  548. } ).done( function( response ) {
  549. var errorMessage;
  550. if ( '-1' === response ) {
  551. errorMessage = __( 'Could not load the preview image.' );
  552. elem.html( '<div class="notice notice-error" tabindex="-1" role="alert"><p>' + errorMessage + '</p></div>' );
  553. }
  554. if ( response.data && response.data.html ) {
  555. elem.html( response.data.html );
  556. }
  557. head.fadeOut( 'fast', function() {
  558. elem.fadeIn( 'fast', function() {
  559. if ( errorMessage ) {
  560. $( document ).trigger( 'image-editor-ui-ready' );
  561. }
  562. } );
  563. btn.removeClass( 'button-activated' );
  564. spin.removeClass( 'is-active' );
  565. } );
  566. // Initialise the Image Editor now that everything is ready.
  567. imageEdit.init( postid );
  568. } );
  569. return dfd;
  570. },
  571. /**
  572. * Initializes the cropping tool and sets a default cropping selection.
  573. *
  574. * @since 2.9.0
  575. *
  576. * @memberof imageEdit
  577. *
  578. * @param {number} postid The post ID.
  579. *
  580. * @return {void}
  581. */
  582. imgLoaded : function(postid) {
  583. var img = $('#image-preview-' + postid), parent = $('#imgedit-crop-' + postid);
  584. // Ensure init has run even when directly loaded.
  585. if ( 'undefined' === typeof this.hold.sizer ) {
  586. this.init( postid );
  587. }
  588. this.initCrop(postid, img, parent);
  589. this.setCropSelection( postid, { 'x1': 0, 'y1': 0, 'x2': 0, 'y2': 0, 'width': img.innerWidth(), 'height': img.innerHeight() } );
  590. this.toggleEditor( postid, 0, true );
  591. },
  592. /**
  593. * Manages keyboard focus in the Image Editor user interface.
  594. *
  595. * @since 5.5.0
  596. *
  597. * @return {void}
  598. */
  599. focusManager: function() {
  600. /*
  601. * Editor is ready. Move focus to one of the admin alert notices displayed
  602. * after a user action or to the first focusable element. Since the DOM
  603. * update is pretty large, the timeout helps browsers update their
  604. * accessibility tree to better support assistive technologies.
  605. */
  606. setTimeout( function() {
  607. var elementToSetFocusTo = $( '.notice[role="alert"]' );
  608. if ( ! elementToSetFocusTo.length ) {
  609. elementToSetFocusTo = $( '.imgedit-wrap' ).find( ':tabbable:first' );
  610. }
  611. elementToSetFocusTo.trigger( 'focus' );
  612. }, 100 );
  613. },
  614. /**
  615. * Initializes the cropping tool.
  616. *
  617. * @since 2.9.0
  618. *
  619. * @memberof imageEdit
  620. *
  621. * @param {number} postid The post ID.
  622. * @param {HTMLElement} image The preview image.
  623. * @param {HTMLElement} parent The preview image container.
  624. *
  625. * @return {void}
  626. */
  627. initCrop : function(postid, image, parent) {
  628. var t = this,
  629. selW = $('#imgedit-sel-width-' + postid),
  630. selH = $('#imgedit-sel-height-' + postid),
  631. $image = $( image ),
  632. $img;
  633. // Already initialized?
  634. if ( $image.data( 'imgAreaSelect' ) ) {
  635. return;
  636. }
  637. t.iasapi = $image.imgAreaSelect({
  638. parent: parent,
  639. instance: true,
  640. handles: true,
  641. keys: true,
  642. minWidth: 3,
  643. minHeight: 3,
  644. /**
  645. * Sets the CSS styles and binds events for locking the aspect ratio.
  646. *
  647. * @ignore
  648. *
  649. * @param {jQuery} img The preview image.
  650. */
  651. onInit: function( img ) {
  652. // Ensure that the imgAreaSelect wrapper elements are position:absolute
  653. // (even if we're in a position:fixed modal).
  654. $img = $( img );
  655. $img.next().css( 'position', 'absolute' )
  656. .nextAll( '.imgareaselect-outer' ).css( 'position', 'absolute' );
  657. /**
  658. * Binds mouse down event to the cropping container.
  659. *
  660. * @return {void}
  661. */
  662. parent.children().on( 'mousedown, touchstart', function(e){
  663. var ratio = false, sel, defRatio;
  664. if ( e.shiftKey ) {
  665. sel = t.iasapi.getSelection();
  666. defRatio = t.getSelRatio(postid);
  667. ratio = ( sel && sel.width && sel.height ) ? sel.width + ':' + sel.height : defRatio;
  668. }
  669. t.iasapi.setOptions({
  670. aspectRatio: ratio
  671. });
  672. });
  673. },
  674. /**
  675. * Event triggered when starting a selection.
  676. *
  677. * @ignore
  678. *
  679. * @return {void}
  680. */
  681. onSelectStart: function() {
  682. imageEdit.setDisabled($('#imgedit-crop-sel-' + postid), 1);
  683. },
  684. /**
  685. * Event triggered when the selection is ended.
  686. *
  687. * @ignore
  688. *
  689. * @param {Object} img jQuery object representing the image.
  690. * @param {Object} c The selection.
  691. *
  692. * @return {Object}
  693. */
  694. onSelectEnd: function(img, c) {
  695. imageEdit.setCropSelection(postid, c);
  696. },
  697. /**
  698. * Event triggered when the selection changes.
  699. *
  700. * @ignore
  701. *
  702. * @param {Object} img jQuery object representing the image.
  703. * @param {Object} c The selection.
  704. *
  705. * @return {void}
  706. */
  707. onSelectChange: function(img, c) {
  708. var sizer = imageEdit.hold.sizer;
  709. selW.val( imageEdit.round(c.width / sizer) );
  710. selH.val( imageEdit.round(c.height / sizer) );
  711. }
  712. });
  713. },
  714. /**
  715. * Stores the current crop selection.
  716. *
  717. * @since 2.9.0
  718. *
  719. * @memberof imageEdit
  720. *
  721. * @param {number} postid The post ID.
  722. * @param {Object} c The selection.
  723. *
  724. * @return {boolean}
  725. */
  726. setCropSelection : function(postid, c) {
  727. var sel;
  728. c = c || 0;
  729. if ( !c || ( c.width < 3 && c.height < 3 ) ) {
  730. this.setDisabled( $( '.imgedit-crop', '#imgedit-panel-' + postid ), 1 );
  731. this.setDisabled( $( '#imgedit-crop-sel-' + postid ), 1 );
  732. $('#imgedit-sel-width-' + postid).val('');
  733. $('#imgedit-sel-height-' + postid).val('');
  734. $('#imgedit-selection-' + postid).val('');
  735. return false;
  736. }
  737. sel = { 'x': c.x1, 'y': c.y1, 'w': c.width, 'h': c.height };
  738. this.setDisabled($('.imgedit-crop', '#imgedit-panel-' + postid), 1);
  739. $('#imgedit-selection-' + postid).val( JSON.stringify(sel) );
  740. },
  741. /**
  742. * Closes the image editor.
  743. *
  744. * @since 2.9.0
  745. *
  746. * @memberof imageEdit
  747. *
  748. * @param {number} postid The post ID.
  749. * @param {boolean} warn Warning message.
  750. *
  751. * @return {void|boolean} Returns false if there is a warning.
  752. */
  753. close : function(postid, warn) {
  754. warn = warn || false;
  755. if ( warn && this.notsaved(postid) ) {
  756. return false;
  757. }
  758. this.iasapi = {};
  759. this.hold = {};
  760. // If we've loaded the editor in the context of a Media Modal,
  761. // then switch to the previous view, whatever that might have been.
  762. if ( this._view ){
  763. this._view.back();
  764. }
  765. // In case we are not accessing the image editor in the context of a View,
  766. // close the editor the old-school way.
  767. else {
  768. $('#image-editor-' + postid).fadeOut('fast', function() {
  769. $( '#media-head-' + postid ).fadeIn( 'fast', function() {
  770. // Move focus back to the Edit Image button. Runs also when saving.
  771. $( '#imgedit-open-btn-' + postid ).trigger( 'focus' );
  772. });
  773. $(this).empty();
  774. });
  775. }
  776. },
  777. /**
  778. * Checks if the image edit history is saved.
  779. *
  780. * @since 2.9.0
  781. *
  782. * @memberof imageEdit
  783. *
  784. * @param {number} postid The post ID.
  785. *
  786. * @return {boolean} Returns true if the history is not saved.
  787. */
  788. notsaved : function(postid) {
  789. var h = $('#imgedit-history-' + postid).val(),
  790. history = ( h !== '' ) ? JSON.parse(h) : [],
  791. pop = this.intval( $('#imgedit-undone-' + postid).val() );
  792. if ( pop < history.length ) {
  793. if ( confirm( $('#imgedit-leaving-' + postid).text() ) ) {
  794. return false;
  795. }
  796. return true;
  797. }
  798. return false;
  799. },
  800. /**
  801. * Adds an image edit action to the history.
  802. *
  803. * @since 2.9.0
  804. *
  805. * @memberof imageEdit
  806. *
  807. * @param {Object} op The original position.
  808. * @param {number} postid The post ID.
  809. * @param {string} nonce The nonce.
  810. *
  811. * @return {void}
  812. */
  813. addStep : function(op, postid, nonce) {
  814. var t = this, elem = $('#imgedit-history-' + postid),
  815. history = ( elem.val() !== '' ) ? JSON.parse( elem.val() ) : [],
  816. undone = $( '#imgedit-undone-' + postid ),
  817. pop = t.intval( undone.val() );
  818. while ( pop > 0 ) {
  819. history.pop();
  820. pop--;
  821. }
  822. undone.val(0); // Reset.
  823. history.push(op);
  824. elem.val( JSON.stringify(history) );
  825. t.refreshEditor(postid, nonce, function() {
  826. t.setDisabled($('#image-undo-' + postid), true);
  827. t.setDisabled($('#image-redo-' + postid), false);
  828. });
  829. },
  830. /**
  831. * Rotates the image.
  832. *
  833. * @since 2.9.0
  834. *
  835. * @memberof imageEdit
  836. *
  837. * @param {string} angle The angle the image is rotated with.
  838. * @param {number} postid The post ID.
  839. * @param {string} nonce The nonce.
  840. * @param {Object} t The target element.
  841. *
  842. * @return {boolean}
  843. */
  844. rotate : function(angle, postid, nonce, t) {
  845. if ( $(t).hasClass('disabled') ) {
  846. return false;
  847. }
  848. this.addStep({ 'r': { 'r': angle, 'fw': this.hold.h, 'fh': this.hold.w }}, postid, nonce);
  849. },
  850. /**
  851. * Flips the image.
  852. *
  853. * @since 2.9.0
  854. *
  855. * @memberof imageEdit
  856. *
  857. * @param {number} axis The axle the image is flipped on.
  858. * @param {number} postid The post ID.
  859. * @param {string} nonce The nonce.
  860. * @param {Object} t The target element.
  861. *
  862. * @return {boolean}
  863. */
  864. flip : function (axis, postid, nonce, t) {
  865. if ( $(t).hasClass('disabled') ) {
  866. return false;
  867. }
  868. this.addStep({ 'f': { 'f': axis, 'fw': this.hold.w, 'fh': this.hold.h }}, postid, nonce);
  869. },
  870. /**
  871. * Crops the image.
  872. *
  873. * @since 2.9.0
  874. *
  875. * @memberof imageEdit
  876. *
  877. * @param {number} postid The post ID.
  878. * @param {string} nonce The nonce.
  879. * @param {Object} t The target object.
  880. *
  881. * @return {void|boolean} Returns false if the crop button is disabled.
  882. */
  883. crop : function (postid, nonce, t) {
  884. var sel = $('#imgedit-selection-' + postid).val(),
  885. w = this.intval( $('#imgedit-sel-width-' + postid).val() ),
  886. h = this.intval( $('#imgedit-sel-height-' + postid).val() );
  887. if ( $(t).hasClass('disabled') || sel === '' ) {
  888. return false;
  889. }
  890. sel = JSON.parse(sel);
  891. if ( sel.w > 0 && sel.h > 0 && w > 0 && h > 0 ) {
  892. sel.fw = w;
  893. sel.fh = h;
  894. this.addStep({ 'c': sel }, postid, nonce);
  895. }
  896. // Clear the selection fields after cropping.
  897. $('#imgedit-sel-width-' + postid).val('');
  898. $('#imgedit-sel-height-' + postid).val('');
  899. },
  900. /**
  901. * Undoes an image edit action.
  902. *
  903. * @since 2.9.0
  904. *
  905. * @memberof imageEdit
  906. *
  907. * @param {number} postid The post ID.
  908. * @param {string} nonce The nonce.
  909. *
  910. * @return {void|false} Returns false if the undo button is disabled.
  911. */
  912. undo : function (postid, nonce) {
  913. var t = this, button = $('#image-undo-' + postid), elem = $('#imgedit-undone-' + postid),
  914. pop = t.intval( elem.val() ) + 1;
  915. if ( button.hasClass('disabled') ) {
  916. return;
  917. }
  918. elem.val(pop);
  919. t.refreshEditor(postid, nonce, function() {
  920. var elem = $('#imgedit-history-' + postid),
  921. history = ( elem.val() !== '' ) ? JSON.parse( elem.val() ) : [];
  922. t.setDisabled($('#image-redo-' + postid), true);
  923. t.setDisabled(button, pop < history.length);
  924. // When undo gets disabled, move focus to the redo button to avoid a focus loss.
  925. if ( history.length === pop ) {
  926. $( '#image-redo-' + postid ).trigger( 'focus' );
  927. }
  928. });
  929. },
  930. /**
  931. * Reverts a undo action.
  932. *
  933. * @since 2.9.0
  934. *
  935. * @memberof imageEdit
  936. *
  937. * @param {number} postid The post ID.
  938. * @param {string} nonce The nonce.
  939. *
  940. * @return {void}
  941. */
  942. redo : function(postid, nonce) {
  943. var t = this, button = $('#image-redo-' + postid), elem = $('#imgedit-undone-' + postid),
  944. pop = t.intval( elem.val() ) - 1;
  945. if ( button.hasClass('disabled') ) {
  946. return;
  947. }
  948. elem.val(pop);
  949. t.refreshEditor(postid, nonce, function() {
  950. t.setDisabled($('#image-undo-' + postid), true);
  951. t.setDisabled(button, pop > 0);
  952. // When redo gets disabled, move focus to the undo button to avoid a focus loss.
  953. if ( 0 === pop ) {
  954. $( '#image-undo-' + postid ).trigger( 'focus' );
  955. }
  956. });
  957. },
  958. /**
  959. * Sets the selection for the height and width in pixels.
  960. *
  961. * @since 2.9.0
  962. *
  963. * @memberof imageEdit
  964. *
  965. * @param {number} postid The post ID.
  966. * @param {jQuery} el The element containing the values.
  967. *
  968. * @return {void|boolean} Returns false when the x or y value is lower than 1,
  969. * void when the value is not numeric or when the operation
  970. * is successful.
  971. */
  972. setNumSelection : function( postid, el ) {
  973. var sel, elX = $('#imgedit-sel-width-' + postid), elY = $('#imgedit-sel-height-' + postid),
  974. x = this.intval( elX.val() ), y = this.intval( elY.val() ),
  975. img = $('#image-preview-' + postid), imgh = img.height(), imgw = img.width(),
  976. sizer = this.hold.sizer, x1, y1, x2, y2, ias = this.iasapi;
  977. if ( false === this.validateNumeric( el ) ) {
  978. return;
  979. }
  980. if ( x < 1 ) {
  981. elX.val('');
  982. return false;
  983. }
  984. if ( y < 1 ) {
  985. elY.val('');
  986. return false;
  987. }
  988. if ( x && y && ( sel = ias.getSelection() ) ) {
  989. x2 = sel.x1 + Math.round( x * sizer );
  990. y2 = sel.y1 + Math.round( y * sizer );
  991. x1 = sel.x1;
  992. y1 = sel.y1;
  993. if ( x2 > imgw ) {
  994. x1 = 0;
  995. x2 = imgw;
  996. elX.val( Math.round( x2 / sizer ) );
  997. }
  998. if ( y2 > imgh ) {
  999. y1 = 0;
  1000. y2 = imgh;
  1001. elY.val( Math.round( y2 / sizer ) );
  1002. }
  1003. ias.setSelection( x1, y1, x2, y2 );
  1004. ias.update();
  1005. this.setCropSelection(postid, ias.getSelection());
  1006. }
  1007. },
  1008. /**
  1009. * Rounds a number to a whole.
  1010. *
  1011. * @since 2.9.0
  1012. *
  1013. * @memberof imageEdit
  1014. *
  1015. * @param {number} num The number.
  1016. *
  1017. * @return {number} The number rounded to a whole number.
  1018. */
  1019. round : function(num) {
  1020. var s;
  1021. num = Math.round(num);
  1022. if ( this.hold.sizer > 0.6 ) {
  1023. return num;
  1024. }
  1025. s = num.toString().slice(-1);
  1026. if ( '1' === s ) {
  1027. return num - 1;
  1028. } else if ( '9' === s ) {
  1029. return num + 1;
  1030. }
  1031. return num;
  1032. },
  1033. /**
  1034. * Sets a locked aspect ratio for the selection.
  1035. *
  1036. * @since 2.9.0
  1037. *
  1038. * @memberof imageEdit
  1039. *
  1040. * @param {number} postid The post ID.
  1041. * @param {number} n The ratio to set.
  1042. * @param {jQuery} el The element containing the values.
  1043. *
  1044. * @return {void}
  1045. */
  1046. setRatioSelection : function(postid, n, el) {
  1047. var sel, r, x = this.intval( $('#imgedit-crop-width-' + postid).val() ),
  1048. y = this.intval( $('#imgedit-crop-height-' + postid).val() ),
  1049. h = $('#image-preview-' + postid).height();
  1050. if ( false === this.validateNumeric( el ) ) {
  1051. this.iasapi.setOptions({
  1052. aspectRatio: null
  1053. });
  1054. return;
  1055. }
  1056. if ( x && y ) {
  1057. this.iasapi.setOptions({
  1058. aspectRatio: x + ':' + y
  1059. });
  1060. if ( sel = this.iasapi.getSelection(true) ) {
  1061. r = Math.ceil( sel.y1 + ( ( sel.x2 - sel.x1 ) / ( x / y ) ) );
  1062. if ( r > h ) {
  1063. r = h;
  1064. if ( n ) {
  1065. $('#imgedit-crop-height-' + postid).val('');
  1066. } else {
  1067. $('#imgedit-crop-width-' + postid).val('');
  1068. }
  1069. }
  1070. this.iasapi.setSelection( sel.x1, sel.y1, sel.x2, r );
  1071. this.iasapi.update();
  1072. }
  1073. }
  1074. },
  1075. /**
  1076. * Validates if a value in a jQuery.HTMLElement is numeric.
  1077. *
  1078. * @since 4.6.0
  1079. *
  1080. * @memberof imageEdit
  1081. *
  1082. * @param {jQuery} el The html element.
  1083. *
  1084. * @return {void|boolean} Returns false if the value is not numeric,
  1085. * void when it is.
  1086. */
  1087. validateNumeric: function( el ) {
  1088. if ( ! this.intval( $( el ).val() ) ) {
  1089. $( el ).val( '' );
  1090. return false;
  1091. }
  1092. }
  1093. };
  1094. })(jQuery);