HistoryV2Manager.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008
  1. import _ from 'lodash'
  2. /* eslint-disable
  3. camelcase,
  4. max-len,
  5. no-return-assign,
  6. no-unused-vars,
  7. */
  8. // TODO: This file was created by bulk-decaffeinate.
  9. // Fix any style issues and re-enable lint.
  10. /*
  11. * decaffeinate suggestions:
  12. * DS101: Remove unnecessary use of Array.from
  13. * DS102: Remove unnecessary code created because of implicit returns
  14. * DS103: Rewrite code to no longer use __guard__
  15. * DS205: Consider reworking code to avoid use of IIFEs
  16. * DS206: Consider reworking classes to avoid initClass
  17. * DS207: Consider shorter variations of null checks
  18. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  19. */
  20. import moment from 'moment'
  21. import ColorManager from '../colors/ColorManager'
  22. import displayNameForUser from './util/displayNameForUser'
  23. import HistoryViewModes from './util/HistoryViewModes'
  24. import './controllers/HistoryV2ListController'
  25. import './controllers/HistoryV2FileTreeController'
  26. import './controllers/HistoryV2ToolbarController'
  27. import './controllers/HistoryV2AddLabelModalController'
  28. import './controllers/HistoryV2DeleteLabelModalController'
  29. import './directives/infiniteScroll'
  30. import './directives/historyDraggableBoundary'
  31. import './directives/historyDroppableArea'
  32. import './components/historyEntriesList'
  33. import './components/historyEntry'
  34. import './components/historyLabelsList'
  35. import './components/historyLabel'
  36. import './components/historyFileTree'
  37. import './components/historyFileEntity'
  38. let HistoryManager
  39. export default (HistoryManager = (function() {
  40. HistoryManager = class HistoryManager {
  41. static initClass() {
  42. this.prototype.MAX_RECENT_UPDATES_TO_SELECT = 5
  43. this.prototype.BATCH_SIZE = 10
  44. }
  45. constructor(ide, $scope, localStorage) {
  46. this.labelCurrentVersion = this.labelCurrentVersion.bind(this)
  47. this.deleteLabel = this.deleteLabel.bind(this)
  48. this._addLabelLocally = this._addLabelLocally.bind(this)
  49. this.ide = ide
  50. this.$scope = $scope
  51. this.localStorage = localStorage
  52. this.$scope.HistoryViewModes = HistoryViewModes
  53. this._localStorageViewModeProjKey = `history.userPrefs.viewMode.${
  54. $scope.project_id
  55. }`
  56. this._localStorageShowOnlyLabelsProjKey = `history.userPrefs.showOnlyLabels.${
  57. $scope.project_id
  58. }`
  59. this._previouslySelectedPathname = null
  60. this._loadFileTreeRequestCanceller = null
  61. this.hardReset()
  62. this.$scope.toggleHistory = () => {
  63. if (this.$scope.ui.view === 'history') {
  64. this.hide()
  65. } else {
  66. this.show()
  67. this._handleHistoryUIStateChange()
  68. }
  69. this.ide.$timeout(() => {
  70. this.$scope.$broadcast('history:toggle')
  71. }, 0)
  72. }
  73. this.$scope.isHistoryLoading = () => {
  74. let selection = this.$scope.history.selection
  75. return (
  76. this.$scope.history.loadingFileTree ||
  77. (this.$scope.history.viewMode === HistoryViewModes.POINT_IN_TIME &&
  78. selection.file &&
  79. selection.file.loading) ||
  80. (this.$scope.history.viewMode === HistoryViewModes.COMPARE &&
  81. selection.diff &&
  82. selection.diff.loading)
  83. )
  84. }
  85. }
  86. show() {
  87. this.$scope.ui.view = 'history'
  88. this.hardReset()
  89. if (this.$scope.history.showOnlyLabels) {
  90. this.fetchNextBatchOfUpdates()
  91. }
  92. }
  93. hide() {
  94. this.$scope.ui.view = 'editor'
  95. }
  96. _getViewModeUserPref() {
  97. return (
  98. this.localStorage(this._localStorageViewModeProjKey) ||
  99. HistoryViewModes.POINT_IN_TIME
  100. )
  101. }
  102. _getShowOnlyLabelsUserPref() {
  103. return this.localStorage(this._localStorageShowOnlyLabelsProjKey) || false
  104. }
  105. _setViewModeUserPref(viewModeUserPref) {
  106. if (
  107. viewModeUserPref === HistoryViewModes.POINT_IN_TIME ||
  108. viewModeUserPref === HistoryViewModes.COMPARE
  109. ) {
  110. this.localStorage(this._localStorageViewModeProjKey, viewModeUserPref)
  111. }
  112. }
  113. _setShowOnlyLabelsUserPref(showOnlyLabelsUserPref) {
  114. this.localStorage(
  115. this._localStorageShowOnlyLabelsProjKey,
  116. !!showOnlyLabelsUserPref
  117. )
  118. }
  119. hardReset() {
  120. this.$scope.history = {
  121. isV2: true,
  122. updates: [],
  123. viewMode: this._getViewModeUserPref(),
  124. nextBeforeTimestamp: null,
  125. loading: false,
  126. atEnd: false,
  127. userHasFullFeature: undefined,
  128. freeHistoryLimitHit: false,
  129. selection: {
  130. docs: {},
  131. pathname: null,
  132. range: {
  133. fromV: null,
  134. toV: null
  135. },
  136. hoveredRange: {
  137. fromV: null,
  138. toV: null
  139. },
  140. diff: null,
  141. files: [],
  142. file: null
  143. },
  144. error: null,
  145. showOnlyLabels: this._getShowOnlyLabelsUserPref(),
  146. labels: null,
  147. loadingFileTree: true
  148. }
  149. let _deregisterFeatureWatcher = this.$scope.$watch(
  150. 'project.features.versioning',
  151. hasVersioning => {
  152. if (hasVersioning != null) {
  153. this.$scope.history.userHasFullFeature = hasVersioning
  154. if (this.$scope.user.isAdmin) {
  155. this.$scope.history.userHasFullFeature = true
  156. }
  157. _deregisterFeatureWatcher()
  158. }
  159. }
  160. )
  161. }
  162. softReset() {
  163. this.$scope.history.viewMode = this._getViewModeUserPref()
  164. this.$scope.history.selection = {
  165. docs: {},
  166. pathname: null,
  167. range: {
  168. fromV: null,
  169. toV: null
  170. },
  171. hoveredRange: {
  172. fromV: null,
  173. toV: null
  174. },
  175. diff: null, // When history.viewMode == HistoryViewModes.COMPARE
  176. files: [], // When history.viewMode == HistoryViewModes.COMPARE
  177. file: null
  178. }
  179. this.$scope.history.error = null
  180. this.$scope.history.showOnlyLabels = this._getShowOnlyLabelsUserPref()
  181. }
  182. toggleHistoryViewMode() {
  183. if (this.$scope.history.viewMode === HistoryViewModes.COMPARE) {
  184. this.softReset()
  185. this.$scope.history.viewMode = HistoryViewModes.POINT_IN_TIME
  186. this._setViewModeUserPref(HistoryViewModes.POINT_IN_TIME)
  187. } else {
  188. this.softReset()
  189. this.$scope.history.viewMode = HistoryViewModes.COMPARE
  190. this._setViewModeUserPref(HistoryViewModes.COMPARE)
  191. }
  192. this._handleHistoryUIStateChange()
  193. this.ide.$timeout(() => {
  194. this.$scope.$broadcast('history:toggle')
  195. }, 0)
  196. }
  197. _handleHistoryUIStateChange() {
  198. if (this.$scope.history.viewMode === HistoryViewModes.COMPARE) {
  199. if (this.$scope.history.showOnlyLabels) {
  200. this.autoSelectLabelsForComparison()
  201. } else {
  202. this.autoSelectRecentUpdates()
  203. }
  204. } else {
  205. // Point-in-time mode
  206. if (this.$scope.history.showOnlyLabels) {
  207. this.autoSelectLabelForPointInTime()
  208. } else {
  209. this.autoSelectVersionForPointInTime()
  210. }
  211. }
  212. }
  213. setHoverFrom(fromV) {
  214. let selection = this.$scope.history.selection
  215. selection.hoveredRange.fromV = fromV
  216. selection.hoveredRange.toV = selection.range.toV
  217. this.$scope.history.hoveringOverListSelectors = true
  218. }
  219. setHoverTo(toV) {
  220. let selection = this.$scope.history.selection
  221. selection.hoveredRange.toV = toV
  222. selection.hoveredRange.fromV = selection.range.fromV
  223. this.$scope.history.hoveringOverListSelectors = true
  224. }
  225. resetHover() {
  226. let selection = this.$scope.history.selection
  227. selection.hoveredRange.toV = null
  228. selection.hoveredRange.fromV = null
  229. this.$scope.history.hoveringOverListSelectors = false
  230. }
  231. showAllUpdates() {
  232. if (this.$scope.history.showOnlyLabels) {
  233. this.$scope.history.showOnlyLabels = false
  234. this._setShowOnlyLabelsUserPref(false)
  235. this._handleHistoryUIStateChange()
  236. }
  237. }
  238. showOnlyLabels() {
  239. if (!this.$scope.history.showOnlyLabels) {
  240. this.$scope.history.showOnlyLabels = true
  241. this._setShowOnlyLabelsUserPref(true)
  242. this._handleHistoryUIStateChange()
  243. }
  244. }
  245. restoreFile(version, pathname) {
  246. const url = `/project/${this.$scope.project_id}/restore_file`
  247. return this.ide.$http.post(url, {
  248. version,
  249. pathname,
  250. _csrf: window.csrfToken
  251. })
  252. }
  253. loadFileTreeForVersion(version) {
  254. return this._loadFileTree(version, version)
  255. }
  256. loadFileTreeDiff(toV, fromV) {
  257. return this._loadFileTree(toV, fromV)
  258. }
  259. _loadFileTree(toV, fromV) {
  260. let url = `/project/${this.$scope.project_id}/filetree/diff`
  261. let selection = this.$scope.history.selection
  262. const query = [`from=${fromV}`, `to=${toV}`]
  263. url += `?${query.join('&')}`
  264. this.$scope.$applyAsync(
  265. () => (this.$scope.history.loadingFileTree = true)
  266. )
  267. selection.file = null
  268. selection.pathname = null
  269. // If `this._loadFileTreeRequestCanceller` is not null, then we have a request inflight
  270. if (this._loadFileTreeRequestCanceller != null) {
  271. // Resolving it will cancel the inflight request (or, rather, ignore its result)
  272. this._loadFileTreeRequestCanceller.resolve()
  273. }
  274. this._loadFileTreeRequestCanceller = this.ide.$q.defer()
  275. return this.ide.$http
  276. .get(url, { timeout: this._loadFileTreeRequestCanceller.promise })
  277. .then(response => {
  278. this.$scope.history.selection.files = response.data.diff
  279. for (let file of this.$scope.history.selection.files) {
  280. if (file.newPathname != null) {
  281. file.oldPathname = file.pathname
  282. file.pathname = file.newPathname
  283. delete file.newPathname
  284. }
  285. }
  286. this._loadFileTreeRequestCanceller = null
  287. this.$scope.history.loadingFileTree = false
  288. this.autoSelectFile()
  289. })
  290. .catch(err => {
  291. if (err.status !== -1) {
  292. this._loadFileTreeRequestCanceller = null
  293. } else {
  294. this.$scope.history.loadingFileTree = false
  295. }
  296. })
  297. }
  298. selectFile(file) {
  299. if (file != null && file.pathname != null) {
  300. this.$scope.history.selection.pathname = this._previouslySelectedPathname =
  301. file.pathname
  302. this.$scope.history.selection.file = file
  303. if (this.$scope.history.viewMode === HistoryViewModes.POINT_IN_TIME) {
  304. this.loadFileAtPointInTime()
  305. } else {
  306. this.reloadDiff()
  307. }
  308. }
  309. }
  310. autoSelectFile() {
  311. let selectedPathname = null
  312. let files = this.$scope.history.selection.files
  313. let fileToSelect = null
  314. let previouslySelectedFile = null
  315. let previouslySelectedFileHasOp = false
  316. let filesWithOps = this._getFilesWithOps()
  317. const orderedOpTypes = ['edited', 'added', 'renamed', 'removed']
  318. if (this._previouslySelectedPathname != null) {
  319. previouslySelectedFile = _.find(files, {
  320. pathname: this._previouslySelectedPathname
  321. })
  322. previouslySelectedFileHasOp = _.some(filesWithOps, {
  323. pathname: this._previouslySelectedPathname
  324. })
  325. }
  326. if (previouslySelectedFile != null && previouslySelectedFileHasOp) {
  327. fileToSelect = previouslySelectedFile
  328. } else {
  329. for (let opType of orderedOpTypes) {
  330. let fileWithMatchingOpType = _.find(filesWithOps, {
  331. operation: opType
  332. })
  333. if (fileWithMatchingOpType != null) {
  334. fileToSelect = _.find(files, {
  335. pathname: fileWithMatchingOpType.pathname
  336. })
  337. break
  338. }
  339. }
  340. if (fileToSelect == null) {
  341. if (previouslySelectedFile != null) {
  342. fileToSelect = previouslySelectedFile
  343. } else {
  344. let mainFile = _.find(files, function(file) {
  345. return /main\.tex$/.test(file.pathname)
  346. })
  347. if (mainFile != null) {
  348. fileToSelect = mainFile
  349. } else {
  350. let anyTeXFile = _.find(files, function(file) {
  351. return /\.tex$/.test(file.pathname)
  352. })
  353. if (anyTeXFile != null) {
  354. fileToSelect = anyTeXFile
  355. } else {
  356. fileToSelect = files[0]
  357. }
  358. }
  359. }
  360. }
  361. }
  362. this.selectFile(fileToSelect)
  363. }
  364. _getFilesWithOps() {
  365. let filesWithOps
  366. if (this.$scope.history.viewMode === HistoryViewModes.POINT_IN_TIME) {
  367. let currentUpdate = this.getUpdateForVersion(
  368. this.$scope.history.selection.range.toV
  369. )
  370. filesWithOps = []
  371. if (currentUpdate != null) {
  372. for (let pathname of currentUpdate.pathnames) {
  373. filesWithOps.push({
  374. pathname: pathname,
  375. operation: 'edited'
  376. })
  377. }
  378. for (let op of currentUpdate.project_ops) {
  379. let fileWithOp
  380. if (op.add != null) {
  381. fileWithOp = {
  382. pathname: op.add.pathname,
  383. operation: 'added'
  384. }
  385. } else if (op.remove != null) {
  386. fileWithOp = {
  387. pathname: op.remove.pathname,
  388. operation: 'removed'
  389. }
  390. } else if (op.rename != null) {
  391. fileWithOp = {
  392. pathname: op.rename.newPathname,
  393. operation: 'renamed'
  394. }
  395. }
  396. if (fileWithOp != null) {
  397. filesWithOps.push(fileWithOp)
  398. }
  399. }
  400. }
  401. } else {
  402. filesWithOps = _.reduce(
  403. this.$scope.history.selection.files,
  404. (curFilesWithOps, file) => {
  405. if (file.operation) {
  406. curFilesWithOps.push({
  407. pathname: file.pathname,
  408. operation: file.operation
  409. })
  410. }
  411. return curFilesWithOps
  412. },
  413. []
  414. )
  415. }
  416. return filesWithOps
  417. }
  418. autoSelectRecentUpdates() {
  419. if (this.$scope.history.updates.length === 0) {
  420. return
  421. }
  422. let toV = this.$scope.history.updates[0].toV
  423. let fromV = null
  424. let indexOfLastUpdateNotByMe = 0
  425. for (let i = 0; i < this.$scope.history.updates.length; i++) {
  426. const update = this.$scope.history.updates[i]
  427. if (
  428. this._updateContainsUserId(update, this.$scope.user.id) ||
  429. i > this.MAX_RECENT_UPDATES_TO_SELECT
  430. ) {
  431. break
  432. }
  433. indexOfLastUpdateNotByMe = i
  434. }
  435. fromV = this.$scope.history.updates[indexOfLastUpdateNotByMe].fromV
  436. this.selectVersionsForCompare(toV, fromV)
  437. }
  438. autoSelectVersionForPointInTime() {
  439. if (this.$scope.history.updates.length === 0) {
  440. return
  441. }
  442. let versionToSelect = this.$scope.history.updates[0].toV
  443. let range = this.$scope.history.selection.range
  444. if (
  445. range.toV != null &&
  446. range.fromV != null &&
  447. range.toV === range.fromV
  448. ) {
  449. versionToSelect = range.toV
  450. }
  451. this.selectVersionForPointInTime(versionToSelect)
  452. }
  453. autoSelectLastLabel() {
  454. if (
  455. this.$scope.history.labels == null ||
  456. this.$scope.history.labels.length === 0
  457. ) {
  458. return
  459. }
  460. return this.selectLabelForPointInTime(this.$scope.history.labels[0])
  461. }
  462. expandSelectionToVersion(version) {
  463. if (version > this.$scope.history.selection.range.toV) {
  464. this.$scope.history.selection.range.toV = version
  465. } else if (version < this.$scope.history.selection.range.fromV) {
  466. this.$scope.history.selection.range.fromV = version
  467. }
  468. }
  469. selectVersionForPointInTime(version) {
  470. let selection = this.$scope.history.selection
  471. if (
  472. selection.range.toV !== version &&
  473. selection.range.fromV !== version
  474. ) {
  475. selection.range.toV = version
  476. selection.range.fromV = version
  477. this.loadFileTreeForVersion(version)
  478. }
  479. }
  480. selectVersionsForCompare(toV, fromV) {
  481. let range = this.$scope.history.selection.range
  482. if (range.toV !== toV || range.fromV !== fromV) {
  483. range.toV = toV
  484. range.fromV = fromV
  485. this.loadFileTreeDiff(toV, fromV)
  486. }
  487. }
  488. autoSelectLabelForPointInTime() {
  489. const selectedUpdate = this.getUpdateForVersion(
  490. this.$scope.history.selection.range.toV
  491. )
  492. let nSelectedLabels = 0
  493. if (selectedUpdate != null && selectedUpdate.labels != null) {
  494. nSelectedLabels = selectedUpdate.labels.length
  495. }
  496. // If the currently selected update has no labels, select the last one (version-wise)
  497. if (nSelectedLabels === 0) {
  498. this.autoSelectLastLabel()
  499. // If the update has one label, select it
  500. } else if (nSelectedLabels === 1) {
  501. this.selectLabelForPointInTime(selectedUpdate.labels[0])
  502. // If there are multiple labels for the update, select the latest
  503. } else if (nSelectedLabels > 1) {
  504. const sortedLabels = this.ide.$filter('orderBy')(
  505. selectedUpdate.labels,
  506. '-created_at'
  507. )
  508. const lastLabelFromUpdate = sortedLabels[0]
  509. this.selectLabelForPointInTime(lastLabelFromUpdate)
  510. }
  511. }
  512. selectLabelForPointInTime(labelToSelect) {
  513. let updateToSelect = null
  514. if (this._isLabelSelected(labelToSelect)) {
  515. // Label already selected
  516. return
  517. }
  518. for (let update of Array.from(this.$scope.history.updates)) {
  519. if (update.toV === labelToSelect.version) {
  520. updateToSelect = update
  521. break
  522. }
  523. }
  524. if (updateToSelect != null) {
  525. this.selectVersionForPointInTime(updateToSelect.toV)
  526. } else {
  527. let selection = this.$scope.history.selection
  528. selection.range.toV = labelToSelect.version
  529. selection.range.fromV = labelToSelect.version
  530. this.loadFileTreeForVersion(labelToSelect.version)
  531. }
  532. }
  533. getUpdateForVersion(version) {
  534. for (let update of this.$scope.history.updates) {
  535. if (update.toV === version) {
  536. return update
  537. }
  538. }
  539. }
  540. autoSelectLabelsForComparison() {
  541. let labels = this.$scope.history.labels
  542. let nLabels = 0
  543. if (Array.isArray(labels)) {
  544. nLabels = labels.length
  545. }
  546. if (nLabels === 0) {
  547. // TODO better handling
  548. } else if (nLabels === 1) {
  549. this.selectVersionsForCompare(labels[0].version, labels[0].version)
  550. } else if (nLabels > 1) {
  551. this.selectVersionsForCompare(labels[0].version, labels[1].version)
  552. }
  553. }
  554. fetchNextBatchOfUpdates() {
  555. if (this.$scope.history.atEnd) {
  556. return
  557. }
  558. let updatesURL = `/project/${this.ide.project_id}/updates?min_count=${
  559. this.BATCH_SIZE
  560. }`
  561. if (this.$scope.history.nextBeforeTimestamp != null) {
  562. updatesURL += `&before=${this.$scope.history.nextBeforeTimestamp}`
  563. }
  564. const labelsURL = `/project/${this.ide.project_id}/labels`
  565. const requests = { updates: this.ide.$http.get(updatesURL) }
  566. if (this.$scope.history.labels == null) {
  567. requests.labels = this.ide.$http.get(labelsURL)
  568. }
  569. this.$scope.history.loading = true
  570. return this.ide.$q
  571. .all(requests)
  572. .then(response => {
  573. this.$scope.history.loading = false
  574. const updatesData = response.updates.data
  575. let lastUpdateToV = null
  576. if (updatesData.updates.length > 0) {
  577. lastUpdateToV = updatesData.updates[0].toV
  578. }
  579. if (response.labels != null) {
  580. this.$scope.history.labels = this._loadLabels(
  581. response.labels.data,
  582. lastUpdateToV
  583. )
  584. }
  585. this._loadUpdates(updatesData.updates)
  586. this.$scope.history.nextBeforeTimestamp =
  587. updatesData.nextBeforeTimestamp
  588. if (
  589. updatesData.nextBeforeTimestamp == null ||
  590. this.$scope.history.freeHistoryLimitHit ||
  591. this.$scope.history.updates.length === 0
  592. ) {
  593. this.$scope.history.atEnd = true
  594. }
  595. if (this.$scope.history.updates.length === 0) {
  596. this.$scope.history.loadingFileTree = false
  597. }
  598. })
  599. .catch(error => {
  600. this.$scope.history.loading = false
  601. const { status, statusText } = error
  602. this.$scope.history.error = { status, statusText }
  603. this.$scope.history.atEnd = true
  604. this.$scope.history.loadingFileTree = false
  605. })
  606. }
  607. _loadLabels(labels, lastUpdateToV) {
  608. let sortedLabels = this._sortLabelsByVersionAndDate(labels)
  609. let labelsWithoutPseudoLabel = this._deletePseudoCurrentStateLabelIfExistent(
  610. sortedLabels
  611. )
  612. let labelsWithPseudoLabelIfNeeded = this._addPseudoCurrentStateLabelIfNeeded(
  613. labelsWithoutPseudoLabel,
  614. lastUpdateToV
  615. )
  616. return labelsWithPseudoLabelIfNeeded
  617. }
  618. _deletePseudoCurrentStateLabelIfExistent(labels) {
  619. if (labels.length && labels[0].isPseudoCurrentStateLabel) {
  620. labels.shift()
  621. }
  622. return labels
  623. }
  624. _addPseudoCurrentStateLabelIfNeeded(labels, mostRecentVersion) {
  625. if (
  626. (labels.length && labels[0].version !== mostRecentVersion) ||
  627. labels.length === 0
  628. ) {
  629. let pseudoCurrentStateLabel = {
  630. id: '1',
  631. isPseudoCurrentStateLabel: true,
  632. version: mostRecentVersion,
  633. created_at: new Date().toISOString()
  634. }
  635. labels.unshift(pseudoCurrentStateLabel)
  636. }
  637. return labels
  638. }
  639. _sortLabelsByVersionAndDate(labels) {
  640. return this.ide.$filter('orderBy')(labels, [
  641. 'isPseudoCurrentStateLabel',
  642. '-version',
  643. '-created_at'
  644. ])
  645. }
  646. loadFileAtPointInTime() {
  647. const toV = this.$scope.history.selection.range.toV
  648. const { pathname } = this.$scope.history.selection
  649. if (toV == null) {
  650. return
  651. }
  652. let url = `/project/${this.$scope.project_id}/diff`
  653. const query = [
  654. `pathname=${encodeURIComponent(pathname)}`,
  655. `from=${toV}`,
  656. `to=${toV}`
  657. ]
  658. url += `?${query.join('&')}`
  659. this.$scope.history.selection.file.loading = true
  660. return this.ide.$http
  661. .get(url)
  662. .then(response => {
  663. const { text, binary } = this._parseDiff(response.data.diff)
  664. this.$scope.history.selection.file.binary = binary
  665. this.$scope.history.selection.file.text = text
  666. this.$scope.history.selection.file.loading = false
  667. })
  668. .catch(function() {})
  669. }
  670. reloadDiff() {
  671. let { diff } = this.$scope.history.selection
  672. const { range, pathname } = this.$scope.history.selection
  673. const { fromV, toV } = range
  674. if (pathname == null) {
  675. this.$scope.history.selection.diff = null
  676. return
  677. }
  678. if (
  679. diff != null &&
  680. diff.pathname === pathname &&
  681. diff.fromV === fromV &&
  682. diff.toV === toV
  683. ) {
  684. return
  685. }
  686. this.$scope.history.selection.diff = diff = {
  687. fromV,
  688. toV,
  689. pathname,
  690. error: false
  691. }
  692. diff.loading = true
  693. let url = `/project/${this.$scope.project_id}/diff`
  694. const query = [`pathname=${encodeURIComponent(pathname)}`]
  695. if (diff.fromV != null && diff.toV != null) {
  696. query.push(`from=${diff.fromV}`, `to=${diff.toV}`)
  697. }
  698. url += `?${query.join('&')}`
  699. return this.ide.$http
  700. .get(url)
  701. .then(response => {
  702. const { data } = response
  703. diff.loading = false
  704. const { text, highlights, binary } = this._parseDiff(data.diff)
  705. diff.binary = binary
  706. diff.text = text
  707. diff.highlights = highlights
  708. })
  709. .catch(function() {
  710. diff.loading = false
  711. diff.error = true
  712. })
  713. }
  714. labelCurrentVersion(labelComment) {
  715. return this._labelVersion(
  716. labelComment,
  717. this.$scope.history.selection.range.toV
  718. )
  719. }
  720. deleteLabel(label) {
  721. const url = `/project/${this.$scope.project_id}/labels/${label.id}`
  722. return this.ide
  723. .$http({
  724. url,
  725. method: 'DELETE',
  726. headers: {
  727. 'X-CSRF-Token': window.csrfToken
  728. }
  729. })
  730. .then(response => {
  731. return this._deleteLabelLocally(label)
  732. })
  733. }
  734. _deleteLabelLocally(labelToDelete) {
  735. for (let i = 0; i < this.$scope.history.updates.length; i++) {
  736. const update = this.$scope.history.updates[i]
  737. if (update.toV === labelToDelete.version) {
  738. update.labels = _.filter(
  739. update.labels,
  740. label => label.id !== labelToDelete.id
  741. )
  742. break
  743. }
  744. }
  745. this.$scope.history.labels = this._loadLabels(
  746. _.filter(
  747. this.$scope.history.labels,
  748. label => label.id !== labelToDelete.id
  749. ),
  750. this.$scope.history.updates[0].toV
  751. )
  752. this._handleHistoryUIStateChange()
  753. }
  754. _isLabelSelected(label) {
  755. if (label) {
  756. return (
  757. label.version <= this.$scope.history.selection.range.toV &&
  758. label.version >= this.$scope.history.selection.range.fromV
  759. )
  760. } else {
  761. return false
  762. }
  763. }
  764. _parseDiff(diff) {
  765. if (diff.binary) {
  766. return { binary: true }
  767. }
  768. let row = 0
  769. let column = 0
  770. const highlights = []
  771. let text = ''
  772. const iterable = diff || []
  773. for (let i = 0; i < iterable.length; i++) {
  774. var endColumn, endRow
  775. const entry = iterable[i]
  776. let content = entry.u || entry.i || entry.d
  777. if (!content) {
  778. content = ''
  779. }
  780. text += content
  781. const lines = content.split('\n')
  782. const startRow = row
  783. const startColumn = column
  784. if (lines.length > 1) {
  785. endRow = startRow + lines.length - 1
  786. endColumn = lines[lines.length - 1].length
  787. } else {
  788. endRow = startRow
  789. endColumn = startColumn + lines[0].length
  790. }
  791. row = endRow
  792. column = endColumn
  793. const range = {
  794. start: {
  795. row: startRow,
  796. column: startColumn
  797. },
  798. end: {
  799. row: endRow,
  800. column: endColumn
  801. }
  802. }
  803. if (entry.i != null || entry.d != null) {
  804. const user =
  805. entry.meta.users != null ? entry.meta.users[0] : undefined
  806. const name = displayNameForUser(user)
  807. const date = moment(entry.meta.end_ts).format('Do MMM YYYY, h:mm a')
  808. if (entry.i != null) {
  809. highlights.push({
  810. label: `Added by ${name} on ${date}`,
  811. highlight: range,
  812. hue: ColorManager.getHueForUserId(
  813. user != null ? user.id : undefined
  814. )
  815. })
  816. } else if (entry.d != null) {
  817. highlights.push({
  818. label: `Deleted by ${name} on ${date}`,
  819. strikeThrough: range,
  820. hue: ColorManager.getHueForUserId(
  821. user != null ? user.id : undefined
  822. )
  823. })
  824. }
  825. }
  826. }
  827. return { text, highlights }
  828. }
  829. _loadUpdates(updates) {
  830. if (updates == null) {
  831. updates = []
  832. }
  833. let previousUpdate = this.$scope.history.updates[
  834. this.$scope.history.updates.length - 1
  835. ]
  836. const dateTimeNow = new Date()
  837. const timestamp24hoursAgo = dateTimeNow.setDate(dateTimeNow.getDate() - 1)
  838. let cutOffIndex = null
  839. const iterable = updates || []
  840. for (let i = 0; i < iterable.length; i++) {
  841. const update = iterable[i]
  842. for (let user of Array.from(update.meta.users || [])) {
  843. if (user != null) {
  844. user.hue = ColorManager.getHueForUserId(user.id)
  845. }
  846. }
  847. if (
  848. previousUpdate == null ||
  849. !moment(previousUpdate.meta.end_ts).isSame(update.meta.end_ts, 'day')
  850. ) {
  851. update.meta.first_in_day = true
  852. }
  853. previousUpdate = update
  854. if (
  855. !this.$scope.history.userHasFullFeature &&
  856. update.meta.end_ts < timestamp24hoursAgo
  857. ) {
  858. cutOffIndex = i || 1 // Make sure that we show at least one entry (to allow labelling).
  859. this.$scope.history.freeHistoryLimitHit = true
  860. if (this.$scope.project.owner._id === this.$scope.user.id) {
  861. ga(
  862. 'send',
  863. 'event',
  864. 'subscription-funnel',
  865. 'editor-click-feature',
  866. 'history'
  867. )
  868. }
  869. break
  870. }
  871. }
  872. const firstLoad = this.$scope.history.updates.length === 0
  873. if (!this.$scope.history.userHasFullFeature && cutOffIndex != null) {
  874. updates = updates.slice(0, cutOffIndex)
  875. }
  876. this.$scope.history.updates = this.$scope.history.updates.concat(updates)
  877. if (firstLoad) {
  878. this._handleHistoryUIStateChange()
  879. }
  880. }
  881. _labelVersion(comment, version) {
  882. const url = `/project/${this.$scope.project_id}/labels`
  883. return this.ide.$http
  884. .post(url, {
  885. comment,
  886. version,
  887. _csrf: window.csrfToken
  888. })
  889. .then(response => {
  890. return this._addLabelLocally(response.data)
  891. })
  892. }
  893. _addLabelLocally(label) {
  894. const localUpdate = _.find(
  895. this.$scope.history.updates,
  896. update => update.toV === label.version
  897. )
  898. if (localUpdate != null) {
  899. localUpdate.labels = localUpdate.labels.concat(label)
  900. }
  901. this.$scope.history.labels = this._loadLabels(
  902. this.$scope.history.labels.concat(label),
  903. this.$scope.history.updates[0].toV
  904. )
  905. this._handleHistoryUIStateChange()
  906. }
  907. _updateContainsUserId(update, user_id) {
  908. for (let user of Array.from(update.meta.users)) {
  909. if ((user != null ? user.id : undefined) === user_id) {
  910. return true
  911. }
  912. }
  913. return false
  914. }
  915. }
  916. HistoryManager.initClass()
  917. return HistoryManager
  918. })())
  919. function __guard__(value, transform) {
  920. return typeof value !== 'undefined' && value !== null
  921. ? transform(value)
  922. : undefined
  923. }