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