visual.ts 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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. import { PreviewPath } from '../../../../../../types/preview-path'
  28. type Options = {
  29. visual: boolean
  30. previewByPath: (path: string) => PreviewPath | null
  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. /**
  100. * A view plugin which shows the editor content, makes it focusable,
  101. * and restores the scroll position, once the initial decorations have been applied.
  102. */
  103. const showContentWhenParsed = [
  104. parsedAttributesConf.of([EditorView.editable.of(false)]),
  105. ViewPlugin.define(view => {
  106. const showContent = () => {
  107. view.dispatch(
  108. {
  109. effects: parsedAttributesConf.reconfigure([
  110. EditorView.editorAttributes.of({
  111. class: 'ol-cm-parsed',
  112. }),
  113. EditorView.editable.of(true),
  114. ]),
  115. },
  116. restoreScrollPosition()
  117. )
  118. view.focus()
  119. }
  120. // already parsed
  121. if (syntaxTree(view.state).length === view.state.doc.length) {
  122. window.setTimeout(showContent)
  123. return {}
  124. }
  125. // as a fallback, make sure the content is visible after 5s
  126. const fallbackTimer = window.setTimeout(showContent, 5000)
  127. let languageLoaded = false
  128. return {
  129. update(update) {
  130. // wait for the language to load before telling the parser to run
  131. if (!languageLoaded && hasLanguageLoadedEffect(update)) {
  132. languageLoaded = true
  133. // in a timeout, as this is already in a dispatch cycle
  134. window.setTimeout(() => {
  135. // run asynchronously
  136. new Promise(() => {
  137. // tell the parser to run until the end of the document
  138. forceParsing(view, view.state.doc.length, Infinity)
  139. // clear the fallback timeout
  140. window.clearTimeout(fallbackTimer)
  141. // show the content, in a timeout so the decorations can build first
  142. window.setTimeout(showContent)
  143. }).catch(debugConsole.error)
  144. })
  145. }
  146. },
  147. }
  148. }),
  149. ]
  150. /**
  151. * A transaction extender which scrolls mouse clicks into view, in case decorations have moved the cursor out of view.
  152. */
  153. const scrollJumpAdjuster = EditorState.transactionExtender.of(tr => {
  154. // Attach a "scrollIntoView" effect on all mouse selections to adjust for
  155. // any jumps that may occur when hiding/showing decorations.
  156. if (!tr.scrollIntoView) {
  157. for (const effect of tr.effects) {
  158. if (effect.is(mouseDownEffect) && effect.value === false) {
  159. return {
  160. effects: EditorView.scrollIntoView(tr.newSelection.main.head),
  161. }
  162. }
  163. }
  164. }
  165. return {}
  166. })
  167. const extension = (options: Options) => [
  168. visualTheme,
  169. visualHighlightStyle,
  170. mousedown,
  171. listItemMarker,
  172. atomicDecorations(options),
  173. markDecorations, // NOTE: must be after atomicDecorations, so that mark decorations wrap inline widgets
  174. visualKeymap,
  175. commandTooltip,
  176. scrollJumpAdjuster,
  177. selectDecoratedArgument,
  178. showContentWhenParsed,
  179. pasteHtml,
  180. tableGeneratorTheme,
  181. ]