message-content.js 1.4 KB

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