PageRenderTime 268ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-admin/js/revisions.js

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