EditorManager.js 17 KB

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