message-content.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import React, { useRef, useEffect } from 'react'
  2. import PropTypes from 'prop-types'
  3. import Linkify from 'react-linkify'
  4. function MessageContent({ content }) {
  5. const root = useRef(null)
  6. useEffect(() => {
  7. const MJHub = window.MathJax.Hub
  8. const inlineMathConfig = MJHub.config && MJHub.config.tex2jax.inlineMath
  9. const alreadyConfigured = inlineMathConfig.some(
  10. c => c[0] === '$' && c[1] === '$'
  11. )
  12. if (!alreadyConfigured) {
  13. MJHub.Config({
  14. tex2jax: {
  15. inlineMath: inlineMathConfig.concat([['$', '$']])
  16. }
  17. })
  18. }
  19. }, [])
  20. useEffect(
  21. () => {
  22. // adds attributes to all the links generated by <Linkify/>, required due to https://github.com/tasti/react-linkify/issues/99
  23. root.current.getElementsByTagName('a').forEach(a => {
  24. a.setAttribute('target', '_blank')
  25. a.setAttribute('rel', 'noreferrer noopener')
  26. })
  27. // MathJax typesetting
  28. const MJHub = window.MathJax.Hub
  29. const timeoutHandler = setTimeout(() => {
  30. MJHub.Queue(['Typeset', MJHub, root.current])
  31. }, 0)
  32. return () => clearTimeout(timeoutHandler)
  33. },
  34. [content]
  35. )
  36. return (
  37. <p ref={root}>
  38. <Linkify>{content}</Linkify>
  39. </p>
  40. )
  41. }
  42. MessageContent.propTypes = {
  43. content: PropTypes.string.isRequired
  44. }
  45. export default MessageContent