EditorManager.js 17 KB

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