EditorManager.js 15 KB

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