math-preview.ts 6.2 KB

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