EditorManager.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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 './directives/formattingButtons'
  19. import './directives/toggleSwitch'
  20. import './controllers/SavingNotificationController'
  21. import './controllers/CompileButton'
  22. import './controllers/SwitchToPDFButton'
  23. import '../metadata/services/metadata'
  24. import { debugConsole } from '@/utils/debugging'
  25. let EditorManager
  26. export default EditorManager = (function () {
  27. EditorManager = class EditorManager {
  28. static initClass() {
  29. this.prototype._syncTimeout = null
  30. }
  31. constructor(ide, $scope, localStorage, eventTracking) {
  32. this.ide = ide
  33. this.editorOpenDocEpoch = 0 // track pending document loads
  34. this.$scope = $scope
  35. this.localStorage = localStorage
  36. this.$scope.editor = {
  37. sharejs_doc: null,
  38. open_doc_id: null,
  39. open_doc_name: null,
  40. opening: true,
  41. trackChanges: false,
  42. wantTrackChanges: false,
  43. docTooLongErrorShown: false,
  44. showVisual: this.showVisual(),
  45. showSymbolPalette: false,
  46. toggleSymbolPalette: () => {
  47. const newValue = !this.$scope.editor.showSymbolPalette
  48. this.$scope.editor.showSymbolPalette = newValue
  49. ide.$scope.$emit('south-pane-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. debugConsole.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. window.addEventListener('editor:open-file', event => {
  123. const { name, ...options } = event.detail
  124. for (const extension of ['', '.tex']) {
  125. const path = `${name}${extension}`
  126. const doc = ide.fileTreeManager.findEntityByPath(path)
  127. if (doc) {
  128. this.openDoc(doc, options)
  129. break
  130. }
  131. }
  132. })
  133. }
  134. getEditorType() {
  135. if (!this.$scope.editor.sharejs_doc) {
  136. return null
  137. }
  138. let editorType = this.$scope.editor.sharejs_doc.editorType()
  139. if (editorType === 'cm6' && this.$scope.editor.showVisual) {
  140. editorType = 'cm6-rich-text'
  141. }
  142. return editorType
  143. }
  144. showVisual() {
  145. return (
  146. this.localStorage(`editor.mode.${this.$scope.project_id}`) ===
  147. 'rich-text'
  148. )
  149. }
  150. autoOpenDoc() {
  151. const open_doc_id =
  152. this.ide.localStorage(`doc.open_id.${this.$scope.project_id}`) ||
  153. this.$scope.project.rootDoc_id
  154. if (open_doc_id == null) {
  155. return
  156. }
  157. const doc = this.ide.fileTreeManager.findEntityById(open_doc_id)
  158. if (doc == null) {
  159. return
  160. }
  161. return this.openDoc(doc)
  162. }
  163. openDocId(doc_id, options) {
  164. if (options == null) {
  165. options = {}
  166. }
  167. const doc = this.ide.fileTreeManager.findEntityById(doc_id)
  168. if (doc == null) {
  169. return
  170. }
  171. return this.openDoc(doc, options)
  172. }
  173. jumpToLine(options) {
  174. return this.$scope.$broadcast(
  175. 'editor:gotoLine',
  176. options.gotoLine,
  177. options.gotoColumn,
  178. options.syncToPdf
  179. )
  180. }
  181. openDoc(doc, options) {
  182. if (options == null) {
  183. options = {}
  184. }
  185. debugConsole.log(`[openDoc] Opening ${doc.id}`)
  186. if (this.$scope.ui.view === 'editor') {
  187. // store position of previous doc before switching docs
  188. this.$scope.$broadcast('store-doc-position')
  189. }
  190. this.$scope.ui.view = 'editor'
  191. const done = isNewDoc => {
  192. const eventName = 'doc:after-opened'
  193. this.$scope.$broadcast(eventName, { isNewDoc })
  194. window.dispatchEvent(new CustomEvent(eventName, { detail: isNewDoc }))
  195. if (options.gotoLine != null) {
  196. // allow Ace to display document before moving, delay until next tick
  197. // added delay to make this happen later that gotoStoredPosition in
  198. // CursorPositionManager
  199. setTimeout(() => this.jumpToLine(options))
  200. // when opening a doc in CM6, jump to the line again after a stored scroll position has been restored
  201. if (isNewDoc) {
  202. window.addEventListener(
  203. 'editor:scroll-position-restored',
  204. () => this.jumpToLine(options),
  205. { once: true }
  206. )
  207. }
  208. } else if (options.gotoOffset != null) {
  209. setTimeout(() => {
  210. this.$scope.$broadcast('editor:gotoOffset', options.gotoOffset)
  211. })
  212. }
  213. }
  214. // If we already have the document open we can return at this point.
  215. // Note: only use forceReopen:true to override this when the document is
  216. // is out of sync and needs to be reloaded from the server.
  217. if (doc.id === this.$scope.editor.open_doc_id && !options.forceReopen) {
  218. // automatically update the file tree whenever the file is opened
  219. this.ide.fileTreeManager.selectEntity(doc)
  220. this.$scope.$broadcast('file-tree.reselectDoc', doc.id)
  221. this.$scope.$apply(() => {
  222. return done(false)
  223. })
  224. return
  225. }
  226. this.$scope.$applyAsync(() => {
  227. // We're now either opening a new document or reloading a broken one.
  228. this.$scope.editor.open_doc_id = doc.id
  229. this.$scope.editor.open_doc_name = doc.name
  230. this.ide.localStorage(`doc.open_id.${this.$scope.project_id}`, doc.id)
  231. this.ide.fileTreeManager.selectEntity(doc)
  232. this.$scope.editor.opening = true
  233. return this._openNewDocument(doc, (error, sharejs_doc) => {
  234. if (error && error.message === 'another document was loaded') {
  235. debugConsole.log(
  236. `[openDoc] another document was loaded while ${doc.id} was loading`
  237. )
  238. return
  239. }
  240. if (error != null) {
  241. this.ide.showGenericMessageModal(
  242. 'Error opening document',
  243. 'Sorry, something went wrong opening this document. Please try again.'
  244. )
  245. return
  246. }
  247. this._syncTrackChangesState(sharejs_doc)
  248. this.$scope.$broadcast('doc:opened')
  249. return this.$scope.$applyAsync(() => {
  250. this.$scope.editor.opening = false
  251. this.$scope.editor.sharejs_doc = sharejs_doc
  252. return done(true)
  253. })
  254. })
  255. })
  256. }
  257. _openNewDocument(doc, callback) {
  258. // Leave the current document
  259. // - when we are opening a different new one, to avoid race conditions
  260. // between leaving and joining the same document
  261. // - when the current one has pending ops that need flushing, to avoid
  262. // race conditions from cleanup
  263. const current_sharejs_doc = this.$scope.editor.sharejs_doc
  264. const currentDocId = current_sharejs_doc && current_sharejs_doc.doc_id
  265. const hasBufferedOps =
  266. current_sharejs_doc && current_sharejs_doc.hasBufferedOps()
  267. const changingDoc = current_sharejs_doc && currentDocId !== doc.id
  268. if (changingDoc || hasBufferedOps) {
  269. debugConsole.log('[_openNewDocument] Leaving existing open doc...')
  270. // Do not trigger any UI changes from remote operations
  271. this._unbindFromDocumentEvents(current_sharejs_doc)
  272. // Keep listening for out-of-sync and similar errors.
  273. this._attachErrorHandlerToDocument(doc, current_sharejs_doc)
  274. // Teardown the Document -> ShareJsDoc -> sharejs doc
  275. // By the time this completes, the Document instance is no longer
  276. // registered in Document.openDocs and _doOpenNewDocument can start
  277. // from scratch -- read: no corrupted internal state.
  278. const editorOpenDocEpoch = ++this.editorOpenDocEpoch
  279. current_sharejs_doc.leaveAndCleanUp(error => {
  280. if (error) {
  281. debugConsole.log(
  282. `[_openNewDocument] error leaving doc ${currentDocId}`,
  283. error
  284. )
  285. return callback(error)
  286. }
  287. if (this.editorOpenDocEpoch !== editorOpenDocEpoch) {
  288. debugConsole.log(
  289. `[openNewDocument] editorOpenDocEpoch mismatch ${this.editorOpenDocEpoch} vs ${editorOpenDocEpoch}`
  290. )
  291. return callback(new Error('another document was loaded'))
  292. }
  293. this._doOpenNewDocument(doc, callback)
  294. })
  295. } else {
  296. this._doOpenNewDocument(doc, callback)
  297. }
  298. }
  299. _doOpenNewDocument(doc, callback) {
  300. if (callback == null) {
  301. callback = function () {}
  302. }
  303. debugConsole.log('[_doOpenNewDocument] Opening...')
  304. const new_sharejs_doc = Document.getDocument(this.ide, doc.id)
  305. const editorOpenDocEpoch = ++this.editorOpenDocEpoch
  306. return new_sharejs_doc.join(error => {
  307. if (error != null) {
  308. debugConsole.log(
  309. `[_doOpenNewDocument] error joining doc ${doc.id}`,
  310. error
  311. )
  312. return callback(error)
  313. }
  314. if (this.editorOpenDocEpoch !== editorOpenDocEpoch) {
  315. debugConsole.log(
  316. `[openNewDocument] editorOpenDocEpoch mismatch ${this.editorOpenDocEpoch} vs ${editorOpenDocEpoch}`
  317. )
  318. new_sharejs_doc.leaveAndCleanUp()
  319. return callback(new Error('another document was loaded'))
  320. }
  321. this._bindToDocumentEvents(doc, new_sharejs_doc)
  322. return callback(null, new_sharejs_doc)
  323. })
  324. }
  325. _attachErrorHandlerToDocument(doc, sharejs_doc) {
  326. sharejs_doc.on('error', (error, meta, editorContent) => {
  327. let message
  328. if ((error != null ? error.message : undefined) != null) {
  329. ;({ message } = error)
  330. } else if (typeof error === 'string') {
  331. message = error
  332. } else {
  333. message = ''
  334. }
  335. if (/maxDocLength/.test(message)) {
  336. this.$scope.docTooLongErrorShown = true
  337. this.openDoc(doc, { forceReopen: true })
  338. const genericMessageModal = this.ide.showGenericMessageModal(
  339. 'Document Too Long',
  340. 'Sorry, this file is too long to be edited manually. Please upload it directly.'
  341. )
  342. genericMessageModal.result.finally(() => {
  343. this.$scope.docTooLongErrorShown = false
  344. })
  345. } else if (/too many comments or tracked changes/.test(message)) {
  346. this.ide.showGenericMessageModal(
  347. 'Too many comments or tracked changes',
  348. 'Sorry, this file has too many comments or tracked changes. Please try accepting or rejecting some existing changes, or resolving and deleting some comments.'
  349. )
  350. } else if (!this.$scope.docTooLongErrorShown) {
  351. // Do not allow this doc to open another error modal.
  352. sharejs_doc.off('error')
  353. // Preserve the sharejs contents before the teardown.
  354. editorContent =
  355. typeof editorContent === 'string'
  356. ? editorContent
  357. : sharejs_doc.doc._doc.snapshot
  358. // Tear down the ShareJsDoc.
  359. if (sharejs_doc.doc) sharejs_doc.doc.clearInflightAndPendingOps()
  360. // Do not re-join after re-connecting.
  361. sharejs_doc.leaveAndCleanUp()
  362. this.ide.connectionManager.disconnect({ permanent: true })
  363. this.ide.reportError(error, meta)
  364. // Tell the user about the error state.
  365. this.$scope.editor.error_state = true
  366. this.ide.showOutOfSyncModal(
  367. 'Out of sync',
  368. "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>",
  369. editorContent
  370. )
  371. // Do not forceReopen the document.
  372. return
  373. }
  374. const removeHandler = this.$scope.$on('project:joined', () => {
  375. this.openDoc(doc, { forceReopen: true })
  376. removeHandler()
  377. })
  378. })
  379. }
  380. _bindToDocumentEvents(doc, sharejs_doc) {
  381. this._attachErrorHandlerToDocument(doc, sharejs_doc)
  382. return sharejs_doc.on('externalUpdate', update => {
  383. if (this._ignoreExternalUpdates) {
  384. return
  385. }
  386. if (
  387. _.property(['meta', 'type'])(update) === 'external' &&
  388. _.property(['meta', 'source'])(update) === 'git-bridge'
  389. ) {
  390. return
  391. }
  392. return this.ide.showGenericMessageModal(
  393. 'Document Updated Externally',
  394. '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.'
  395. )
  396. })
  397. }
  398. _unbindFromDocumentEvents(document) {
  399. return document.off()
  400. }
  401. getCurrentDocValue() {
  402. return this.$scope.editor.sharejs_doc != null
  403. ? this.$scope.editor.sharejs_doc.getSnapshot()
  404. : undefined
  405. }
  406. getCurrentDocId() {
  407. return this.$scope.editor.open_doc_id
  408. }
  409. startIgnoringExternalUpdates() {
  410. return (this._ignoreExternalUpdates = true)
  411. }
  412. stopIgnoringExternalUpdates() {
  413. return (this._ignoreExternalUpdates = false)
  414. }
  415. _syncTrackChangesState(doc) {
  416. let tryToggle
  417. if (doc == null) {
  418. return
  419. }
  420. if (this._syncTimeout != null) {
  421. clearTimeout(this._syncTimeout)
  422. this._syncTimeout = null
  423. }
  424. const want = this.$scope.editor.wantTrackChanges
  425. const have = doc.getTrackingChanges()
  426. if (want === have) {
  427. this.$scope.editor.trackChanges = want
  428. return
  429. }
  430. return (tryToggle = () => {
  431. const saved = doc.getInflightOp() == null && doc.getPendingOp() == null
  432. if (saved) {
  433. doc.setTrackingChanges(want)
  434. return this.$scope.$apply(() => {
  435. return (this.$scope.editor.trackChanges = want)
  436. })
  437. } else {
  438. return (this._syncTimeout = setTimeout(tryToggle, 100))
  439. }
  440. })()
  441. }
  442. }
  443. EditorManager.initClass()
  444. return EditorManager
  445. })()