message-content.js 1.4 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. if (!(window.MathJax && window.MathJax.Hub)) {
  8. return
  9. }
  10. const MJHub = window.MathJax.Hub
  11. const inlineMathConfig = MJHub.config && MJHub.config.tex2jax.inlineMath
  12. const alreadyConfigured = inlineMathConfig.some(
  13. c => c[0] === '$' && c[1] === '$'
  14. )
  15. if (!alreadyConfigured) {
  16. MJHub.Config({
  17. tex2jax: {
  18. inlineMath: inlineMathConfig.concat([['$', '$']])
  19. }
  20. })
  21. }
  22. }, [])
  23. useEffect(() => {
  24. // adds attributes to all the links generated by <Linkify/>, required due to https://github.com/tasti/react-linkify/issues/99
  25. for (let a of root.current.getElementsByTagName('a')) {
  26. a.setAttribute('target', '_blank')
  27. a.setAttribute('rel', 'noreferrer noopener')
  28. }
  29. // MathJax typesetting
  30. const MJHub = window.MathJax.Hub
  31. const timeoutHandler = setTimeout(() => {
  32. MJHub.Queue(['Typeset', MJHub, root.current])
  33. }, 0)
  34. return () => clearTimeout(timeoutHandler)
  35. }, [content])
  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