math-preview.ts 6.1 KB

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