image-edit.js 29 KB

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