[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

title

Body

[close]

/wp-admin/js/ -> image-edit.js (source)

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


Generated: Fri Oct 25 08:20:01 2019 Cross-referenced by PHPXref 0.7