PageRenderTime 57ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-admin/js/revisions.js

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