From 573d6dcb518682b6787e027e01c07ca305ee5737 Mon Sep 17 00:00:00 2001 From: Patrick Browne Date: Tue, 23 Aug 2022 12:53:01 +0200 Subject: [PATCH] feat: Use currency formatter if measure is a currency --- app/configurator/components/ui-helpers.spec.ts | 13 +++++++++++++ app/configurator/components/ui-helpers.ts | 14 +++++++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/app/configurator/components/ui-helpers.spec.ts b/app/configurator/components/ui-helpers.spec.ts index 70d1eebe15..f75140e1b8 100644 --- a/app/configurator/components/ui-helpers.spec.ts +++ b/app/configurator/components/ui-helpers.spec.ts @@ -56,6 +56,14 @@ describe("useDimensionFormatters", () => { isNumerical: true, isKeyDimension: false, } as DimensionMetaDataFragment, + { + iri: "iri-currency", + isNumerical: true, + isKeyDimension: false, + isCurrency: true, + currencyExponent: 1, + __typename: "Measure", + } as DimensionMetaDataFragment, ]) ); return { formatters }; @@ -75,6 +83,11 @@ describe("useDimensionFormatters", () => { const { formatters } = setup(); expect(formatters["iri-number"]("2.33333")).toEqual("2,33"); }); + + it("should work with currencies", () => { + const { formatters } = setup(); + expect(formatters["iri-currency"]("20002.3333")).toEqual("20'002,3"); + }); }); describe("time intervals", () => { diff --git a/app/configurator/components/ui-helpers.ts b/app/configurator/components/ui-helpers.ts index 162d09f1dc..c4027242a9 100644 --- a/app/configurator/components/ui-helpers.ts +++ b/app/configurator/components/ui-helpers.ts @@ -51,6 +51,7 @@ import { ChartProps } from "../../charts/shared/use-chart-state"; import { Observation } from "../../domain/data"; import { DimensionMetaDataFragment, + Measure, TemporalDimension, TimeUnit, } from "../../graphql/query-hooks"; @@ -149,9 +150,16 @@ const namedNodeFormatter = (d: DimensionMetaDataFragment) => { }; }; +const currencyFormatter = (d: Measure, locale: string) => { + const formatLocale = getD3FormatLocale(locale); + // Use the currency exponent from the dimension, with default 2 + return formatLocale.format(`,.${d.currencyExponent || 2}f`); +}; + export const useDimensionFormatters = ( dimensions: DimensionMetaDataFragment[] ) => { + const locale = useLocale(); const formatNumber = useFormatNumber() as unknown as ( d: number | string ) => string; @@ -163,7 +171,11 @@ export const useDimensionFormatters = ( dimensions.map((d) => { let formatter: (s: any) => string; if (d.__typename === "Measure") { - formatter = formatNumber; + if (d.isCurrency) { + formatter = currencyFormatter(d, locale); + } else { + formatter = formatNumber; + } } else if (d.__typename === "TemporalDimension") { formatter = dateFormatterFromDimension( d,