EditorManager.js 16 KB

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