All files / FormattedKintMessage FormattedKintMessage.js

13.33% Statements 2/15
0% Branches 0/12
0% Functions 0/1
13.33% Lines 2/15

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          27x                                                                               27x                  
import PropTypes from 'prop-types';
import { FormattedMessage, useIntl } from 'react-intl';
import { useIntlKey } from '../hooks';
 
// This works analogously to useKintIntl's "formatKintMessage"
const FormattedKintMessage = ({
  fallbackMessage,
  id,
  intlKey: passedIntlKey,
  intlNS: passedIntlNS,
  overrideValue,
  ...formattedMessageProps
}) => {
  const intlKey = useIntlKey(passedIntlKey, passedIntlNS);
  const intlObj = useIntl();
 
  if (overrideValue) {
    // Version 3 is a breaking change, where labelOverrides must be strings.
    if (typeof overrideValue !== 'string') {
      throw new Error('Override values must be strings as of stripes-kint-components ^3.0.0');
    }
 
    if (intlObj.messages?.[overrideValue]) {
      // We've been passed a key as an override, return formattedMessage with it
      return <FormattedMessage id={overrideValue} {...formattedMessageProps} />;
    }
    // At this stage we have an overrideValue that's not a key, return it.
    return overrideValue;
  }
 
  // If key does not exist in intl, and we have a specified "fallbackMessage", use that
 
  // (FallbackMessage works like defaultMessage but with no warning)
  if (!intlObj.messages?.[`${intlKey}.${id}`] && fallbackMessage) {
    // Allow fallback message to be an intl key
    if (intlObj.messages?.[fallbackMessage]) {
      return <FormattedMessage id={fallbackMessage} {...formattedMessageProps} />;
    }
 
    return fallbackMessage;
  }
 
  return (<FormattedMessage id={`${intlKey}.${id}`} {...formattedMessageProps} />);
};
 
FormattedKintMessage.propTypes = {
  fallbackMessage: PropTypes.string,
  id: PropTypes.string.isRequired,
  intlKey: PropTypes.string,
  intlNS: PropTypes.string,
  overrideValue: PropTypes.string
};
 
export default FormattedKintMessage;