EditorManager.js 15 KB

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