[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

/wp-admin/js/ -> revisions.js (source)

   1  /**
   2   * @file Revisions interface functions, Backbone classes and
   3   * the revisions.php document.ready bootstrap.
   4   *
   5   * @output wp-admin/js/revisions.js
   6   */
   7  
   8  /* global isRtl */
   9  
  10  window.wp = window.wp || {};
  11  
  12  (function($) {
  13      var revisions;
  14      /**
  15       * Expose the module in window.wp.revisions.
  16       */
  17      revisions = wp.revisions = { model: {}, view: {}, controller: {} };
  18  
  19      // Link post revisions data served from the back end.
  20      revisions.settings = window._wpRevisionsSettings || {};
  21  
  22      // For debugging
  23      revisions.debug = false;
  24  
  25      /**
  26       * wp.revisions.log
  27       *
  28       * A debugging utility for revisions. Works only when a
  29       * debug flag is on and the browser supports it.
  30       */
  31      revisions.log = function() {
  32          if ( window.console && revisions.debug ) {
  33              window.console.log.apply( window.console, arguments );
  34          }
  35      };
  36  
  37      // Handy functions to help with positioning
  38      $.fn.allOffsets = function() {
  39          var offset = this.offset() || {top: 0, left: 0}, win = $(window);
  40          return _.extend( offset, {
  41              right:  win.width()  - offset.left - this.outerWidth(),
  42              bottom: win.height() - offset.top  - this.outerHeight()
  43          });
  44      };
  45  
  46      $.fn.allPositions = function() {
  47          var position = this.position() || {top: 0, left: 0}, parent = this.parent();
  48          return _.extend( position, {
  49              right:  parent.outerWidth()  - position.left - this.outerWidth(),
  50              bottom: parent.outerHeight() - position.top  - this.outerHeight()
  51          });
  52      };
  53  
  54      /**
  55       * ========================================================================
  56       * MODELS
  57       * ========================================================================
  58       */
  59      revisions.model.Slider = Backbone.Model.extend({
  60          defaults: {
  61              value: null,
  62              values: null,
  63              min: 0,
  64              max: 1,
  65              step: 1,
  66              range: false,
  67              compareTwoMode: false
  68          },
  69  
  70          initialize: function( options ) {
  71              this.frame = options.frame;
  72              this.revisions = options.revisions;
  73  
  74              // Listen for changes to the revisions or mode from outside
  75              this.listenTo( this.frame, 'update:revisions', this.receiveRevisions );
  76              this.listenTo( this.frame, 'change:compareTwoMode', this.updateMode );
  77  
  78              // Listen for internal changes
  79              this.on( 'change:from', this.handleLocalChanges );
  80              this.on( 'change:to', this.handleLocalChanges );
  81              this.on( 'change:compareTwoMode', this.updateSliderSettings );
  82              this.on( 'update:revisions', this.updateSliderSettings );
  83  
  84              // Listen for changes to the hovered revision
  85              this.on( 'change:hoveredRevision', this.hoverRevision );
  86  
  87              this.set({
  88                  max:   this.revisions.length - 1,
  89                  compareTwoMode: this.frame.get('compareTwoMode'),
  90                  from: this.frame.get('from'),
  91                  to: this.frame.get('to')
  92              });
  93              this.updateSliderSettings();
  94          },
  95  
  96          getSliderValue: function( a, b ) {
  97              return isRtl ? this.revisions.length - this.revisions.indexOf( this.get(a) ) - 1 : this.revisions.indexOf( this.get(b) );
  98          },
  99  
 100          updateSliderSettings: function() {
 101              if ( this.get('compareTwoMode') ) {
 102                  this.set({
 103                      values: [
 104                          this.getSliderValue( 'to', 'from' ),
 105                          this.getSliderValue( 'from', 'to' )
 106                      ],
 107                      value: null,
 108                      range: true // ensures handles cannot cross
 109                  });
 110              } else {
 111                  this.set({
 112                      value: this.getSliderValue( 'to', 'to' ),
 113                      values: null,
 114                      range: false
 115                  });
 116              }
 117              this.trigger( 'update:slider' );
 118          },
 119  
 120          // Called when a revision is hovered
 121          hoverRevision: function( model, value ) {
 122              this.trigger( 'hovered:revision', value );
 123          },
 124  
 125          // Called when `compareTwoMode` changes
 126          updateMode: function( model, value ) {
 127              this.set({ compareTwoMode: value });
 128          },
 129  
 130          // Called when `from` or `to` changes in the local model
 131          handleLocalChanges: function() {
 132              this.frame.set({
 133                  from: this.get('from'),
 134                  to: this.get('to')
 135              });
 136          },
 137  
 138          // Receives revisions changes from outside the model
 139          receiveRevisions: function( from, to ) {
 140              // Bail if nothing changed
 141              if ( this.get('from') === from && this.get('to') === to ) {
 142                  return;
 143              }
 144  
 145              this.set({ from: from, to: to }, { silent: true });
 146              this.trigger( 'update:revisions', from, to );
 147          }
 148  
 149      });
 150  
 151      revisions.model.Tooltip = Backbone.Model.extend({
 152          defaults: {
 153              revision: null,
 154              offset: {},
 155              hovering: false, // Whether the mouse is hovering
 156              scrubbing: false // Whether the mouse is scrubbing
 157          },
 158  
 159          initialize: function( options ) {
 160              this.frame = options.frame;
 161              this.revisions = options.revisions;
 162              this.slider = options.slider;
 163  
 164              this.listenTo( this.slider, 'hovered:revision', this.updateRevision );
 165              this.listenTo( this.slider, 'change:hovering', this.setHovering );
 166              this.listenTo( this.slider, 'change:scrubbing', this.setScrubbing );
 167          },
 168  
 169  
 170          updateRevision: function( revision ) {
 171              this.set({ revision: revision });
 172          },
 173  
 174          setHovering: function( model, value ) {
 175              this.set({ hovering: value });
 176          },
 177  
 178          setScrubbing: function( model, value ) {
 179              this.set({ scrubbing: value });
 180          }
 181      });
 182  
 183      revisions.model.Revision = Backbone.Model.extend({});
 184  
 185      /**
 186       * wp.revisions.model.Revisions
 187       *
 188       * A collection of post revisions.
 189       */
 190      revisions.model.Revisions = Backbone.Collection.extend({
 191          model: revisions.model.Revision,
 192  
 193          initialize: function() {
 194              _.bindAll( this, 'next', 'prev' );
 195          },
 196  
 197          next: function( revision ) {
 198              var index = this.indexOf( revision );
 199  
 200              if ( index !== -1 && index !== this.length - 1 ) {
 201                  return this.at( index + 1 );
 202              }
 203          },
 204  
 205          prev: function( revision ) {
 206              var index = this.indexOf( revision );
 207  
 208              if ( index !== -1 && index !== 0 ) {
 209                  return this.at( index - 1 );
 210              }
 211          }
 212      });
 213  
 214      revisions.model.Field = Backbone.Model.extend({});
 215  
 216      revisions.model.Fields = Backbone.Collection.extend({
 217          model: revisions.model.Field
 218      });
 219  
 220      revisions.model.Diff = Backbone.Model.extend({
 221          initialize: function() {
 222              var fields = this.get('fields');
 223              this.unset('fields');
 224  
 225              this.fields = new revisions.model.Fields( fields );
 226          }
 227      });
 228  
 229      revisions.model.Diffs = Backbone.Collection.extend({
 230          initialize: function( models, options ) {
 231              _.bindAll( this, 'getClosestUnloaded' );
 232              this.loadAll = _.once( this._loadAll );
 233              this.revisions = options.revisions;
 234              this.postId = options.postId;
 235              this.requests  = {};
 236          },
 237  
 238          model: revisions.model.Diff,
 239  
 240          ensure: function( id, context ) {
 241              var diff     = this.get( id ),
 242                  request  = this.requests[ id ],
 243                  deferred = $.Deferred(),
 244                  ids      = {},
 245                  from     = id.split(':')[0],
 246                  to       = id.split(':')[1];
 247              ids[id] = true;
 248  
 249              wp.revisions.log( 'ensure', id );
 250  
 251              this.trigger( 'ensure', ids, from, to, deferred.promise() );
 252  
 253              if ( diff ) {
 254                  deferred.resolveWith( context, [ diff ] );
 255              } else {
 256                  this.trigger( 'ensure:load', ids, from, to, deferred.promise() );
 257                  _.each( ids, _.bind( function( id ) {
 258                      // Remove anything that has an ongoing request
 259                      if ( this.requests[ id ] ) {
 260                          delete ids[ id ];
 261                      }
 262                      // Remove anything we already have
 263                      if ( this.get( id ) ) {
 264                          delete ids[ id ];
 265                      }
 266                  }, this ) );
 267                  if ( ! request ) {
 268                      // Always include the ID that started this ensure
 269                      ids[ id ] = true;
 270                      request   = this.load( _.keys( ids ) );
 271                  }
 272  
 273                  request.done( _.bind( function() {
 274                      deferred.resolveWith( context, [ this.get( id ) ] );
 275                  }, this ) ).fail( _.bind( function() {
 276                      deferred.reject();
 277                  }) );
 278              }
 279  
 280              return deferred.promise();
 281          },
 282  
 283          // Returns an array of proximal diffs
 284          getClosestUnloaded: function( ids, centerId ) {
 285              var self = this;
 286              return _.chain([0].concat( ids )).initial().zip( ids ).sortBy( function( pair ) {
 287                  return Math.abs( centerId - pair[1] );
 288              }).map( function( pair ) {
 289                  return pair.join(':');
 290              }).filter( function( diffId ) {
 291                  return _.isUndefined( self.get( diffId ) ) && ! self.requests[ diffId ];
 292              }).value();
 293          },
 294  
 295          _loadAll: function( allRevisionIds, centerId, num ) {
 296              var self = this, deferred = $.Deferred(),
 297                  diffs = _.first( this.getClosestUnloaded( allRevisionIds, centerId ), num );
 298              if ( _.size( diffs ) > 0 ) {
 299                  this.load( diffs ).done( function() {
 300                      self._loadAll( allRevisionIds, centerId, num ).done( function() {
 301                          deferred.resolve();
 302                      });
 303                  }).fail( function() {
 304                      if ( 1 === num ) { // Already tried 1. This just isn't working. Give up.
 305                          deferred.reject();
 306                      } else { // Request fewer diffs this time
 307                          self._loadAll( allRevisionIds, centerId, Math.ceil( num / 2 ) ).done( function() {
 308                              deferred.resolve();
 309                          });
 310                      }
 311                  });
 312              } else {
 313                  deferred.resolve();
 314              }
 315              return deferred;
 316          },
 317  
 318          load: function( comparisons ) {
 319              wp.revisions.log( 'load', comparisons );
 320              // Our collection should only ever grow, never shrink, so remove: false
 321              return this.fetch({ data: { compare: comparisons }, remove: false }).done( function() {
 322                  wp.revisions.log( 'load:complete', comparisons );
 323              });
 324          },
 325  
 326          sync: function( method, model, options ) {
 327              if ( 'read' === method ) {
 328                  options = options || {};
 329                  options.context = this;
 330                  options.data = _.extend( options.data || {}, {
 331                      action: 'get-revision-diffs',
 332                      post_id: this.postId
 333                  });
 334  
 335                  var deferred = wp.ajax.send( options ),
 336                      requests = this.requests;
 337  
 338                  // Record that we're requesting each diff.
 339                  if ( options.data.compare ) {
 340                      _.each( options.data.compare, function( id ) {
 341                          requests[ id ] = deferred;
 342                      });
 343                  }
 344  
 345                  // When the request completes, clear the stored request.
 346                  deferred.always( function() {
 347                      if ( options.data.compare ) {
 348                          _.each( options.data.compare, function( id ) {
 349                              delete requests[ id ];
 350                          });
 351                      }
 352                  });
 353  
 354                  return deferred;
 355  
 356              // Otherwise, fall back to `Backbone.sync()`.
 357              } else {
 358                  return Backbone.Model.prototype.sync.apply( this, arguments );
 359              }
 360          }
 361      });
 362  
 363  
 364      /**
 365       * wp.revisions.model.FrameState
 366       *
 367       * The frame state.
 368       *
 369       * @see wp.revisions.view.Frame
 370       *
 371       * @param {object}                    attributes        Model attributes - none are required.
 372       * @param {object}                    options           Options for the model.
 373       * @param {revisions.model.Revisions} options.revisions A collection of revisions.
 374       */
 375      revisions.model.FrameState = Backbone.Model.extend({
 376          defaults: {
 377              loading: false,
 378              error: false,
 379              compareTwoMode: false
 380          },
 381  
 382          initialize: function( attributes, options ) {
 383              var state = this.get( 'initialDiffState' );
 384              _.bindAll( this, 'receiveDiff' );
 385              this._debouncedEnsureDiff = _.debounce( this._ensureDiff, 200 );
 386  
 387              this.revisions = options.revisions;
 388  
 389              this.diffs = new revisions.model.Diffs( [], {
 390                  revisions: this.revisions,
 391                  postId: this.get( 'postId' )
 392              } );
 393  
 394              // Set the initial diffs collection.
 395              this.diffs.set( this.get( 'diffData' ) );
 396  
 397              // Set up internal listeners
 398              this.listenTo( this, 'change:from', this.changeRevisionHandler );
 399              this.listenTo( this, 'change:to', this.changeRevisionHandler );
 400              this.listenTo( this, 'change:compareTwoMode', this.changeMode );
 401              this.listenTo( this, 'update:revisions', this.updatedRevisions );
 402              this.listenTo( this.diffs, 'ensure:load', this.updateLoadingStatus );
 403              this.listenTo( this, 'update:diff', this.updateLoadingStatus );
 404  
 405              // Set the initial revisions, baseUrl, and mode as provided through attributes.
 406  
 407              this.set( {
 408                  to : this.revisions.get( state.to ),
 409                  from : this.revisions.get( state.from ),
 410                  compareTwoMode : state.compareTwoMode
 411              } );
 412  
 413              // Start the router if browser supports History API
 414              if ( window.history && window.history.pushState ) {
 415                  this.router = new revisions.Router({ model: this });
 416                  if ( Backbone.History.started ) {
 417                      Backbone.history.stop();
 418                  }
 419                  Backbone.history.start({ pushState: true });
 420              }
 421          },
 422  
 423          updateLoadingStatus: function() {
 424              this.set( 'error', false );
 425              this.set( 'loading', ! this.diff() );
 426          },
 427  
 428          changeMode: function( model, value ) {
 429              var toIndex = this.revisions.indexOf( this.get( 'to' ) );
 430  
 431              // If we were on the first revision before switching to two-handled mode,
 432              // bump the 'to' position over one
 433              if ( value && 0 === toIndex ) {
 434                  this.set({
 435                      from: this.revisions.at( toIndex ),
 436                      to:   this.revisions.at( toIndex + 1 )
 437                  });
 438              }
 439  
 440              // When switching back to single-handled mode, reset 'from' model to
 441              // one position before the 'to' model
 442              if ( ! value && 0 !== toIndex ) { // '! value' means switching to single-handled mode
 443                  this.set({
 444                      from: this.revisions.at( toIndex - 1 ),
 445                      to:   this.revisions.at( toIndex )
 446                  });
 447              }
 448          },
 449  
 450          updatedRevisions: function( from, to ) {
 451              if ( this.get( 'compareTwoMode' ) ) {
 452                  // TODO: compare-two loading strategy
 453              } else {
 454                  this.diffs.loadAll( this.revisions.pluck('id'), to.id, 40 );
 455              }
 456          },
 457  
 458          // Fetch the currently loaded diff.
 459          diff: function() {
 460              return this.diffs.get( this._diffId );
 461          },
 462  
 463          // So long as `from` and `to` are changed at the same time, the diff
 464          // will only be updated once. This is because Backbone updates all of
 465          // the changed attributes in `set`, and then fires the `change` events.
 466          updateDiff: function( options ) {
 467              var from, to, diffId, diff;
 468  
 469              options = options || {};
 470              from = this.get('from');
 471              to = this.get('to');
 472              diffId = ( from ? from.id : 0 ) + ':' + to.id;
 473  
 474              // Check if we're actually changing the diff id.
 475              if ( this._diffId === diffId ) {
 476                  return $.Deferred().reject().promise();
 477              }
 478  
 479              this._diffId = diffId;
 480              this.trigger( 'update:revisions', from, to );
 481  
 482              diff = this.diffs.get( diffId );
 483  
 484              // If we already have the diff, then immediately trigger the update.
 485              if ( diff ) {
 486                  this.receiveDiff( diff );
 487                  return $.Deferred().resolve().promise();
 488              // Otherwise, fetch the diff.
 489              } else {
 490                  if ( options.immediate ) {
 491                      return this._ensureDiff();
 492                  } else {
 493                      this._debouncedEnsureDiff();
 494                      return $.Deferred().reject().promise();
 495                  }
 496              }
 497          },
 498  
 499          // A simple wrapper around `updateDiff` to prevent the change event's
 500          // parameters from being passed through.
 501          changeRevisionHandler: function() {
 502              this.updateDiff();
 503          },
 504  
 505          receiveDiff: function( diff ) {
 506              // Did we actually get a diff?
 507              if ( _.isUndefined( diff ) || _.isUndefined( diff.id ) ) {
 508                  this.set({
 509                      loading: false,
 510                      error: true
 511                  });
 512              } else if ( this._diffId === diff.id ) { // Make sure the current diff didn't change
 513                  this.trigger( 'update:diff', diff );
 514              }
 515          },
 516  
 517          _ensureDiff: function() {
 518              return this.diffs.ensure( this._diffId, this ).always( this.receiveDiff );
 519          }
 520      });
 521  
 522  
 523      /**
 524       * ========================================================================
 525       * VIEWS
 526       * ========================================================================
 527       */
 528  
 529      /**
 530       * wp.revisions.view.Frame
 531       *
 532       * Top level frame that orchestrates the revisions experience.
 533       *
 534       * @param {object}                     options       The options hash for the view.
 535       * @param {revisions.model.FrameState} options.model The frame state model.
 536       */
 537      revisions.view.Frame = wp.Backbone.View.extend({
 538          className: 'revisions',
 539          template: wp.template('revisions-frame'),
 540  
 541          initialize: function() {
 542              this.listenTo( this.model, 'update:diff', this.renderDiff );
 543              this.listenTo( this.model, 'change:compareTwoMode', this.updateCompareTwoMode );
 544              this.listenTo( this.model, 'change:loading', this.updateLoadingStatus );
 545              this.listenTo( this.model, 'change:error', this.updateErrorStatus );
 546  
 547              this.views.set( '.revisions-control-frame', new revisions.view.Controls({
 548                  model: this.model
 549              }) );
 550          },
 551  
 552          render: function() {
 553              wp.Backbone.View.prototype.render.apply( this, arguments );
 554  
 555              $('html').css( 'overflow-y', 'scroll' );
 556              $('#wpbody-content .wrap').append( this.el );
 557              this.updateCompareTwoMode();
 558              this.renderDiff( this.model.diff() );
 559              this.views.ready();
 560  
 561              return this;
 562          },
 563  
 564          renderDiff: function( diff ) {
 565              this.views.set( '.revisions-diff-frame', new revisions.view.Diff({
 566                  model: diff
 567              }) );
 568          },
 569  
 570          updateLoadingStatus: function() {
 571              this.$el.toggleClass( 'loading', this.model.get('loading') );
 572          },
 573  
 574          updateErrorStatus: function() {
 575              this.$el.toggleClass( 'diff-error', this.model.get('error') );
 576          },
 577  
 578          updateCompareTwoMode: function() {
 579              this.$el.toggleClass( 'comparing-two-revisions', this.model.get('compareTwoMode') );
 580          }
 581      });
 582  
 583      /**
 584       * wp.revisions.view.Controls
 585       *
 586       * The controls view.
 587       *
 588       * Contains the revision slider, previous/next buttons, the meta info and the compare checkbox.
 589       */
 590      revisions.view.Controls = wp.Backbone.View.extend({
 591          className: 'revisions-controls',
 592  
 593          initialize: function() {
 594              _.bindAll( this, 'setWidth' );
 595  
 596              // Add the button view
 597              this.views.add( new revisions.view.Buttons({
 598                  model: this.model
 599              }) );
 600  
 601              // Add the checkbox view
 602              this.views.add( new revisions.view.Checkbox({
 603                  model: this.model
 604              }) );
 605  
 606              // Prep the slider model
 607              var slider = new revisions.model.Slider({
 608                  frame: this.model,
 609                  revisions: this.model.revisions
 610              }),
 611  
 612              // Prep the tooltip model
 613              tooltip = new revisions.model.Tooltip({
 614                  frame: this.model,
 615                  revisions: this.model.revisions,
 616                  slider: slider
 617              });
 618  
 619              // Add the tooltip view
 620              this.views.add( new revisions.view.Tooltip({
 621                  model: tooltip
 622              }) );
 623  
 624              // Add the tickmarks view
 625              this.views.add( new revisions.view.Tickmarks({
 626                  model: tooltip
 627              }) );
 628  
 629              // Add the slider view
 630              this.views.add( new revisions.view.Slider({
 631                  model: slider
 632              }) );
 633  
 634              // Add the Metabox view
 635              this.views.add( new revisions.view.Metabox({
 636                  model: this.model
 637              }) );
 638          },
 639  
 640          ready: function() {
 641              this.top = this.$el.offset().top;
 642              this.window = $(window);
 643              this.window.on( 'scroll.wp.revisions', {controls: this}, function(e) {
 644                  var controls  = e.data.controls,
 645                      container = controls.$el.parent(),
 646                      scrolled  = controls.window.scrollTop(),
 647                      frame     = controls.views.parent;
 648  
 649                  if ( scrolled >= controls.top ) {
 650                      if ( ! frame.$el.hasClass('pinned') ) {
 651                          controls.setWidth();
 652                          container.css('height', container.height() + 'px' );
 653                          controls.window.on('resize.wp.revisions.pinning click.wp.revisions.pinning', {controls: controls}, function(e) {
 654                              e.data.controls.setWidth();
 655                          });
 656                      }
 657                      frame.$el.addClass('pinned');
 658                  } else if ( frame.$el.hasClass('pinned') ) {
 659                      controls.window.off('.wp.revisions.pinning');
 660                      controls.$el.css('width', 'auto');
 661                      frame.$el.removeClass('pinned');
 662                      container.css('height', 'auto');
 663                      controls.top = controls.$el.offset().top;
 664                  } else {
 665                      controls.top = controls.$el.offset().top;
 666                  }
 667              });
 668          },
 669  
 670          setWidth: function() {
 671              this.$el.css('width', this.$el.parent().width() + 'px');
 672          }
 673      });
 674  
 675      // The tickmarks view
 676      revisions.view.Tickmarks = wp.Backbone.View.extend({
 677          className: 'revisions-tickmarks',
 678          direction: isRtl ? 'right' : 'left',
 679  
 680          initialize: function() {
 681              this.listenTo( this.model, 'change:revision', this.reportTickPosition );
 682          },
 683  
 684          reportTickPosition: function( model, revision ) {
 685              var offset, thisOffset, parentOffset, tick, index = this.model.revisions.indexOf( revision );
 686              thisOffset = this.$el.allOffsets();
 687              parentOffset = this.$el.parent().allOffsets();
 688              if ( index === this.model.revisions.length - 1 ) {
 689                  // Last one
 690                  offset = {
 691                      rightPlusWidth: thisOffset.left - parentOffset.left + 1,
 692                      leftPlusWidth: thisOffset.right - parentOffset.right + 1
 693                  };
 694              } else {
 695                  // Normal tick
 696                  tick = this.$('div:nth-of-type(' + (index + 1) + ')');
 697                  offset = tick.allPositions();
 698                  _.extend( offset, {
 699                      left: offset.left + thisOffset.left - parentOffset.left,
 700                      right: offset.right + thisOffset.right - parentOffset.right
 701                  });
 702                  _.extend( offset, {
 703                      leftPlusWidth: offset.left + tick.outerWidth(),
 704                      rightPlusWidth: offset.right + tick.outerWidth()
 705                  });
 706              }
 707              this.model.set({ offset: offset });
 708          },
 709  
 710          ready: function() {
 711              var tickCount, tickWidth;
 712              tickCount = this.model.revisions.length - 1;
 713              tickWidth = 1 / tickCount;
 714              this.$el.css('width', ( this.model.revisions.length * 50 ) + 'px');
 715  
 716              _(tickCount).times( function( index ){
 717                  this.$el.append( '<div style="' + this.direction + ': ' + ( 100 * tickWidth * index ) + '%"></div>' );
 718              }, this );
 719          }
 720      });
 721  
 722      // The metabox view
 723      revisions.view.Metabox = wp.Backbone.View.extend({
 724          className: 'revisions-meta',
 725  
 726          initialize: function() {
 727              // Add the 'from' view
 728              this.views.add( new revisions.view.MetaFrom({
 729                  model: this.model,
 730                  className: 'diff-meta diff-meta-from'
 731              }) );
 732  
 733              // Add the 'to' view
 734              this.views.add( new revisions.view.MetaTo({
 735                  model: this.model
 736              }) );
 737          }
 738      });
 739  
 740      // The revision meta view (to be extended)
 741      revisions.view.Meta = wp.Backbone.View.extend({
 742          template: wp.template('revisions-meta'),
 743  
 744          events: {
 745              'click .restore-revision': 'restoreRevision'
 746          },
 747  
 748          initialize: function() {
 749              this.listenTo( this.model, 'update:revisions', this.render );
 750          },
 751  
 752          prepare: function() {
 753              return _.extend( this.model.toJSON()[this.type] || {}, {
 754                  type: this.type
 755              });
 756          },
 757  
 758          restoreRevision: function() {
 759              document.location = this.model.get('to').attributes.restoreUrl;
 760          }
 761      });
 762  
 763      // The revision meta 'from' view
 764      revisions.view.MetaFrom = revisions.view.Meta.extend({
 765          className: 'diff-meta diff-meta-from',
 766          type: 'from'
 767      });
 768  
 769      // The revision meta 'to' view
 770      revisions.view.MetaTo = revisions.view.Meta.extend({
 771          className: 'diff-meta diff-meta-to',
 772          type: 'to'
 773      });
 774  
 775      // The checkbox view.
 776      revisions.view.Checkbox = wp.Backbone.View.extend({
 777          className: 'revisions-checkbox',
 778          template: wp.template('revisions-checkbox'),
 779  
 780          events: {
 781              'click .compare-two-revisions': 'compareTwoToggle'
 782          },
 783  
 784          initialize: function() {
 785              this.listenTo( this.model, 'change:compareTwoMode', this.updateCompareTwoMode );
 786          },
 787  
 788          ready: function() {
 789              if ( this.model.revisions.length < 3 ) {
 790                  $('.revision-toggle-compare-mode').hide();
 791              }
 792          },
 793  
 794          updateCompareTwoMode: function() {
 795              this.$('.compare-two-revisions').prop( 'checked', this.model.get('compareTwoMode') );
 796          },
 797  
 798          // Toggle the compare two mode feature when the compare two checkbox is checked.
 799          compareTwoToggle: function() {
 800              // Activate compare two mode?
 801              this.model.set({ compareTwoMode: $('.compare-two-revisions').prop('checked') });
 802          }
 803      });
 804  
 805      // The tooltip view.
 806      // Encapsulates the tooltip.
 807      revisions.view.Tooltip = wp.Backbone.View.extend({
 808          className: 'revisions-tooltip',
 809          template: wp.template('revisions-meta'),
 810  
 811          initialize: function() {
 812              this.listenTo( this.model, 'change:offset', this.render );
 813              this.listenTo( this.model, 'change:hovering', this.toggleVisibility );
 814              this.listenTo( this.model, 'change:scrubbing', this.toggleVisibility );
 815          },
 816  
 817          prepare: function() {
 818              if ( _.isNull( this.model.get('revision') ) ) {
 819                  return;
 820              } else {
 821                  return _.extend( { type: 'tooltip' }, {
 822                      attributes: this.model.get('revision').toJSON()
 823                  });
 824              }
 825          },
 826  
 827          render: function() {
 828              var otherDirection,
 829                  direction,
 830                  directionVal,
 831                  flipped,
 832                  css      = {},
 833                  position = this.model.revisions.indexOf( this.model.get('revision') ) + 1;
 834  
 835              flipped = ( position / this.model.revisions.length ) > 0.5;
 836              if ( isRtl ) {
 837                  direction = flipped ? 'left' : 'right';
 838                  directionVal = flipped ? 'leftPlusWidth' : direction;
 839              } else {
 840                  direction = flipped ? 'right' : 'left';
 841                  directionVal = flipped ? 'rightPlusWidth' : direction;
 842              }
 843              otherDirection = 'right' === direction ? 'left': 'right';
 844              wp.Backbone.View.prototype.render.apply( this, arguments );
 845              css[direction] = this.model.get('offset')[directionVal] + 'px';
 846              css[otherDirection] = '';
 847              this.$el.toggleClass( 'flipped', flipped ).css( css );
 848          },
 849  
 850          visible: function() {
 851              return this.model.get( 'scrubbing' ) || this.model.get( 'hovering' );
 852          },
 853  
 854          toggleVisibility: function() {
 855              if ( this.visible() ) {
 856                  this.$el.stop().show().fadeTo( 100 - this.el.style.opacity * 100, 1 );
 857              } else {
 858                  this.$el.stop().fadeTo( this.el.style.opacity * 300, 0, function(){ $(this).hide(); } );
 859              }
 860              return;
 861          }
 862      });
 863  
 864      // The buttons view.
 865      // Encapsulates all of the configuration for the previous/next buttons.
 866      revisions.view.Buttons = wp.Backbone.View.extend({
 867          className: 'revisions-buttons',
 868          template: wp.template('revisions-buttons'),
 869  
 870          events: {
 871              'click .revisions-next .button': 'nextRevision',
 872              'click .revisions-previous .button': 'previousRevision'
 873          },
 874  
 875          initialize: function() {
 876              this.listenTo( this.model, 'update:revisions', this.disabledButtonCheck );
 877          },
 878  
 879          ready: function() {
 880              this.disabledButtonCheck();
 881          },
 882  
 883          // Go to a specific model index
 884          gotoModel: function( toIndex ) {
 885              var attributes = {
 886                  to: this.model.revisions.at( toIndex )
 887              };
 888              // If we're at the first revision, unset 'from'.
 889              if ( toIndex ) {
 890                  attributes.from = this.model.revisions.at( toIndex - 1 );
 891              } else {
 892                  this.model.unset('from', { silent: true });
 893              }
 894  
 895              this.model.set( attributes );
 896          },
 897  
 898          // Go to the 'next' revision
 899          nextRevision: function() {
 900              var toIndex = this.model.revisions.indexOf( this.model.get('to') ) + 1;
 901              this.gotoModel( toIndex );
 902          },
 903  
 904          // Go to the 'previous' revision
 905          previousRevision: function() {
 906              var toIndex = this.model.revisions.indexOf( this.model.get('to') ) - 1;
 907              this.gotoModel( toIndex );
 908          },
 909  
 910          // Check to see if the Previous or Next buttons need to be disabled or enabled.
 911          disabledButtonCheck: function() {
 912              var maxVal   = this.model.revisions.length - 1,
 913                  minVal   = 0,
 914                  next     = $('.revisions-next .button'),
 915                  previous = $('.revisions-previous .button'),
 916                  val      = this.model.revisions.indexOf( this.model.get('to') );
 917  
 918              // Disable "Next" button if you're on the last node.
 919              next.prop( 'disabled', ( maxVal === val ) );
 920  
 921              // Disable "Previous" button if you're on the first node.
 922              previous.prop( 'disabled', ( minVal === val ) );
 923          }
 924      });
 925  
 926  
 927      // The slider view.
 928      revisions.view.Slider = wp.Backbone.View.extend({
 929          className: 'wp-slider',
 930          direction: isRtl ? 'right' : 'left',
 931  
 932          events: {
 933              'mousemove' : 'mouseMove'
 934          },
 935  
 936          initialize: function() {
 937              _.bindAll( this, 'start', 'slide', 'stop', 'mouseMove', 'mouseEnter', 'mouseLeave' );
 938              this.listenTo( this.model, 'update:slider', this.applySliderSettings );
 939          },
 940  
 941          ready: function() {
 942              this.$el.css('width', ( this.model.revisions.length * 50 ) + 'px');
 943              this.$el.slider( _.extend( this.model.toJSON(), {
 944                  start: this.start,
 945                  slide: this.slide,
 946                  stop:  this.stop
 947              }) );
 948  
 949              this.$el.hoverIntent({
 950                  over: this.mouseEnter,
 951                  out: this.mouseLeave,
 952                  timeout: 800
 953              });
 954  
 955              this.applySliderSettings();
 956          },
 957  
 958          mouseMove: function( e ) {
 959              var zoneCount         = this.model.revisions.length - 1, // One fewer zone than models
 960                  sliderFrom        = this.$el.allOffsets()[this.direction], // "From" edge of slider
 961                  sliderWidth       = this.$el.width(), // Width of slider
 962                  tickWidth         = sliderWidth / zoneCount, // Calculated width of zone
 963                  actualX           = ( isRtl ? $(window).width() - e.pageX : e.pageX ) - sliderFrom, // Flipped for RTL - sliderFrom;
 964                  currentModelIndex = Math.floor( ( actualX  + ( tickWidth / 2 )  ) / tickWidth ); // Calculate the model index
 965  
 966              // Ensure sane value for currentModelIndex.
 967              if ( currentModelIndex < 0 ) {
 968                  currentModelIndex = 0;
 969              } else if ( currentModelIndex >= this.model.revisions.length ) {
 970                  currentModelIndex = this.model.revisions.length - 1;
 971              }
 972  
 973              // Update the tooltip mode
 974              this.model.set({ hoveredRevision: this.model.revisions.at( currentModelIndex ) });
 975          },
 976  
 977          mouseLeave: function() {
 978              this.model.set({ hovering: false });
 979          },
 980  
 981          mouseEnter: function() {
 982              this.model.set({ hovering: true });
 983          },
 984  
 985          applySliderSettings: function() {
 986              this.$el.slider( _.pick( this.model.toJSON(), 'value', 'values', 'range' ) );
 987              var handles = this.$('a.ui-slider-handle');
 988  
 989              if ( this.model.get('compareTwoMode') ) {
 990                  // in RTL mode the 'left handle' is the second in the slider, 'right' is first
 991                  handles.first()
 992                      .toggleClass( 'to-handle', !! isRtl )
 993                      .toggleClass( 'from-handle', ! isRtl );
 994                  handles.last()
 995                      .toggleClass( 'from-handle', !! isRtl )
 996                      .toggleClass( 'to-handle', ! isRtl );
 997              } else {
 998                  handles.removeClass('from-handle to-handle');
 999              }
1000          },
1001  
1002          start: function( event, ui ) {
1003              this.model.set({ scrubbing: true });
1004  
1005              // Track the mouse position to enable smooth dragging,
1006              // overrides default jQuery UI step behavior.
1007              $( window ).on( 'mousemove.wp.revisions', { view: this }, function( e ) {
1008                  var handles,
1009                      view              = e.data.view,
1010                      leftDragBoundary  = view.$el.offset().left,
1011                      sliderOffset      = leftDragBoundary,
1012                      sliderRightEdge   = leftDragBoundary + view.$el.width(),
1013                      rightDragBoundary = sliderRightEdge,
1014                      leftDragReset     = '0',
1015                      rightDragReset    = '100%',
1016                      handle            = $( ui.handle );
1017  
1018                  // In two handle mode, ensure handles can't be dragged past each other.
1019                  // Adjust left/right boundaries and reset points.
1020                  if ( view.model.get('compareTwoMode') ) {
1021                      handles = handle.parent().find('.ui-slider-handle');
1022                      if ( handle.is( handles.first() ) ) { // We're the left handle
1023                          rightDragBoundary = handles.last().offset().left;
1024                          rightDragReset    = rightDragBoundary - sliderOffset;
1025                      } else { // We're the right handle
1026                          leftDragBoundary = handles.first().offset().left + handles.first().width();
1027                          leftDragReset    = leftDragBoundary - sliderOffset;
1028                      }
1029                  }
1030  
1031                  // Follow mouse movements, as long as handle remains inside slider.
1032                  if ( e.pageX < leftDragBoundary ) {
1033                      handle.css( 'left', leftDragReset ); // Mouse to left of slider.
1034                  } else if ( e.pageX > rightDragBoundary ) {
1035                      handle.css( 'left', rightDragReset ); // Mouse to right of slider.
1036                  } else {
1037                      handle.css( 'left', e.pageX - sliderOffset ); // Mouse in slider.
1038                  }
1039              } );
1040          },
1041  
1042          getPosition: function( position ) {
1043              return isRtl ? this.model.revisions.length - position - 1: position;
1044          },
1045  
1046          // Responds to slide events
1047          slide: function( event, ui ) {
1048              var attributes, movedRevision;
1049              // Compare two revisions mode
1050              if ( this.model.get('compareTwoMode') ) {
1051                  // Prevent sliders from occupying same spot
1052                  if ( ui.values[1] === ui.values[0] ) {
1053                      return false;
1054                  }
1055                  if ( isRtl ) {
1056                      ui.values.reverse();
1057                  }
1058                  attributes = {
1059                      from: this.model.revisions.at( this.getPosition( ui.values[0] ) ),
1060                      to: this.model.revisions.at( this.getPosition( ui.values[1] ) )
1061                  };
1062              } else {
1063                  attributes = {
1064                      to: this.model.revisions.at( this.getPosition( ui.value ) )
1065                  };
1066                  // If we're at the first revision, unset 'from'.
1067                  if ( this.getPosition( ui.value ) > 0 ) {
1068                      attributes.from = this.model.revisions.at( this.getPosition( ui.value ) - 1 );
1069                  } else {
1070                      attributes.from = undefined;
1071                  }
1072              }
1073              movedRevision = this.model.revisions.at( this.getPosition( ui.value ) );
1074  
1075              // If we are scrubbing, a scrub to a revision is considered a hover
1076              if ( this.model.get('scrubbing') ) {
1077                  attributes.hoveredRevision = movedRevision;
1078              }
1079  
1080              this.model.set( attributes );
1081          },
1082  
1083          stop: function() {
1084              $( window ).off('mousemove.wp.revisions');
1085              this.model.updateSliderSettings(); // To snap us back to a tick mark
1086              this.model.set({ scrubbing: false });
1087          }
1088      });
1089  
1090      // The diff view.
1091      // This is the view for the current active diff.
1092      revisions.view.Diff = wp.Backbone.View.extend({
1093          className: 'revisions-diff',
1094          template:  wp.template('revisions-diff'),
1095  
1096          // Generate the options to be passed to the template.
1097          prepare: function() {
1098              return _.extend({ fields: this.model.fields.toJSON() }, this.options );
1099          }
1100      });
1101  
1102      // The revisions router.
1103      // Maintains the URL routes so browser URL matches state.
1104      revisions.Router = Backbone.Router.extend({
1105          initialize: function( options ) {
1106              this.model = options.model;
1107  
1108              // Maintain state and history when navigating
1109              this.listenTo( this.model, 'update:diff', _.debounce( this.updateUrl, 250 ) );
1110              this.listenTo( this.model, 'change:compareTwoMode', this.updateUrl );
1111          },
1112  
1113          baseUrl: function( url ) {
1114              return this.model.get('baseUrl') + url;
1115          },
1116  
1117          updateUrl: function() {
1118              var from = this.model.has('from') ? this.model.get('from').id : 0,
1119                  to   = this.model.get('to').id;
1120              if ( this.model.get('compareTwoMode' ) ) {
1121                  this.navigate( this.baseUrl( '?from=' + from + '&to=' + to ), { replace: true } );
1122              } else {
1123                  this.navigate( this.baseUrl( '?revision=' + to ), { replace: true } );
1124              }
1125          },
1126  
1127          handleRoute: function( a, b ) {
1128              var compareTwo = _.isUndefined( b );
1129  
1130              if ( ! compareTwo ) {
1131                  b = this.model.revisions.get( a );
1132                  a = this.model.revisions.prev( b );
1133                  b = b ? b.id : 0;
1134                  a = a ? a.id : 0;
1135              }
1136          }
1137      });
1138  
1139      /**
1140       * Initialize the revisions UI for revision.php.
1141       */
1142      revisions.init = function() {
1143          var state;
1144  
1145          // Bail if the current page is not revision.php.
1146          if ( ! window.adminpage || 'revision-php' !== window.adminpage ) {
1147              return;
1148          }
1149  
1150          state = new revisions.model.FrameState({
1151              initialDiffState: {
1152                  // wp_localize_script doesn't stringifies ints, so cast them.
1153                  to: parseInt( revisions.settings.to, 10 ),
1154                  from: parseInt( revisions.settings.from, 10 ),
1155                  // wp_localize_script does not allow for top-level booleans so do a comparator here.
1156                  compareTwoMode: ( revisions.settings.compareTwoMode === '1' )
1157              },
1158              diffData: revisions.settings.diffData,
1159              baseUrl: revisions.settings.baseUrl,
1160              postId: parseInt( revisions.settings.postId, 10 )
1161          }, {
1162              revisions: new revisions.model.Revisions( revisions.settings.revisionData )
1163          });
1164  
1165          revisions.view.frame = new revisions.view.Frame({
1166              model: state
1167          }).render();
1168      };
1169  
1170      $( revisions.init );
1171  }(jQuery));


Generated: Wed Jul 17 01:00:03 2019 Cross-referenced by PHPXref 0.7.1