visual.ts 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. import {
  2. Compartment,
  3. EditorState,
  4. Extension,
  5. StateEffect,
  6. StateField,
  7. TransactionSpec,
  8. } from '@codemirror/state'
  9. import { visualHighlightStyle, visualTheme } from './visual-theme'
  10. import { atomicDecorations } from './atomic-decorations'
  11. import { markDecorations } from './mark-decorations'
  12. import { EditorView, ViewPlugin } from '@codemirror/view'
  13. import { visualKeymap } from './visual-keymap'
  14. import { skipPreambleWithCursor } from './skip-preamble-cursor'
  15. import { mouseDownEffect, mouseDownListener } from './selection'
  16. import { findEffect } from '../../utils/effects'
  17. import { forceParsing, syntaxTree } from '@codemirror/language'
  18. import { hasLanguageLoadedEffect } from '../language'
  19. import { restoreScrollPosition } from '../scroll-position'
  20. import { CurrentDoc } from '../../../../../../types/current-doc'
  21. import isValidTeXFile from '../../../../main/is-valid-tex-file'
  22. import { listItemMarker } from './list-item-marker'
  23. import { figureModalPasteHandler } from '../figure-modal'
  24. import { isSplitTestEnabled } from '../../../../utils/splitTestUtils'
  25. import { toolbarPanel } from '../toolbar/toolbar-panel'
  26. type Options = {
  27. visual: boolean
  28. fileTreeManager: {
  29. getPreviewByPath: (
  30. path: string
  31. ) => { url: string; extension: string } | null
  32. }
  33. }
  34. const visualConf = new Compartment()
  35. export const toggleVisualEffect = StateEffect.define<boolean>()
  36. export const findToggleVisualEffect = findEffect(toggleVisualEffect)
  37. const visualState = StateField.define<boolean>({
  38. create() {
  39. return false
  40. },
  41. update(value, tr) {
  42. return findToggleVisualEffect(tr)?.value ?? value
  43. },
  44. })
  45. const configureVisualExtensions = (options: Options) =>
  46. options.visual ? extension(options) : []
  47. export const visual = (currentDoc: CurrentDoc, options: Options): Extension => {
  48. if (!isValidTeXFile(currentDoc.docName)) {
  49. return []
  50. }
  51. return [
  52. visualState.init(() => options.visual),
  53. visualConf.of(configureVisualExtensions(options)),
  54. ]
  55. }
  56. export const isVisual = (view: EditorView) => {
  57. return view.state.field(visualState, false) || false
  58. }
  59. export const setVisual = (options: Options): TransactionSpec => {
  60. return {
  61. effects: [
  62. toggleVisualEffect.of(options.visual),
  63. visualConf.reconfigure(configureVisualExtensions(options)),
  64. ],
  65. }
  66. }
  67. export const sourceOnly = (visual: boolean, extension: Extension) => {
  68. const conf = new Compartment()
  69. const configure = (visual: boolean) => (visual ? [] : extension)
  70. return [
  71. conf.of(configure(visual)),
  72. // Respond to switching editor modes
  73. EditorState.transactionExtender.of(tr => {
  74. const effect = findToggleVisualEffect(tr)
  75. if (effect) {
  76. return {
  77. effects: conf.reconfigure(configure(effect.value)),
  78. }
  79. }
  80. return null
  81. }),
  82. // restore the scroll position when switching to source mode
  83. EditorView.updateListener.of(update => {
  84. for (const tr of update.transactions) {
  85. for (const effect of tr.effects) {
  86. if (effect.is(toggleVisualEffect)) {
  87. if (!effect.value) {
  88. // switching to the source editor
  89. window.setTimeout(() => {
  90. update.view.dispatch(restoreScrollPosition())
  91. update.view.focus()
  92. })
  93. }
  94. }
  95. }
  96. }
  97. }),
  98. ]
  99. }
  100. const parsedAttributesConf = new Compartment()
  101. /**
  102. * A view plugin which shows the editor content, makes it focusable,
  103. * and restores the scroll position, once the initial decorations have been applied.
  104. */
  105. const showContentWhenParsed = [
  106. parsedAttributesConf.of([EditorView.editable.of(false)]),
  107. ViewPlugin.define(view => {
  108. const showContent = () => {
  109. view.dispatch(
  110. {
  111. effects: parsedAttributesConf.reconfigure([
  112. EditorView.editorAttributes.of({
  113. class: 'ol-cm-parsed',
  114. }),
  115. EditorView.editable.of(true),
  116. ]),
  117. },
  118. restoreScrollPosition()
  119. )
  120. view.focus()
  121. }
  122. // already parsed
  123. if (syntaxTree(view.state).length === view.state.doc.length) {
  124. window.setTimeout(showContent)
  125. return {}
  126. }
  127. // as a fallback, make sure the content is visible after 5s
  128. const fallbackTimer = window.setTimeout(showContent, 5000)
  129. let languageLoaded = false
  130. return {
  131. update(update) {
  132. // wait for the language to load before telling the parser to run
  133. if (!languageLoaded && hasLanguageLoadedEffect(update)) {
  134. languageLoaded = true
  135. // in a timeout, as this is already in a dispatch cycle
  136. window.setTimeout(() => {
  137. // run asynchronously
  138. new Promise(() => {
  139. // tell the parser to run until the end of the document
  140. forceParsing(view, view.state.doc.length, Infinity)
  141. // clear the fallback timeout
  142. window.clearTimeout(fallbackTimer)
  143. // show the content, in a timeout so the decorations can build first
  144. window.setTimeout(showContent)
  145. }).catch(error => {
  146. console.error(error)
  147. })
  148. })
  149. }
  150. },
  151. }
  152. }),
  153. ]
  154. /**
  155. * A transaction extender which scrolls mouse clicks into view, in case decorations have moved the cursor out of view.
  156. */
  157. const scrollJumpAdjuster = EditorState.transactionExtender.of(tr => {
  158. // Attach a "scrollIntoView" effect on all mouse selections to adjust for
  159. // any jumps that may occur when hiding/showing decorations.
  160. if (!tr.scrollIntoView) {
  161. for (const effect of tr.effects) {
  162. if (effect.is(mouseDownEffect) && effect.value === false) {
  163. return {
  164. effects: EditorView.scrollIntoView(tr.newSelection.main.head),
  165. }
  166. }
  167. }
  168. }
  169. return {}
  170. })
  171. const extension = (options: Options) => [
  172. visualTheme,
  173. visualHighlightStyle,
  174. mouseDownListener,
  175. listItemMarker,
  176. markDecorations,
  177. atomicDecorations(options),
  178. skipPreambleWithCursor,
  179. visualKeymap,
  180. scrollJumpAdjuster,
  181. isSplitTestEnabled('source-editor-toolbar') ? [] : toolbarPanel(),
  182. showContentWhenParsed,
  183. figureModalPasteHandler(),
  184. ]