EditorManager.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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 './controllers/SwitchToPDFButton'
  24. import getMeta from '../../utils/meta'
  25. import { hasSeenCM6SwitchAwaySurvey } from '../../features/source-editor/utils/switch-away-survey'
  26. let EditorManager
  27. export default EditorManager = (function () {
  28. EditorManager = class EditorManager {
  29. static initClass() {
  30. this.prototype._syncTimeout = null
  31. }
  32. constructor(ide, $scope, localStorage, eventTracking) {
  33. this.ide = ide
  34. this.editorOpenDocEpoch = 0 // track pending document loads
  35. this.$scope = $scope
  36. this.localStorage = localStorage
  37. this.$scope.editor = {
  38. sharejs_doc: null,
  39. open_doc_id: null,
  40. open_doc_name: null,
  41. opening: true,
  42. trackChanges: false,
  43. wantTrackChanges: false,
  44. docTooLongErrorShown: false,
  45. showRichText: this.showRichText(),
  46. newSourceEditor: this.newSourceEditor(),
  47. showSymbolPalette: false,
  48. toggleSymbolPalette: () => {
  49. const newValue = !this.$scope.editor.showSymbolPalette
  50. this.$scope.editor.showSymbolPalette = newValue
  51. if (newValue && this.$scope.editor.showGalileo) {
  52. this.$scope.editor.toggleGalileoPanel()
  53. }
  54. ide.$scope.$emit('south-pane-toggled', newValue)
  55. eventTracking.sendMB(
  56. newValue ? 'symbol-palette-show' : 'symbol-palette-hide'
  57. )
  58. },
  59. insertSymbol: symbol => {
  60. ide.$scope.$emit('editor:replace-selection', symbol.command)
  61. eventTracking.sendMB('symbol-palette-insert')
  62. },
  63. showGalileo: false,
  64. toggleGalileoPanel: () => {
  65. const newValue = !this.$scope.editor.showGalileo
  66. this.$scope.editor.showGalileo = newValue
  67. if (newValue && this.$scope.editor.showSymbolPalette) {
  68. this.$scope.editor.toggleSymbolPalette()
  69. }
  70. ide.$scope.$emit('south-pane-toggled', newValue)
  71. eventTracking.sendMB(newValue ? 'galileo-show' : 'galileo-hide')
  72. },
  73. galileoActivated: false,
  74. toggleGalileo: () => {
  75. const newValue = !this.$scope.editor.galileoActivated
  76. this.$scope.editor.galileoActivated = newValue
  77. eventTracking.sendMB(
  78. newValue ? 'galileo-activated' : 'galileo-disabled'
  79. )
  80. },
  81. multiSelectedCount: 0,
  82. }
  83. window.addEventListener('editor:insert-symbol', event => {
  84. this.$scope.editor.insertSymbol(event.detail)
  85. })
  86. this.$scope.$on('entity:selected', (event, entity) => {
  87. if (this.$scope.ui.view !== 'history' && entity.type === 'doc') {
  88. return this.openDoc(entity)
  89. }
  90. })
  91. this.$scope.$on('entity:no-selection', () => {
  92. this.$scope.$apply(() => {
  93. this.$scope.ui.view = null
  94. })
  95. })
  96. this.$scope.$on('entity:deleted', (event, entity) => {
  97. if (this.$scope.editor.open_doc_id === entity.id) {
  98. if (!this.$scope.project.rootDoc_id) {
  99. this.$scope.ui.view = null
  100. return
  101. }
  102. const doc = this.ide.fileTreeManager.findEntityById(
  103. this.$scope.project.rootDoc_id
  104. )
  105. if (doc == null) {
  106. this.$scope.ui.view = null
  107. return
  108. }
  109. return this.openDoc(doc)
  110. }
  111. })
  112. let initialized = false
  113. this.$scope.$on('file-tree:initialized', () => {
  114. if (!initialized) {
  115. initialized = true
  116. return this.autoOpenDoc()
  117. }
  118. })
  119. this.$scope.$on('flush-changes', () => {
  120. return Document.flushAll()
  121. })
  122. // event dispatched by pdf preview
  123. window.addEventListener('flush-changes', () => {
  124. Document.flushAll()
  125. })
  126. window.addEventListener('blur', () => {
  127. // The browser may put the tab into sleep as it looses focus.
  128. // Flushing the documents should help with keeping the documents in
  129. // sync: we can use any new version of the doc that the server may
  130. // present us. There should be no need to insert local changes into
  131. // the doc history as the user comes back.
  132. sl_console.log('[EditorManager] forcing flush onblur')
  133. Document.flushAll()
  134. })
  135. this.$scope.$watch('editor.wantTrackChanges', value => {
  136. if (value == null) {
  137. return
  138. }
  139. return this._syncTrackChangesState(this.$scope.editor.sharejs_doc)
  140. })
  141. window.addEventListener('editor:open-doc', event => {
  142. const { doc, ...options } = event.detail
  143. this.openDoc(doc, options)
  144. })
  145. }
  146. getEditorType() {
  147. if (!this.$scope.editor.sharejs_doc) {
  148. return null
  149. }
  150. return this.$scope.editor.sharejs_doc.editorType()
  151. }
  152. showRichText() {
  153. return (
  154. this.localStorage(`editor.mode.${this.$scope.project_id}`) ===
  155. 'rich-text'
  156. )
  157. }
  158. newSourceEditor() {
  159. // only use the new source editor if the option to switch is available
  160. if (!getMeta('ol-showNewSourceEditorOption')) {
  161. return false
  162. }
  163. const storedPrefIsCM6 = () => {
  164. const sourceEditor = this.localStorage(
  165. `editor.source_editor.${this.$scope.project_id}`
  166. )
  167. return sourceEditor === 'cm6' || sourceEditor == null
  168. }
  169. const showCM6SwitchAwaySurvey = getMeta('ol-showCM6SwitchAwaySurvey')
  170. if (!showCM6SwitchAwaySurvey) {
  171. return storedPrefIsCM6()
  172. }
  173. if (hasSeenCM6SwitchAwaySurvey()) {
  174. return storedPrefIsCM6()
  175. } else {
  176. // force user to switch to cm6 if they haven't seen either of the
  177. // switch-away surveys
  178. return true
  179. }
  180. }
  181. autoOpenDoc() {
  182. const open_doc_id =
  183. this.ide.localStorage(`doc.open_id.${this.$scope.project_id}`) ||
  184. this.$scope.project.rootDoc_id
  185. if (open_doc_id == null) {
  186. return
  187. }
  188. const doc = this.ide.fileTreeManager.findEntityById(open_doc_id)
  189. if (doc == null) {
  190. return
  191. }
  192. return this.openDoc(doc)
  193. }
  194. openDocId(doc_id, options) {
  195. if (options == null) {
  196. options = {}
  197. }
  198. const doc = this.ide.fileTreeManager.findEntityById(doc_id)
  199. if (doc == null) {
  200. return
  201. }
  202. return this.openDoc(doc, options)
  203. }
  204. jumpToLine(options) {
  205. return this.$scope.$broadcast(
  206. 'editor:gotoLine',
  207. options.gotoLine,
  208. options.gotoColumn,
  209. options.syncToPdf
  210. )
  211. }
  212. openDoc(doc, options) {
  213. if (options == null) {
  214. options = {}
  215. }
  216. sl_console.log(`[openDoc] Opening ${doc.id}`)
  217. if (this.$scope.ui.view === 'editor') {
  218. // store position of previous doc before switching docs
  219. this.$scope.$broadcast('store-doc-position')
  220. }
  221. this.$scope.ui.view = 'editor'
  222. const done = isNewDoc => {
  223. const eventName = 'doc:after-opened'
  224. this.$scope.$broadcast(eventName, { isNewDoc })
  225. window.dispatchEvent(new CustomEvent(eventName, { detail: isNewDoc }))
  226. if (options.gotoLine != null) {
  227. // allow Ace to display document before moving, delay until next tick
  228. // added delay to make this happen later that gotoStoredPosition in
  229. // CursorPositionManager
  230. return setTimeout(() => this.jumpToLine(options), 0)
  231. } else if (options.gotoOffset != null) {
  232. return setTimeout(() => {
  233. return this.$scope.$broadcast(
  234. 'editor:gotoOffset',
  235. options.gotoOffset
  236. )
  237. }, 0)
  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. })()