math-preview.ts 5.9 KB

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