EditorManager.js 18 KB

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