EditorManager.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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. // event dispatched by pdf preview
  93. window.addEventListener('flush-changes', () => {
  94. Document.flushAll()
  95. })
  96. window.addEventListener('blur', () => {
  97. // The browser may put the tab into sleep as it looses focus.
  98. // Flushing the documents should help with keeping the documents in
  99. // sync: we can use any new version of the doc that the server may
  100. // present us. There should be no need to insert local changes into
  101. // the doc history as the user comes back.
  102. sl_console.log('[EditorManager] forcing flush onblur')
  103. Document.flushAll()
  104. })
  105. this.$scope.$watch('editor.wantTrackChanges', value => {
  106. if (value == null) {
  107. return
  108. }
  109. return this._syncTrackChangesState(this.$scope.editor.sharejs_doc)
  110. })
  111. window.addEventListener('editor:open-doc', event => {
  112. const { doc, ...options } = event.detail
  113. this.openDoc(doc, options)
  114. })
  115. }
  116. showRichText() {
  117. return (
  118. this.localStorage(`editor.mode.${this.$scope.project_id}`) ===
  119. 'rich-text'
  120. )
  121. }
  122. autoOpenDoc() {
  123. const open_doc_id =
  124. this.ide.localStorage(`doc.open_id.${this.$scope.project_id}`) ||
  125. this.$scope.project.rootDoc_id
  126. if (open_doc_id == null) {
  127. return
  128. }
  129. const doc = this.ide.fileTreeManager.findEntityById(open_doc_id)
  130. if (doc == null) {
  131. return
  132. }
  133. return this.openDoc(doc)
  134. }
  135. openDocId(doc_id, options) {
  136. if (options == null) {
  137. options = {}
  138. }
  139. const doc = this.ide.fileTreeManager.findEntityById(doc_id)
  140. if (doc == null) {
  141. return
  142. }
  143. return this.openDoc(doc, options)
  144. }
  145. jumpToLine(options) {
  146. return this.$scope.$broadcast(
  147. 'editor:gotoLine',
  148. options.gotoLine,
  149. options.gotoColumn,
  150. options.syncToPdf
  151. )
  152. }
  153. openDoc(doc, options) {
  154. if (options == null) {
  155. options = {}
  156. }
  157. sl_console.log(`[openDoc] Opening ${doc.id}`)
  158. this.$scope.ui.view = 'editor'
  159. const done = isNewDoc => {
  160. this.$scope.$broadcast('doc:after-opened', { isNewDoc })
  161. if (options.gotoLine != null) {
  162. // allow Ace to display document before moving, delay until next tick
  163. // added delay to make this happen later that gotoStoredPosition in
  164. // CursorPositionManager
  165. return setTimeout(() => this.jumpToLine(options), 0)
  166. } else if (options.gotoOffset != null) {
  167. return setTimeout(() => {
  168. return this.$scope.$broadcast(
  169. 'editor:gotoOffset',
  170. options.gotoOffset
  171. )
  172. }, 0)
  173. }
  174. }
  175. // If we already have the document open we can return at this point.
  176. // Note: only use forceReopen:true to override this when the document is
  177. // is out of sync and needs to be reloaded from the server.
  178. if (doc.id === this.$scope.editor.open_doc_id && !options.forceReopen) {
  179. // automatically update the file tree whenever the file is opened
  180. this.ide.fileTreeManager.selectEntity(doc)
  181. this.$scope.$apply(() => {
  182. return done(false)
  183. })
  184. return
  185. }
  186. // We're now either opening a new document or reloading a broken one.
  187. this.$scope.editor.open_doc_id = doc.id
  188. this.$scope.editor.open_doc_name = doc.name
  189. this.ide.localStorage(`doc.open_id.${this.$scope.project_id}`, doc.id)
  190. this.ide.fileTreeManager.selectEntity(doc)
  191. this.$scope.editor.opening = true
  192. return this._openNewDocument(doc, (error, sharejs_doc) => {
  193. if (error && error.message === 'another document was loaded') {
  194. sl_console.log(
  195. `[openDoc] another document was loaded while ${doc.id} was loading`
  196. )
  197. return
  198. }
  199. if (error != null) {
  200. this.ide.showGenericMessageModal(
  201. 'Error opening document',
  202. 'Sorry, something went wrong opening this document. Please try again.'
  203. )
  204. return
  205. }
  206. this._syncTrackChangesState(sharejs_doc)
  207. this.$scope.$broadcast('doc:opened')
  208. return this.$scope.$apply(() => {
  209. this.$scope.editor.opening = false
  210. this.$scope.editor.sharejs_doc = sharejs_doc
  211. return done(true)
  212. })
  213. })
  214. }
  215. _openNewDocument(doc, callback) {
  216. // Leave the current document
  217. // - when we are opening a different new one, to avoid race conditions
  218. // between leaving and joining the same document
  219. // - when the current one has pending ops that need flushing, to avoid
  220. // race conditions from cleanup
  221. const current_sharejs_doc = this.$scope.editor.sharejs_doc
  222. const currentDocId = current_sharejs_doc && current_sharejs_doc.doc_id
  223. const hasBufferedOps =
  224. current_sharejs_doc && current_sharejs_doc.hasBufferedOps()
  225. const changingDoc = current_sharejs_doc && currentDocId !== doc.id
  226. if (changingDoc || hasBufferedOps) {
  227. sl_console.log('[_openNewDocument] Leaving existing open doc...')
  228. // Do not trigger any UI changes from remote operations
  229. this._unbindFromDocumentEvents(current_sharejs_doc)
  230. // Keep listening for out-of-sync and similar errors.
  231. this._attachErrorHandlerToDocument(doc, current_sharejs_doc)
  232. // Teardown the Document -> ShareJsDoc -> sharejs doc
  233. // By the time this completes, the Document instance is no longer
  234. // registered in Document.openDocs and _doOpenNewDocument can start
  235. // from scratch -- read: no corrupted internal state.
  236. const editorOpenDocEpoch = ++this.editorOpenDocEpoch
  237. current_sharejs_doc.leaveAndCleanUp(error => {
  238. if (error) {
  239. sl_console.log(
  240. `[_openNewDocument] error leaving doc ${currentDocId}`,
  241. error
  242. )
  243. return callback(error)
  244. }
  245. if (this.editorOpenDocEpoch !== editorOpenDocEpoch) {
  246. sl_console.log(
  247. `[openNewDocument] editorOpenDocEpoch mismatch ${this.editorOpenDocEpoch} vs ${editorOpenDocEpoch}`
  248. )
  249. return callback(new Error('another document was loaded'))
  250. }
  251. this._doOpenNewDocument(doc, callback)
  252. })
  253. } else {
  254. this._doOpenNewDocument(doc, callback)
  255. }
  256. }
  257. _doOpenNewDocument(doc, callback) {
  258. if (callback == null) {
  259. callback = function (error, sharejs_doc) {}
  260. }
  261. sl_console.log('[_doOpenNewDocument] Opening...')
  262. const new_sharejs_doc = Document.getDocument(this.ide, doc.id)
  263. const editorOpenDocEpoch = ++this.editorOpenDocEpoch
  264. return new_sharejs_doc.join(error => {
  265. if (error != null) {
  266. sl_console.log(
  267. `[_doOpenNewDocument] error joining doc ${doc.id}`,
  268. error
  269. )
  270. return callback(error)
  271. }
  272. if (this.editorOpenDocEpoch !== editorOpenDocEpoch) {
  273. sl_console.log(
  274. `[openNewDocument] editorOpenDocEpoch mismatch ${this.editorOpenDocEpoch} vs ${editorOpenDocEpoch}`
  275. )
  276. new_sharejs_doc.leaveAndCleanUp()
  277. return callback(new Error('another document was loaded'))
  278. }
  279. this._bindToDocumentEvents(doc, new_sharejs_doc)
  280. return callback(null, new_sharejs_doc)
  281. })
  282. }
  283. _attachErrorHandlerToDocument(doc, sharejs_doc) {
  284. sharejs_doc.on('error', (error, meta, editorContent) => {
  285. let message
  286. if ((error != null ? error.message : undefined) != null) {
  287. ;({ message } = error)
  288. } else if (typeof error === 'string') {
  289. message = error
  290. } else {
  291. message = ''
  292. }
  293. if (/maxDocLength/.test(message)) {
  294. this.ide.showGenericMessageModal(
  295. 'Document Too Long',
  296. 'Sorry, this file is too long to be edited manually. Please upload it directly.'
  297. )
  298. } else if (/too many comments or tracked changes/.test(message)) {
  299. this.ide.showGenericMessageModal(
  300. 'Too many comments or tracked changes',
  301. 'Sorry, this file has too many comments or tracked changes. Please try accepting or rejecting some existing changes, or resolving and deleting some comments.'
  302. )
  303. } else {
  304. // Do not allow this doc to open another error modal.
  305. sharejs_doc.off('error')
  306. // Preserve the sharejs contents before the teardown.
  307. editorContent =
  308. typeof editorContent === 'string'
  309. ? editorContent
  310. : sharejs_doc.doc._doc.snapshot
  311. // Tear down the ShareJsDoc.
  312. if (sharejs_doc.doc) sharejs_doc.doc.clearInflightAndPendingOps()
  313. // Do not re-join after re-connecting.
  314. sharejs_doc.leaveAndCleanUp()
  315. this.ide.connectionManager.disconnect({ permanent: true })
  316. this.ide.reportError(error, meta)
  317. // Tell the user about the error state.
  318. this.$scope.editor.error_state = true
  319. this.ide.showOutOfSyncModal(
  320. 'Out of sync',
  321. "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>",
  322. editorContent
  323. )
  324. // Do not forceReopen the document.
  325. return
  326. }
  327. const removeHandler = this.$scope.$on('project:joined', () => {
  328. this.openDoc(doc, { forceReopen: true })
  329. removeHandler()
  330. })
  331. })
  332. }
  333. _bindToDocumentEvents(doc, sharejs_doc) {
  334. this._attachErrorHandlerToDocument(doc, sharejs_doc)
  335. return sharejs_doc.on('externalUpdate', update => {
  336. if (this._ignoreExternalUpdates) {
  337. return
  338. }
  339. if (
  340. _.property(['meta', 'type'])(update) === 'external' &&
  341. _.property(['meta', 'source'])(update) === 'git-bridge'
  342. ) {
  343. return
  344. }
  345. return this.ide.showGenericMessageModal(
  346. 'Document Updated Externally',
  347. '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.'
  348. )
  349. })
  350. }
  351. _unbindFromDocumentEvents(document) {
  352. return document.off()
  353. }
  354. getCurrentDocValue() {
  355. return this.$scope.editor.sharejs_doc != null
  356. ? this.$scope.editor.sharejs_doc.getSnapshot()
  357. : undefined
  358. }
  359. getCurrentDocId() {
  360. return this.$scope.editor.open_doc_id
  361. }
  362. startIgnoringExternalUpdates() {
  363. return (this._ignoreExternalUpdates = true)
  364. }
  365. stopIgnoringExternalUpdates() {
  366. return (this._ignoreExternalUpdates = false)
  367. }
  368. _syncTrackChangesState(doc) {
  369. let tryToggle
  370. if (doc == null) {
  371. return
  372. }
  373. if (this._syncTimeout != null) {
  374. clearTimeout(this._syncTimeout)
  375. this._syncTimeout = null
  376. }
  377. const want = this.$scope.editor.wantTrackChanges
  378. const have = doc.getTrackingChanges()
  379. if (want === have) {
  380. this.$scope.editor.trackChanges = want
  381. return
  382. }
  383. return (tryToggle = () => {
  384. const saved = doc.getInflightOp() == null && doc.getPendingOp() == null
  385. if (saved) {
  386. doc.setTrackingChanges(want)
  387. return this.$scope.$apply(() => {
  388. return (this.$scope.editor.trackChanges = want)
  389. })
  390. } else {
  391. return (this._syncTimeout = setTimeout(tryToggle, 100))
  392. }
  393. })()
  394. }
  395. }
  396. EditorManager.initClass()
  397. return EditorManager
  398. })()