visual.ts 6.4 KB

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