visual.ts 5.7 KB

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