All files / hooks/intlHooks/useKintIntl useKintIntl.js

83.33% Statements 15/18
75% Branches 9/12
100% Functions 3/3
82.35% Lines 14/17

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        27x 1123x 1123x       1123x 2666x   4x       4x         4x           2662x   5x       5x       2657x     1123x   1123x                
import { useIntl } from 'react-intl';
import useIntlKey from '../useIntlKey';
 
/* A hook to enrich the intl object we get from useIntl */
const useKintIntl = (passedIntlKey, passedIntlNS) => {
  const intlObj = useIntl();
  const intlKey = useIntlKey(passedIntlKey, passedIntlNS);
 
  // FormatKintMessage id misses out the top level key part of the path.
  // This works analogously to FormattedKintMessage component
  const formatKintMessage = ({ id, overrideValue, fallbackMessage, ...formatParams }, formatValues) => {
    if (overrideValue) {
      // Version 3 is a breaking change, where labelOverrides must be strings.
      Iif (typeof overrideValue !== 'string') {
        throw new Error('Override values must be strings as of stripes-kint-components ^3.0.0');
      }
 
      Iif (intlObj.messages?.[overrideValue]) {
        // We've been passed a key as an override, use it
        return intlObj.formatMessage({ id: overrideValue, ...formatParams }, formatValues);
      }
      // 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
      Iif (intlObj.messages?.[fallbackMessage]) {
        return intlObj.formatMessage({ id: fallbackMessage, ...formatParams }, formatValues);
      }
 
      return fallbackMessage;
    }
 
    // After all that, render the message from key
    return intlObj.formatMessage({ id: `${intlKey}.${id}`, ...formatParams }, formatValues);
  };
 
  const messageExists = (key) => !!intlObj.messages?.[`${intlKey}.${key}`];
 
  return {
    ...intlObj,
    formatKintMessage,
    messageExists
  };
};
 
export default useKintIntl;