1
0
Fork 0
mirror of https://github.com/betagouv/mon-entreprise synced 2025-02-09 04:05:01 +00:00
mon-entreprise/source/components/Value.js
Maxime Quandalle 0663c97204 Utilisation du hook useTranslation de react-i18next
Suppression de notre composant withLanguage qui rajoutait une abstraction
inutile.

Note: de nombreux appels à withTranslation et withLanguage était inutile
car le composant augmenté n'utilisait pas les paramètres fournis (language, t, i18n).
L'utilisation des hooks nous permet de mieux gérer le code mort, car il s'agit
de simples variables dont le non-usage est détecté par l'analyse statique.
2019-09-11 11:17:23 +02:00

103 lines
2.2 KiB
JavaScript

import { React, T } from 'Components'
import { serialiseUnit } from 'Engine/units'
import { memoizeWith } from 'ramda'
import { useTranslation } from 'react-i18next'
const NumberFormat = memoizeWith(
(...args) => JSON.stringify(args),
Intl.NumberFormat
)
export let numberFormatter = ({
style,
maximumFractionDigits,
minimumFractionDigits = 0,
language
}) => value =>
NumberFormat(language, {
style,
currency: 'EUR',
maximumFractionDigits,
minimumFractionDigits
}).format(value)
// let booleanTranslations = { true: '✅', false: '❌' }
let booleanTranslations = {
fr: { true: 'Oui', false: 'Non' },
en: { true: 'Yes', false: 'No' }
}
let style = customStyle => `
font-family: 'Courier New', Courier, monospace;
${customStyle}
`
export default ({
nodeValue: value,
unit,
nilValueSymbol,
maximumFractionDigits,
minimumFractionDigits,
children,
negative,
customCSS = ''
}) => {
const {
i18n: { language }
} = useTranslation()
/* Either an entire rule object is passed, or just the right attributes and the value as a JSX child*/
let nodeValue = value === undefined ? children : value
if (
(nilValueSymbol !== undefined && nodeValue === 0) ||
Number.isNaN(nodeValue) ||
nodeValue === null
)
return (
<span css={style(customCSS)} className="value">
-
</span>
)
let valueType = typeof nodeValue,
unitText =
unit !== null && (typeof unit == 'object' ? serialiseUnit(unit) : unit),
formattedValue =
valueType === 'string' ? (
<T>{nodeValue}</T>
) : valueType === 'object' ? (
nodeValue.nom
) : valueType === 'boolean' ? (
booleanTranslations[language][nodeValue]
) : unitText === '€' ? (
numberFormatter({
style: 'currency',
maximumFractionDigits,
minimumFractionDigits,
language
})(nodeValue)
) : unitText === '%' ? (
numberFormatter({ style: 'percent', maximumFractionDigits: 3 })(
nodeValue
)
) : (
<>
{numberFormatter({
style: 'decimal',
minimumFractionDigits,
maximumFractionDigits
})(nodeValue)}
&nbsp;
{unitText}
</>
)
return nodeValue == undefined ? null : (
<span css={style(customCSS)} className="value">
{negative ? '-' : ''}
{formattedValue}
</span>
)
}