All files / src index.jsx

96.42% Statements 27/28
100% Branches 10/10
100% Functions 7/7
96.15% Lines 25/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 622x 2x 2x   2x 4x 32x   32x 32x 32x           22x   10x 10x             32x 10x     22x     4x             4x     2x 12x     2x       2x 12x     2x       2x 2x  
import React, { useMemo } from 'react';
import PropTypes from 'prop-types';
import KaTeX from 'katex';
 
const createMathComponent = (Component, { displayMode }) => {
  const MathComponent = ({ children, errorColor, math, renderError }) => {
    const formula = math ?? children;
 
    const { html, error } = useMemo(() => {
      try {
        const html = KaTeX.renderToString(formula, {
          displayMode,
          errorColor,
          throwOnError: !!renderError,
        });
 
        return { html, error: undefined };
      } catch (error) {
        if (error instanceof KaTeX.ParseError || error instanceof TypeError) {
          return { error };
        }
 
        throw error;
      }
    }, [formula, errorColor, renderError]);
 
    if (error) {
      return renderError ? renderError(error) : <Component html={`${error.message}`} />;
    }
 
    return <Component html={html} />;
  };
 
  MathComponent.propTypes = {
    children: PropTypes.string,
    errorColor: PropTypes.string,
    math: PropTypes.string,
    renderError: PropTypes.func,
  };
 
  return MathComponent;
};
 
const InternalBlockMath = ({ html }) => {
  return <div data-testid="react-katex" dangerouslySetInnerHTML={{ __html: html }} />;
};
 
InternalBlockMath.propTypes = {
  html: PropTypes.string.isRequired,
};
 
const InternalInlineMath = ({ html }) => {
  return <span data-testid="react-katex" dangerouslySetInnerHTML={{ __html: html }} />;
};
 
InternalInlineMath.propTypes = {
  html: PropTypes.string.isRequired,
};
 
export const BlockMath = createMathComponent(InternalBlockMath, { displayMode: true });
export const InlineMath = createMathComponent(InternalInlineMath, { displayMode: false });