EditorManager.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. import _ from 'lodash'
  2. /* eslint-disable
  3. camelcase,
  4. node/handle-callback-err,
  5. max-len,
  6. no-return-assign,
  7. */
  8. // TODO: This file was created by bulk-decaffeinate.
  9. // Fix any style issues and re-enable lint.
  10. /*
  11. * decaffeinate suggestions:
  12. * DS102: Remove unnecessary code created because of implicit returns
  13. * DS206: Consider reworking classes to avoid initClass
  14. * DS207: Consider shorter variations of null checks
  15. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  16. */
  17. import Document from './Document'
  18. import './components/spellMenu'
  19. import './directives/aceEditor'
  20. import './directives/toggleSwitch'
  21. import './controllers/SavingNotificationController'
  22. import '../../features/symbol-palette/controllers/symbol-palette-controller'
  23. let EditorManager
  24. export default EditorManager = (function () {
  25. EditorManager = class EditorManager {
  26. static initClass() {
  27. this.prototype._syncTimeout = null
  28. }
  29. constructor(ide, $scope, localStorage, eventTracking) {
  30. this.ide = ide
  31. this.editorOpenDocEpoch = 0 // track pending document loads
  32. this.$scope = $scope
  33. this.localStorage = localStorage
  34. this.$scope.editor = {
  35. sharejs_doc: null,
  36. open_doc_id: null,
  37. open_doc_name: null,
  38. opening: true,
  39. trackChanges: false,
  40. wantTrackChanges: false,
  41. showRichText: this.showRichText(),
  42. showSymbolPalette: false,
  43. toggleSymbolPalette: () => {
  44. const newValue = !this.$scope.editor.showSymbolPalette
  45. this.$scope.editor.showSymbolPalette = newValue
  46. ide.$scope.$emit('symbol-palette-toggled', newValue)
  47. eventTracking.sendMB(
  48. newValue ? 'symbol-palette-show' : 'symbol-palette-hide'
  49. )
  50. },
  51. insertSymbol: symbol => {
  52. ide.$scope.$emit('editor:replace-selection', symbol.command)
  53. eventTracking.sendMB('symbol-palette-insert')
  54. },
  55. }
  56. this.$scope.$on('entity:selected', (event, entity) => {
  57. if (this.$scope.ui.view !== 'history' && entity.type === 'doc') {
  58. return this.openDoc(entity)
  59. }
  60. })
  61. this.$scope.$on('entity:no-selection', () => {
  62. this.$scope.$apply(() => {
  63. this.$scope.ui.view = null
  64. })
  65. })
  66. this.$scope.$on('entity:deleted', (event, entity) => {
  67. if (this.$scope.editor.open_doc_id === entity.id) {
  68. if (!this.$scope.project.rootDoc_id) {
  69. this.$scope.ui.view = null
  70. return
  71. }
  72. const doc = this.ide.fileTreeManager.findEntityById(
  73. this.$scope.project.rootDoc_id
  74. )
  75. if (doc == null) {
  76. this.$scope.ui.view = null
  77. return
  78. }
  79. return this.openDoc(doc)
  80. }
  81. })
  82. let initialized = false
  83. this.$scope.$on('file-tree:initialized', () => {
  84. if (!initialized) {
  85. initialized = true
  86. return this.autoOpenDoc()
  87. }
  88. })
  89. this.$scope.$on('flush-changes', () => {
  90. return Document.flushAll()
  91. })
  92. window.addEventListener('blur', () => {
  93. // The browser may put the tab into sleep as it looses focus.
  94. // Flushing the documents should help with keeping the documents in
  95. // sync: we can use any new version of the doc that the server may
  96. // present us. There should be no need to insert local changes into
  97. // the doc history as the user comes back.
  98. sl_console.log('[EditorManager] forcing flush onblur')
  99. Document.flushAll()
  100. })
  101. this.$scope.$watch('editor.wantTrackChanges', value => {
  102. if (value == null) {
  103. return
  104. }
  105. return this._syncTrackChangesState(this.$scope.editor.sharejs_doc)
  106. })
  107. }
  108. showRichText() {
  109. return (
  110. this.localStorage(`editor.mode.${this.$scope.project_id}`) ===
  111. 'rich-text'
  112. )
  113. }
  114. autoOpenDoc() {
  115. const open_doc_id =
  116. this.ide.localStorage(`doc.open_id.${this.$scope.project_id}`) ||
  117. this.$scope.project.rootDoc_id
  118. if (open_doc_id == null) {
  119. return
  120. }
  121. const doc = this.ide.fileTreeManager.findEntityById(open_doc_id)
  122. if (doc == null) {
  123. return
  124. }
  125. return this.openDoc(doc)
  126. }
  127. openDocId(doc_id, options) {
  128. if (options == null) {
  129. options = {}
  130. }
  131. const doc = this.ide.fileTreeManager.findEntityById(doc_id)
  132. if (doc == null) {
  133. return
  134. }
  135. return this.openDoc(doc, options)
  136. }
  137. jumpToLine(options) {
  138. return this.$scope.$broadcast(
  139. 'editor:gotoLine',
  140. options.gotoLine,
  141. options.gotoColumn,
  142. options.syncToPdf
  143. )
  144. }
  145. openDoc(doc, options) {
  146. if (options == null) {
  147. options = {}
  148. }
  149. sl_console.log(`[openDoc] Opening ${doc.id}`)
  150. this.$scope.ui.view = 'editor'
  151. const done = isNewDoc => {
  152. this.$scope.$broadcast('doc:after-opened', { isNewDoc })
  153. if (options.gotoLine != null) {
  154. // allow Ace to display document before moving, delay until next tick
  155. // added delay to make this happen later that gotoStoredPosition in
  156. // CursorPositionManager
  157. return setTimeout(() => this.jumpToLine(options), 0)
  158. } else if (options.gotoOffset != null) {
  159. return setTimeout(() => {
  160. return this.$scope.$broadcast(
  161. 'editor:gotoOffset',
  162. options.gotoOffset
  163. )
  164. }, 0)
  165. }
  166. }
  167. // If we already have the document open we can return at this point.
  168. // Note: only use forceReopen:true to override this when the document is
  169. // is out of sync and needs to be reloaded from the server.
  170. if (doc.id === this.$scope.editor.open_doc_id && !options.forceReopen) {
  171. // automatically update the file tree whenever the file is opened
  172. this.ide.fileTreeManager.selectEntity(doc)
  173. this.$scope.$apply(() => {
  174. return done(false)
  175. })
  176. return
  177. }
  178. // We're now either opening a new document or reloading a broken one.
  179. this.$scope.editor.open_doc_id = doc.id
  180. this.$scope.editor.open_doc_name = doc.name
  181. this.ide.localStorage(`doc.open_id.${this.$scope.project_id}`, doc.id)
  182. this.ide.fileTreeManager.selectEntity(doc)
  183. this.$scope.editor.opening = true
  184. return this._openNewDocument(doc, (error, sharejs_doc) => {
  185. if (error && error.message === 'another document was loaded') {
  186. sl_console.log(
  187. `[openDoc] another document was loaded while ${doc.id} was loading`
  188. )
  189. return
  190. }
  191. if (error != null) {
  192. this.ide.showGenericMessageModal(
  193. 'Error opening document',
  194. 'Sorry, something went wrong opening this document. Please try again.'
  195. )
  196. return
  197. }
  198. this._syncTrackChangesState(sharejs_doc)
  199. this.$scope.$broadcast('doc:opened')
  200. return this.$scope.$apply(() => {
  201. this.$scope.editor.opening = false
  202. this.$scope.editor.sharejs_doc = sharejs_doc
  203. return done(true)
  204. })
  205. })
  206. }
  207. _openNewDocument(doc, callback) {
  208. // Leave the current document
  209. // - when we are opening a different new one, to avoid race conditions
  210. // between leaving and joining the same document
  211. // - when the current one has pending ops that need flushing, to avoid
  212. // race conditions from cleanup
  213. const current_sharejs_doc = this.$scope.editor.sharejs_doc
  214. const currentDocId = current_sharejs_doc && current_sharejs_doc.doc_id
  215. const hasBufferedOps =
  216. current_sharejs_doc && current_sharejs_doc.hasBufferedOps()
  217. const changingDoc = current_sharejs_doc && currentDocId !== doc.id
  218. if (changingDoc || hasBufferedOps) {
  219. sl_console.log('[_openNewDocument] Leaving existing open doc...')
  220. // Do not trigger any UI changes from remote operations
  221. this._unbindFromDocumentEvents(current_sharejs_doc)
  222. // Keep listening for out-of-sync and similar errors.
  223. this._attachErrorHandlerToDocument(doc, current_sharejs_doc)
  224. // Teardown the Document -> ShareJsDoc -> sharejs doc
  225. // By the time this completes, the Document instance is no longer
  226. // registered in Document.openDocs and _doOpenNewDocument can start
  227. // from scratch -- read: no corrupted internal state.
  228. const editorOpenDocEpoch = ++this.editorOpenDocEpoch
  229. current_sharejs_doc.leaveAndCleanUp(error => {
  230. if (error) {
  231. sl_console.log(
  232. `[_openNewDocument] error leaving doc ${currentDocId}`,
  233. error
  234. )
  235. return callback(error)
  236. }
  237. if (this.editorOpenDocEpoch !== editorOpenDocEpoch) {
  238. sl_console.log(
  239. `[openNewDocument] editorOpenDocEpoch mismatch ${this.editorOpenDocEpoch} vs ${editorOpenDocEpoch}`
  240. )
  241. return callback(new Error('another document was loaded'))
  242. }
  243. this._doOpenNewDocument(doc, callback)
  244. })
  245. } else {
  246. this._doOpenNewDocument(doc, callback)
  247. }
  248. }
  249. _doOpenNewDocument(doc, callback) {
  250. if (callback == null) {
  251. callback = function (error, sharejs_doc) {}
  252. }
  253. sl_console.log('[_doOpenNewDocument] Opening...')
  254. const new_sharejs_doc = Document.getDocument(this.ide, doc.id)
  255. const editorOpenDocEpoch = ++this.editorOpenDocEpoch
  256. return new_sharejs_doc.join(error => {
  257. if (error != null) {
  258. sl_console.log(
  259. `[_doOpenNewDocument] error joining doc ${doc.id}`,
  260. error
  261. )
  262. return callback(error)
  263. }
  264. if (this.editorOpenDocEpoch !== editorOpenDocEpoch) {
  265. sl_console.log(
  266. `[openNewDocument] editorOpenDocEpoch mismatch ${this.editorOpenDocEpoch} vs ${editorOpenDocEpoch}`
  267. )
  268. new_sharejs_doc.leaveAndCleanUp()
  269. return callback(new Error('another document was loaded'))
  270. }
  271. this._bindToDocumentEvents(doc, new_sharejs_doc)
  272. return callback(null, new_sharejs_doc)
  273. })
  274. }
  275. _attachErrorHandlerToDocument(doc, sharejs_doc) {
  276. sharejs_doc.on('error', (error, meta, editorContent) => {
  277. let message
  278. if ((error != null ? error.message : undefined) != null) {
  279. ;({ message } = error)
  280. } else if (typeof error === 'string') {
  281. message = error
  282. } else {
  283. message = ''
  284. }
  285. if (/maxDocLength/.test(message)) {
  286. this.ide.showGenericMessageModal(
  287. 'Document Too Long',
  288. 'Sorry, this file is too long to be edited manually. Please upload it directly.'
  289. )
  290. } else if (/too many comments or tracked changes/.test(message)) {
  291. this.ide.showGenericMessageModal(
  292. 'Too many comments or tracked changes',
  293. 'Sorry, this file has too many comments or tracked changes. Please try accepting or rejecting some existing changes, or resolving and deleting some comments.'
  294. )
  295. } else {
  296. // Do not allow this doc to open another error modal.
  297. sharejs_doc.off('error')
  298. // Preserve the sharejs contents before the teardown.
  299. editorContent =
  300. typeof editorContent === 'string'
  301. ? editorContent
  302. : sharejs_doc.doc._doc.snapshot
  303. // Tear down the ShareJsDoc.
  304. if (sharejs_doc.doc) sharejs_doc.doc.clearInflightAndPendingOps()
  305. // Do not re-join after re-connecting.
  306. sharejs_doc.leaveAndCleanUp()
  307. this.ide.connectionManager.disconnect({ permanent: true })
  308. this.ide.reportError(error, meta)
  309. // Tell the user about the error state.
  310. this.$scope.editor.error_state = true
  311. this.ide.showOutOfSyncModal(
  312. 'Out of sync',
  313. "Sorry, this file has gone out of sync and we need to do a full refresh. <br> <a target='_blank' rel='noopener noreferrer' href='/learn/Kb/Editor_out_of_sync_problems'>Please see this help guide for more information</a>",
  314. editorContent
  315. )
  316. // Do not forceReopen the document.
  317. return
  318. }
  319. const removeHandler = this.$scope.$on('project:joined', () => {
  320. this.openDoc(doc, { forceReopen: true })
  321. removeHandler()
  322. })
  323. })
  324. }
  325. _bindToDocumentEvents(doc, sharejs_doc) {
  326. this._attachErrorHandlerToDocument(doc, sharejs_doc)
  327. return sharejs_doc.on('externalUpdate', update => {
  328. if (this._ignoreExternalUpdates) {
  329. return
  330. }
  331. if (
  332. _.property(['meta', 'type'])(update) === 'external' &&
  333. _.property(['meta', 'source'])(update) === 'git-bridge'
  334. ) {
  335. return
  336. }
  337. return this.ide.showGenericMessageModal(
  338. 'Document Updated Externally',
  339. 'This document was just updated externally. Any recent changes you have made may have been overwritten. To see previous versions please look in the history.'
  340. )
  341. })
  342. }
  343. _unbindFromDocumentEvents(document) {
  344. return document.off()
  345. }
  346. getCurrentDocValue() {
  347. return this.$scope.editor.sharejs_doc != null
  348. ? this.$scope.editor.sharejs_doc.getSnapshot()
  349. : undefined
  350. }
  351. getCurrentDocId() {
  352. return this.$scope.editor.open_doc_id
  353. }
  354. startIgnoringExternalUpdates() {
  355. return (this._ignoreExternalUpdates = true)
  356. }
  357. stopIgnoringExternalUpdates() {
  358. return (this._ignoreExternalUpdates = false)
  359. }
  360. _syncTrackChangesState(doc) {
  361. let tryToggle
  362. if (doc == null) {
  363. return
  364. }
  365. if (this._syncTimeout != null) {
  366. clearTimeout(this._syncTimeout)
  367. this._syncTimeout = null
  368. }
  369. const want = this.$scope.editor.wantTrackChanges
  370. const have = doc.getTrackingChanges()
  371. if (want === have) {
  372. this.$scope.editor.trackChanges = want
  373. return
  374. }
  375. return (tryToggle = () => {
  376. const saved = doc.getInflightOp() == null && doc.getPendingOp() == null
  377. if (saved) {
  378. doc.setTrackingChanges(want)
  379. return this.$scope.$apply(() => {
  380. return (this.$scope.editor.trackChanges = want)
  381. })
  382. } else {
  383. return (this._syncTimeout = setTimeout(tryToggle, 100))
  384. }
  385. })()
  386. }
  387. }
  388. EditorManager.initClass()
  389. return EditorManager
  390. })()