EditorManager.js 18 KB

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