EditorManager.js 16 KB

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