EditorManager.js 15 KB

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