EditorManager.js 17 KB

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