image-edit.js 28 KB

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