message-content.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. // adds attributes to all the links generated by <Linkify/>, required due to https://github.com/tasti/react-linkify/issues/99
  22. for (let a of root.current.getElementsByTagName('a')) {
  23. a.setAttribute('target', '_blank')
  24. a.setAttribute('rel', 'noreferrer noopener')
  25. }
  26. // MathJax typesetting
  27. const MJHub = window.MathJax.Hub
  28. const timeoutHandler = setTimeout(() => {
  29. MJHub.Queue(['Typeset', MJHub, root.current])
  30. }, 0)
  31. return () => clearTimeout(timeoutHandler)
  32. }, [content])
  33. return (
  34. <p ref={root}>
  35. <Linkify>{content}</Linkify>
  36. </p>
  37. )
  38. }
  39. MessageContent.propTypes = {
  40. content: PropTypes.string.isRequired
  41. }
  42. export default MessageContent