EditorManager.js 17 KB

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