math-preview.ts 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. import {
  2. repositionTooltips,
  3. showTooltip,
  4. Tooltip,
  5. ViewPlugin,
  6. } from '@codemirror/view'
  7. import {
  8. Compartment,
  9. EditorState,
  10. Extension,
  11. StateField,
  12. TransactionSpec,
  13. } from '@codemirror/state'
  14. import { loadMathJax } from '../../mathjax/load-mathjax'
  15. import { descendantsOfNodeWithType } from '../utils/tree-query'
  16. import {
  17. mathAncestorNode,
  18. parseMathContainer,
  19. } from '../utils/tree-operations/math'
  20. import { documentCommands } from '../languages/latex/document-commands'
  21. import { debugConsole } from '@/utils/debugging'
  22. import { isSplitTestEnabled } from '@/utils/splitTestUtils'
  23. const REPOSITION_EVENT = 'editor:repositionMathTooltips'
  24. export const mathPreview = (enabled: boolean): Extension => {
  25. if (!isSplitTestEnabled('math-preview')) {
  26. return []
  27. }
  28. return mathPreviewConf.of(enabled ? mathPreviewStateField : [])
  29. }
  30. const mathPreviewConf = new Compartment()
  31. export const setMathPreview = (enabled: boolean): TransactionSpec => ({
  32. effects: mathPreviewConf.reconfigure(enabled ? mathPreviewStateField : []),
  33. })
  34. const mathPreviewStateField = StateField.define<readonly Tooltip[]>({
  35. create: buildTooltips,
  36. update(tooltips, tr) {
  37. if (tr.docChanged || tr.selection) {
  38. tooltips = buildTooltips(tr.state)
  39. }
  40. return tooltips
  41. },
  42. provide: field => [
  43. showTooltip.computeN([field], state => state.field(field)),
  44. ViewPlugin.define(view => {
  45. const listener = () => repositionTooltips(view)
  46. window.addEventListener(REPOSITION_EVENT, listener)
  47. return {
  48. destroy() {
  49. window.removeEventListener(REPOSITION_EVENT, listener)
  50. },
  51. }
  52. }),
  53. ],
  54. })
  55. const renderMath = async (
  56. content: string,
  57. displayMode: boolean,
  58. element: HTMLElement,
  59. definitions: string
  60. ) => {
  61. const MathJax = await loadMathJax()
  62. MathJax.texReset([0]) // equation numbering is disabled, but this is still needed
  63. try {
  64. await MathJax.tex2svgPromise(definitions)
  65. } catch {
  66. // ignore errors thrown during parsing command definitions
  67. }
  68. const math = await MathJax.tex2svgPromise(content, {
  69. ...MathJax.getMetricsFor(element),
  70. display: displayMode,
  71. })
  72. element.textContent = ''
  73. element.append(math)
  74. }
  75. function buildTooltips(state: EditorState): readonly Tooltip[] {
  76. const tooltips: Tooltip[] = []
  77. for (const range of state.selection.ranges) {
  78. if (range.empty) {
  79. const pos = range.from
  80. const content = buildTooltipContent(state, pos)
  81. if (content) {
  82. const tooltip: Tooltip = {
  83. pos,
  84. above: true,
  85. arrow: false,
  86. create() {
  87. const dom = document.createElement('div')
  88. dom.append(content)
  89. dom.className = 'ol-cm-math-tooltip'
  90. return { dom, overlap: true, offset: { x: 0, y: 8 } }
  91. },
  92. }
  93. tooltips.push(tooltip)
  94. }
  95. }
  96. }
  97. return tooltips
  98. }
  99. const buildTooltipContent = (
  100. state: EditorState,
  101. pos: number
  102. ): HTMLDivElement | null => {
  103. // if anywhere inside Math, render the whole Math content
  104. const ancestorNode = mathAncestorNode(state, pos)
  105. if (!ancestorNode) return null
  106. const [node] = descendantsOfNodeWithType(ancestorNode, 'Math', 'Math')
  107. if (!node) return null
  108. const math = parseMathContainer(state, node, ancestorNode)
  109. if (!math || !math.content.length) return null
  110. const element = document.createElement('div')
  111. element.style.opacity = '0'
  112. element.style.transition = 'opacity .01s ease-in'
  113. element.textContent = math.content
  114. let definitions = ''
  115. const commandState = state.field(documentCommands, false)
  116. if (commandState?.items) {
  117. for (const command of commandState.items) {
  118. if (command.type === 'definition' && command.raw) {
  119. definitions += `${command.raw}\n`
  120. }
  121. }
  122. }
  123. renderMath(math.content, math.displayMode, element, definitions)
  124. .then(() => {
  125. element.style.opacity = '1'
  126. window.dispatchEvent(new Event(REPOSITION_EVENT))
  127. })
  128. .catch(error => {
  129. debugConsole.error(error)
  130. })
  131. return element
  132. }