math-preview.tsx 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. import {
  2. EditorView,
  3. repositionTooltips,
  4. showTooltip,
  5. Tooltip,
  6. ViewPlugin,
  7. } from '@codemirror/view'
  8. import {
  9. Compartment,
  10. EditorState,
  11. Extension,
  12. StateField,
  13. TransactionSpec,
  14. } from '@codemirror/state'
  15. import { loadMathJax } from '../../mathjax/load-mathjax'
  16. import { descendantsOfNodeWithType } from '../utils/tree-query'
  17. import {
  18. MathContainer,
  19. mathAncestorNode,
  20. parseMathContainer,
  21. } from '../utils/tree-operations/math'
  22. import { documentCommands } from '../languages/latex/document-commands'
  23. import { debugConsole } from '@/utils/debugging'
  24. import { isSplitTestEnabled } from '@/utils/splitTestUtils'
  25. import ReactDOM from 'react-dom'
  26. import { SplitTestProvider } from '@/shared/context/split-test-context'
  27. import SplitTestBadge from '@/shared/components/split-test-badge'
  28. import { nodeHasError } from '../utils/tree-operations/common'
  29. const REPOSITION_EVENT = 'editor:repositionMathTooltips'
  30. export const mathPreview = (enabled: boolean): Extension => {
  31. if (!isSplitTestEnabled('math-preview')) {
  32. return []
  33. }
  34. return mathPreviewConf.of(
  35. enabled ? [mathPreviewTheme, mathPreviewStateField] : []
  36. )
  37. }
  38. const mathPreviewConf = new Compartment()
  39. export const setMathPreview = (enabled: boolean): TransactionSpec => ({
  40. effects: mathPreviewConf.reconfigure(enabled ? mathPreviewStateField : []),
  41. })
  42. const mathPreviewStateField = StateField.define<readonly Tooltip[]>({
  43. create: buildTooltips,
  44. update(tooltips, tr) {
  45. if (tr.docChanged || tr.selection) {
  46. tooltips = buildTooltips(tr.state)
  47. }
  48. return tooltips
  49. },
  50. provide: field => [
  51. showTooltip.computeN([field], state => state.field(field)),
  52. ViewPlugin.define(view => {
  53. const listener = () => repositionTooltips(view)
  54. window.addEventListener(REPOSITION_EVENT, listener)
  55. return {
  56. destroy() {
  57. window.removeEventListener(REPOSITION_EVENT, listener)
  58. },
  59. }
  60. }),
  61. ],
  62. })
  63. const renderMath = async (
  64. content: string,
  65. displayMode: boolean,
  66. element: HTMLElement,
  67. definitions: string
  68. ) => {
  69. const MathJax = await loadMathJax()
  70. MathJax.texReset([0]) // equation numbering is disabled, but this is still needed
  71. try {
  72. await MathJax.tex2svgPromise(definitions)
  73. } catch {
  74. // ignore errors thrown during parsing command definitions
  75. }
  76. const math = await MathJax.tex2svgPromise(content, {
  77. ...MathJax.getMetricsFor(element),
  78. display: displayMode,
  79. })
  80. element.textContent = ''
  81. element.append(math)
  82. }
  83. function buildTooltips(state: EditorState): readonly Tooltip[] {
  84. const tooltips: Tooltip[] = []
  85. for (const range of state.selection.ranges) {
  86. if (range.empty) {
  87. const mathContainer = getMathContainer(state, range.from)
  88. const content = buildTooltipContent(state, mathContainer)
  89. if (content && mathContainer) {
  90. const tooltip: Tooltip = {
  91. pos: mathContainer.pos,
  92. above: true,
  93. strictSide: true,
  94. arrow: false,
  95. create() {
  96. const dom = document.createElement('div')
  97. dom.append(content)
  98. const badge = renderSplitTestBadge()
  99. dom.append(badge)
  100. dom.className = 'ol-cm-math-tooltip'
  101. return { dom, overlap: true, offset: { x: 0, y: 8 } }
  102. },
  103. }
  104. tooltips.push(tooltip)
  105. }
  106. }
  107. }
  108. return tooltips
  109. }
  110. const getMathContainer = (state: EditorState, pos: number) => {
  111. // if anywhere inside Math, find the whole Math node
  112. const ancestorNode = mathAncestorNode(state, pos)
  113. if (!ancestorNode) return null
  114. const [node] = descendantsOfNodeWithType(ancestorNode, 'Math', 'Math')
  115. if (!node) return null
  116. if (nodeHasError(ancestorNode)) return null
  117. return parseMathContainer(state, node, ancestorNode)
  118. }
  119. const buildTooltipContent = (
  120. state: EditorState,
  121. math: MathContainer | null
  122. ): HTMLDivElement | null => {
  123. if (!math || !math.content.length) return null
  124. const element = document.createElement('div')
  125. element.style.opacity = '0'
  126. element.textContent = math.content
  127. let definitions = ''
  128. const commandState = state.field(documentCommands, false)
  129. if (commandState?.items) {
  130. for (const command of commandState.items) {
  131. if (command.type === 'definition' && command.raw) {
  132. definitions += `${command.raw}\n`
  133. }
  134. }
  135. }
  136. renderMath(math.content, math.displayMode, element, definitions)
  137. .then(() => {
  138. element.style.opacity = '1'
  139. window.dispatchEvent(new Event(REPOSITION_EVENT))
  140. })
  141. .catch(error => {
  142. debugConsole.error(error)
  143. })
  144. return element
  145. }
  146. const renderSplitTestBadge = () => {
  147. const element = document.createElement('span')
  148. ReactDOM.render(
  149. <SplitTestProvider>
  150. <SplitTestBadge
  151. displayOnVariants={['enabled']}
  152. splitTestName="math-preview"
  153. />
  154. </SplitTestProvider>,
  155. element
  156. )
  157. return element
  158. }
  159. /**
  160. * Styles for the preview tooltip
  161. */
  162. const mathPreviewTheme = EditorView.baseTheme({
  163. '&light .ol-cm-math-tooltip': {
  164. boxShadow: '0px 2px 4px 0px #1e253029',
  165. border: '1px solid #e7e9ee !important',
  166. backgroundColor: 'white !important',
  167. },
  168. '&dark .ol-cm-math-tooltip': {
  169. boxShadow: '0px 2px 4px 0px #1e253029',
  170. border: '1px solid #2f3a4c !important',
  171. backgroundColor: '#1b222c !important',
  172. },
  173. })