EditorManager.js 15 KB

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