math-preview.tsx 5.2 KB

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