EditorManager.js 15 KB

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