EditorManager.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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. 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. const sourceEditor = this.localStorage(
  142. `editor.source_editor.${this.$scope.project_id}`
  143. )
  144. return sourceEditor === 'cm6' || sourceEditor == null
  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. if (this.$scope.ui.view === 'editor') {
  183. // store position of previous doc before switching docs
  184. this.$scope.$broadcast('store-doc-position')
  185. }
  186. this.$scope.ui.view = 'editor'
  187. const done = isNewDoc => {
  188. const eventName = 'doc:after-opened'
  189. this.$scope.$broadcast(eventName, { isNewDoc })
  190. window.dispatchEvent(new CustomEvent(eventName, { isNewDoc }))
  191. if (options.gotoLine != null) {
  192. // allow Ace to display document before moving, delay until next tick
  193. // added delay to make this happen later that gotoStoredPosition in
  194. // CursorPositionManager
  195. return setTimeout(() => this.jumpToLine(options), 0)
  196. } else if (options.gotoOffset != null) {
  197. return setTimeout(() => {
  198. return this.$scope.$broadcast(
  199. 'editor:gotoOffset',
  200. options.gotoOffset
  201. )
  202. }, 0)
  203. }
  204. }
  205. // If we already have the document open we can return at this point.
  206. // Note: only use forceReopen:true to override this when the document is
  207. // is out of sync and needs to be reloaded from the server.
  208. if (doc.id === this.$scope.editor.open_doc_id && !options.forceReopen) {
  209. // automatically update the file tree whenever the file is opened
  210. this.ide.fileTreeManager.selectEntity(doc)
  211. this.$scope.$broadcast('file-tree.reselectDoc', doc.id)
  212. this.$scope.$apply(() => {
  213. return done(false)
  214. })
  215. return
  216. }
  217. // We're now either opening a new document or reloading a broken one.
  218. this.$scope.editor.open_doc_id = doc.id
  219. this.$scope.editor.open_doc_name = doc.name
  220. this.ide.localStorage(`doc.open_id.${this.$scope.project_id}`, doc.id)
  221. this.ide.fileTreeManager.selectEntity(doc)
  222. this.$scope.editor.opening = true
  223. return this._openNewDocument(doc, (error, sharejs_doc) => {
  224. if (error && error.message === 'another document was loaded') {
  225. sl_console.log(
  226. `[openDoc] another document was loaded while ${doc.id} was loading`
  227. )
  228. return
  229. }
  230. if (error != null) {
  231. this.ide.showGenericMessageModal(
  232. 'Error opening document',
  233. 'Sorry, something went wrong opening this document. Please try again.'
  234. )
  235. return
  236. }
  237. this._syncTrackChangesState(sharejs_doc)
  238. this.$scope.$broadcast('doc:opened')
  239. return this.$scope.$apply(() => {
  240. this.$scope.editor.opening = false
  241. this.$scope.editor.sharejs_doc = sharejs_doc
  242. return done(true)
  243. })
  244. })
  245. }
  246. _openNewDocument(doc, callback) {
  247. // Leave the current document
  248. // - when we are opening a different new one, to avoid race conditions
  249. // between leaving and joining the same document
  250. // - when the current one has pending ops that need flushing, to avoid
  251. // race conditions from cleanup
  252. const current_sharejs_doc = this.$scope.editor.sharejs_doc
  253. const currentDocId = current_sharejs_doc && current_sharejs_doc.doc_id
  254. const hasBufferedOps =
  255. current_sharejs_doc && current_sharejs_doc.hasBufferedOps()
  256. const changingDoc = current_sharejs_doc && currentDocId !== doc.id
  257. if (changingDoc || hasBufferedOps) {
  258. sl_console.log('[_openNewDocument] Leaving existing open doc...')
  259. // Do not trigger any UI changes from remote operations
  260. this._unbindFromDocumentEvents(current_sharejs_doc)
  261. // Keep listening for out-of-sync and similar errors.
  262. this._attachErrorHandlerToDocument(doc, current_sharejs_doc)
  263. // Teardown the Document -> ShareJsDoc -> sharejs doc
  264. // By the time this completes, the Document instance is no longer
  265. // registered in Document.openDocs and _doOpenNewDocument can start
  266. // from scratch -- read: no corrupted internal state.
  267. const editorOpenDocEpoch = ++this.editorOpenDocEpoch
  268. current_sharejs_doc.leaveAndCleanUp(error => {
  269. if (error) {
  270. sl_console.log(
  271. `[_openNewDocument] error leaving doc ${currentDocId}`,
  272. error
  273. )
  274. return callback(error)
  275. }
  276. if (this.editorOpenDocEpoch !== editorOpenDocEpoch) {
  277. sl_console.log(
  278. `[openNewDocument] editorOpenDocEpoch mismatch ${this.editorOpenDocEpoch} vs ${editorOpenDocEpoch}`
  279. )
  280. return callback(new Error('another document was loaded'))
  281. }
  282. this._doOpenNewDocument(doc, callback)
  283. })
  284. } else {
  285. this._doOpenNewDocument(doc, callback)
  286. }
  287. }
  288. _doOpenNewDocument(doc, callback) {
  289. if (callback == null) {
  290. callback = function () {}
  291. }
  292. sl_console.log('[_doOpenNewDocument] Opening...')
  293. const new_sharejs_doc = Document.getDocument(this.ide, doc.id)
  294. const editorOpenDocEpoch = ++this.editorOpenDocEpoch
  295. return new_sharejs_doc.join(error => {
  296. if (error != null) {
  297. sl_console.log(
  298. `[_doOpenNewDocument] error joining doc ${doc.id}`,
  299. error
  300. )
  301. return callback(error)
  302. }
  303. if (this.editorOpenDocEpoch !== editorOpenDocEpoch) {
  304. sl_console.log(
  305. `[openNewDocument] editorOpenDocEpoch mismatch ${this.editorOpenDocEpoch} vs ${editorOpenDocEpoch}`
  306. )
  307. new_sharejs_doc.leaveAndCleanUp()
  308. return callback(new Error('another document was loaded'))
  309. }
  310. this._bindToDocumentEvents(doc, new_sharejs_doc)
  311. return callback(null, new_sharejs_doc)
  312. })
  313. }
  314. _attachErrorHandlerToDocument(doc, sharejs_doc) {
  315. sharejs_doc.on('error', (error, meta, editorContent) => {
  316. let message
  317. if ((error != null ? error.message : undefined) != null) {
  318. ;({ message } = error)
  319. } else if (typeof error === 'string') {
  320. message = error
  321. } else {
  322. message = ''
  323. }
  324. if (/maxDocLength/.test(message)) {
  325. this.$scope.docTooLongErrorShown = true
  326. this.openDoc(doc, { forceReopen: true })
  327. const genericMessageModal = this.ide.showGenericMessageModal(
  328. 'Document Too Long',
  329. 'Sorry, this file is too long to be edited manually. Please upload it directly.'
  330. )
  331. genericMessageModal.result.finally(() => {
  332. this.$scope.docTooLongErrorShown = false
  333. })
  334. } else if (/too many comments or tracked changes/.test(message)) {
  335. this.ide.showGenericMessageModal(
  336. 'Too many comments or tracked changes',
  337. 'Sorry, this file has too many comments or tracked changes. Please try accepting or rejecting some existing changes, or resolving and deleting some comments.'
  338. )
  339. } else if (!this.$scope.docTooLongErrorShown) {
  340. // Do not allow this doc to open another error modal.
  341. sharejs_doc.off('error')
  342. // Preserve the sharejs contents before the teardown.
  343. editorContent =
  344. typeof editorContent === 'string'
  345. ? editorContent
  346. : sharejs_doc.doc._doc.snapshot
  347. // Tear down the ShareJsDoc.
  348. if (sharejs_doc.doc) sharejs_doc.doc.clearInflightAndPendingOps()
  349. // Do not re-join after re-connecting.
  350. sharejs_doc.leaveAndCleanUp()
  351. this.ide.connectionManager.disconnect({ permanent: true })
  352. this.ide.reportError(error, meta)
  353. // Tell the user about the error state.
  354. this.$scope.editor.error_state = true
  355. this.ide.showOutOfSyncModal(
  356. 'Out of sync',
  357. "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>",
  358. editorContent
  359. )
  360. // Do not forceReopen the document.
  361. return
  362. }
  363. const removeHandler = this.$scope.$on('project:joined', () => {
  364. this.openDoc(doc, { forceReopen: true })
  365. removeHandler()
  366. })
  367. })
  368. }
  369. _bindToDocumentEvents(doc, sharejs_doc) {
  370. this._attachErrorHandlerToDocument(doc, sharejs_doc)
  371. return sharejs_doc.on('externalUpdate', update => {
  372. if (this._ignoreExternalUpdates) {
  373. return
  374. }
  375. if (
  376. _.property(['meta', 'type'])(update) === 'external' &&
  377. _.property(['meta', 'source'])(update) === 'git-bridge'
  378. ) {
  379. return
  380. }
  381. return this.ide.showGenericMessageModal(
  382. 'Document Updated Externally',
  383. '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.'
  384. )
  385. })
  386. }
  387. _unbindFromDocumentEvents(document) {
  388. return document.off()
  389. }
  390. getCurrentDocValue() {
  391. return this.$scope.editor.sharejs_doc != null
  392. ? this.$scope.editor.sharejs_doc.getSnapshot()
  393. : undefined
  394. }
  395. getCurrentDocId() {
  396. return this.$scope.editor.open_doc_id
  397. }
  398. startIgnoringExternalUpdates() {
  399. return (this._ignoreExternalUpdates = true)
  400. }
  401. stopIgnoringExternalUpdates() {
  402. return (this._ignoreExternalUpdates = false)
  403. }
  404. _syncTrackChangesState(doc) {
  405. let tryToggle
  406. if (doc == null) {
  407. return
  408. }
  409. if (this._syncTimeout != null) {
  410. clearTimeout(this._syncTimeout)
  411. this._syncTimeout = null
  412. }
  413. const want = this.$scope.editor.wantTrackChanges
  414. const have = doc.getTrackingChanges()
  415. if (want === have) {
  416. this.$scope.editor.trackChanges = want
  417. return
  418. }
  419. return (tryToggle = () => {
  420. const saved = doc.getInflightOp() == null && doc.getPendingOp() == null
  421. if (saved) {
  422. doc.setTrackingChanges(want)
  423. return this.$scope.$apply(() => {
  424. return (this.$scope.editor.trackChanges = want)
  425. })
  426. } else {
  427. return (this._syncTimeout = setTimeout(tryToggle, 100))
  428. }
  429. })()
  430. }
  431. }
  432. EditorManager.initClass()
  433. return EditorManager
  434. })()