message-content.tsx 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { useRef, useEffect, type FC } from 'react'
  2. // @ts-ignore
  3. import Linkify from 'react-linkify'
  4. import { loadMathJax } from '../../../../../modules/source-editor/frontend/js/utils/mathjax'
  5. import useIsMounted from '../../../shared/hooks/use-is-mounted'
  6. import { configureMathJax } from '../../mathjax/configure'
  7. const MessageContent: FC<{ content: string }> = ({ content }) => {
  8. const root = useRef<HTMLDivElement | null>(null)
  9. const mounted = useIsMounted()
  10. useEffect(() => {
  11. if (root.current) {
  12. // adds attributes to all the links generated by <Linkify/>, required due to https://github.com/tasti/react-linkify/issues/99
  13. for (const a of root.current.getElementsByTagName('a')) {
  14. a.setAttribute('target', '_blank')
  15. a.setAttribute('rel', 'noreferrer noopener')
  16. }
  17. // MathJax v2 typesetting
  18. if (window.MathJax?.Hub) {
  19. const timeout = setTimeout(() => {
  20. configureMathJax()
  21. window.MathJax.Hub.Queue([
  22. 'Typeset',
  23. window.MathJax.Hub,
  24. root.current,
  25. ])
  26. }, 0)
  27. return () => clearTimeout(timeout)
  28. }
  29. // MathJax v3 typesetting
  30. loadMathJax()
  31. .then(MathJax => {
  32. if (mounted.current) {
  33. MathJax.typesetPromise([root.current]).catch((error: Error) => {
  34. console.error(error)
  35. })
  36. }
  37. })
  38. .catch(error => {
  39. console.error(error)
  40. })
  41. }
  42. }, [content, mounted])
  43. return (
  44. <p ref={root}>
  45. <Linkify>{content}</Linkify>
  46. </p>
  47. )
  48. }
  49. export default MessageContent