PageRenderTime 28ms CodeModel.GetById 9ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-admin/js/revisions.js

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