visual.ts 5.5 KB

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