EditorManager.js 15 KB

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