Skip to content

Commit

Permalink
Use next-intl useFormatter
Browse files Browse the repository at this point in the history
  • Loading branch information
terotik committed Nov 28, 2024
1 parent 9413861 commit be94c65
Show file tree
Hide file tree
Showing 12 changed files with 108 additions and 63 deletions.
2 changes: 1 addition & 1 deletion common/paths/preprocess.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export const beautifyValue = (x: number, significantDigits?: number) => {
return rounded;
};

// Use Format number to locale and round to 3 decimals
// DEPRECATED, use useFormatter instead
export const formatNumber = (value, language = 'en') => {
return parseFloat(
Number(value).toPrecision(nrSignificantDigits)
Expand Down
7 changes: 7 additions & 0 deletions components/paths/ActionParameters.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { ParameterInterface } from '@/common/__generated__/paths/graphql';

//import { ActionParameterFragment } from 'common/__generated__/graphql';
import ParameterWidget from './ParameterWidget';
import { useTranslations } from 'next-intl';

const Parameters = styled.div`
display: flex;
Expand All @@ -17,15 +18,21 @@ const Parameters = styled.div`

const ActionParameters = (props: { parameters: ParameterInterface[] }) => {
const { parameters } = props;
const t = useTranslations();
if (!parameters) {
return null;
}
// Separate mandatory on/off parameter with standard id
const actionParameterSwitchParameter = parameters.find(
(param) => param.node && param.id === `${param.node.id}.enabled`
);

const actionParameterSwitch = {
...actionParameterSwitchParameter,
description:
t('action-enabled-description') === 'action-enabled-description'
? actionParameterSwitchParameter?.description
: t('action-enabled-description'),
__typename: 'EnableParameterType',
} as ParameterInterface;
const actionOtherParameters = parameters.filter(
Expand Down
42 changes: 32 additions & 10 deletions components/paths/CategoryCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ import {
CausalGridNodeFragment,
} from 'common/__generated__/paths/graphql';
import { Link } from 'common/links';
import { beautifyValue } from 'common/paths/preprocess';

import ActionParameters from 'components/paths/ActionParameters';
import { useTranslations } from 'next-intl';
import { useFormatter, useTranslations } from 'next-intl';
import { readableColor, transparentize } from 'polished';
import ContentLoader from 'react-content-loader';
import styled, { useTheme } from 'styled-components';
Expand Down Expand Up @@ -176,6 +176,7 @@ const PathsBasicNodeContent = (props: PathsBasicNodeContentProps) => {
const { categoryId, node, onLoaded } = props;
const yearRange = useReactiveVar(yearRangeVar);
const activeGoal = useReactiveVar(activeGoalVar);
const format = useFormatter();
//const [sliceConfig, setSliceConfig] = useState<SliceConfig>(null);

const [emissions, setEmissions] = useState<Emissions>({
Expand Down Expand Up @@ -270,15 +271,24 @@ const PathsBasicNodeContent = (props: PathsBasicNodeContentProps) => {
{emissions.total.latest.value ? (
<SubValue>
<HighlightValue
displayValue={beautifyValue(emissions.total.latest.value) || ''}
displayValue={
emissions.total.latest.value
? format.number(emissions.total.latest.value, {
maximumSignificantDigits: 2,
})
: ''
}
header={`${emissions.total.latest.label} (${emissions.total.latest.year})`}
unit={unit || ''}
size="md"
change={
emissions.total.latest.change != null
? `${
emissions.total.latest.change > 0 ? '+' : ''
}${beautifyValue(emissions.total.latest.change * 100)}%`
}${format.number(emissions.total.latest.change * 100, {
style: 'unit',
unit: 'percent',
})}`
: undefined
}
/>
Expand All @@ -288,7 +298,11 @@ const PathsBasicNodeContent = (props: PathsBasicNodeContentProps) => {
<SubValue>
<HighlightValue
displayValue={
beautifyValue(emissions.total.reference.value) || ''
emissions.total.reference.value
? format.number(emissions.total.reference.value, {
maximumSignificantDigits: 2,
})
: ''
}
header={`${emissions.total.reference.label} (${emissions.total.reference.year})`}
unit={unit || ''}
Expand All @@ -297,7 +311,10 @@ const PathsBasicNodeContent = (props: PathsBasicNodeContentProps) => {
emissions.total.reference.change != null
? `${
emissions.total.reference.change > 0 ? '+' : ''
}${beautifyValue(emissions.total.reference.change * 100)}%`
}${format.number(emissions.total.reference.change * 100, {
style: 'unit',
unit: 'percent',
})}`
: undefined
}
/>
Expand All @@ -318,7 +335,7 @@ type PathsActionNodeContentProps = {
const PathsActionNodeContent = (props: PathsActionNodeContentProps) => {
const { categoryId, node, refetching = false, onLoaded } = props;
const t = useTranslations();

const format = useFormatter();
const yearRange = useReactiveVar(yearRangeVar);
const pathsAction = new PathsActionNode(node);
const impact = pathsAction.getYearlyImpact(yearRange[1]) || 0;
Expand All @@ -334,13 +351,19 @@ const PathsActionNodeContent = (props: PathsActionNodeContentProps) => {
<Values>
<SubValue>
<HighlightValue
displayValue={pathsAction.isEnabled() ? beautifyValue(impact) : '-'}
displayValue={
pathsAction.isEnabled()
? format.number(impact, { maximumSignificantDigits: 2 })
: '-'
}
header={`${t('impact')} ${yearRange[1]}`}
unit={pathsAction.getUnit() || ''}
size="md"
muted={refetching || !pathsAction.isEnabled()}
mutedReason={
!pathsAction.isEnabled() ? 'Not included in scenario' : ''
!pathsAction.isEnabled()
? t('action-not-included-in-scenario')
: ''
}
/>
</SubValue>
Expand Down Expand Up @@ -429,7 +452,6 @@ const CategoryCard = (props: CategoryCardProps) => {
? flattenHTML(mainGoalValue)
: null;

console.log('category indicators', category?.indicators);
return (
<Card>
{group && (
Expand Down
4 changes: 3 additions & 1 deletion components/paths/contentblocks/CategoryPageHeaderBlock.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import PathsActionNode from '@/utils/paths/PathsActionNode';
import { gql, NetworkStatus, useQuery, useReactiveVar } from '@apollo/client';

import HighlightValue from '../HighlightValue';
import { useTranslations } from 'next-intl';

export const GET_CATEGORY_ATTRIBUTE_TYPES = gql`
query GetCategoryAttributeTypes($plan: ID!) {
Expand Down Expand Up @@ -186,6 +187,7 @@ type PathsActionNodeContentProps = {

const PathsActionNodeContent = (props: PathsActionNodeContentProps) => {
const { node, refetching } = props;
const t = useTranslations();
const yearRange = useReactiveVar(yearRangeVar);

const pathsAction = new PathsActionNode(node);
Expand All @@ -202,7 +204,7 @@ const PathsActionNodeContent = (props: PathsActionNodeContentProps) => {
size="lg"
muted={refetching || !pathsAction.isEnabled()}
mutedReason={
!pathsAction.isEnabled() ? 'Not included in scenario' : ''
!pathsAction.isEnabled() ? t('action-not-included-in-scenario') : ''
}
/>
</div>
Expand Down
26 changes: 8 additions & 18 deletions components/paths/graphs/DataTable.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { useTranslations } from 'next-intl';
import { useFormatter, useTranslations } from 'next-intl';
import { Table } from 'reactstrap';
import Styled from 'styled-components';

import type { OutcomeNodeFieldsFragment } from '@/common/__generated__/paths/graphql';
import { formatNumber } from '@/common/paths/preprocess';

// import { useFeatures } from '@/common/instance';
interface DataTableProps {
Expand Down Expand Up @@ -40,6 +39,7 @@ const DataTable = (props: DataTableProps) => {
disclaimer,
} = props;
const t = useTranslations();
const format = useFormatter();
const totalHistoricalValues = node.metric.historicalValues.filter((value) =>
separateYears
? separateYears.includes(value.year)
Expand Down Expand Up @@ -110,23 +110,18 @@ const DataTable = (props: DataTableProps) => {
{subNode.metric.historicalValues.find(
(value) => value.year === metric.year
)
? formatNumber(
? format.number(
subNode.metric.historicalValues.find(
(value) => value.year === metric.year
).value,
t.language,
maximumFractionDigits
{ maximumSignificantDigits: 2 }
)
: '-'}
</td>
))}
{hasTotalValues && (
<td>
{formatNumber(
metric.value,
t.language,
maximumFractionDigits
)}
{format.number(metric.value, { maximumSignificantDigits: 2 })}
</td>
)}
<td
Expand All @@ -145,23 +140,18 @@ const DataTable = (props: DataTableProps) => {
{subNode.metric.forecastValues.find(
(value) => value.year === metric.year
)
? formatNumber(
? format.number(
subNode.metric.forecastValues.find(
(value) => value.year === metric.year
).value,
t.language,
maximumFractionDigits
{ maximumSignificantDigits: 2 }
)
: '-'}
</td>
))}
{hasTotalValues && (
<td>
{formatNumber(
metric.value,
t.language,
maximumFractionDigits
)}
{format.number(metric.value, { maximumSignificantDigits: 2 })}
</td>
)}
<td
Expand Down
5 changes: 2 additions & 3 deletions components/paths/graphs/DimensionalNodePlot.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,12 +69,11 @@ function formatHover(
maximumFractionDigits?: number
) {
const valueFormatter =
// Round to maximumFractionDigits if provided, otherwise 3 significant digits
// Round to maximumFractionDigits if provided, otherwise 2 significant digits
typeof maximumFractionDigits === 'number'
? `.${maximumFractionDigits}f`
? `.${maximumFractionDigits}r`
: '.2r';
//const predText = predLabel ? ` <i>(${predLabel})</i>` : '';

const out: Partial<Plotly.PlotData> = {
/*
hovertemplate: `${name}<br />` +
Expand Down
15 changes: 10 additions & 5 deletions components/paths/graphs/DimensionalPieGraph.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,10 @@ import { useEffect, useMemo, useState } from 'react';
import chroma from 'chroma-js';
import type { DimensionalNodeMetricFragment } from 'common/__generated__/paths/graphql';
import { isEqual } from 'lodash';
import { useTranslations } from 'next-intl';
import { useFormatter, useTranslations } from 'next-intl';
import dynamic from 'next/dynamic';
import styled, { useTheme } from 'styled-components';

import { beautifyValue } from '@/common/paths/preprocess';
import { activeGoalVar } from '@/context/paths/cache';
//import type { InstanceGoal } from 'common/instance';
import { DimensionalMetric, type SliceConfig } from '@/utils/paths/metric';
Expand Down Expand Up @@ -39,6 +38,7 @@ const DimensionalPieGraph = ({
colorChange: colorChangeProp = 0,
}: DimensionalPieGraphProps) => {
const t = useTranslations();
const format = useFormatter();
const theme = useTheme();
const activeGoal = useReactiveVar(activeGoalVar);
const cube = useMemo(() => new DimensionalMetric(metric), [metric]);
Expand Down Expand Up @@ -156,7 +156,8 @@ const DimensionalPieGraph = ({
pieSegmentColors.push(chroma(segmentColor).brighten(colorChange).hex());
pieSegmentHovers.push(
`${yearData.allLabels.find((l) => l.id === rowId)?.label}, ${
datum && beautifyValue(Math.abs(datum), 2)
datum &&
format.number(Math.abs(datum), { maximumSignificantDigits: 2 })
} ${datum && metric.unit.htmlShort}` || ''
);
}
Expand All @@ -170,7 +171,9 @@ const DimensionalPieGraph = ({
return numSum + numValue;
}, 0) || 0;
const percentages = pieSegmentValues.map((value) =>
value ? beautifyValue((value / total) * 100) : null
value
? format.number((value / total) * 100, { maximumSignificantDigits: 2 })
: null
);

// Create new labels with percentages
Expand All @@ -189,7 +192,9 @@ const DimensionalPieGraph = ({
color: theme.graphColors.grey050,
},
showarrow: false,
text: `<b>${beautifyValue(total, 2)}</b>`,
text: `<b>${format.number(total, {
maximumSignificantDigits: 2,
})}</b>`,
x: 0.5,
y: 0.5,
},
Expand Down
10 changes: 7 additions & 3 deletions components/paths/graphs/IndicatorSparkline.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React from 'react';

import type { DatasetComponentOption } from 'echarts/components';
import { useTranslations } from 'next-intl';
import { useTranslations, useFormatter } from 'next-intl';
import styled, { useTheme } from 'styled-components';

import {
Expand Down Expand Up @@ -48,6 +48,7 @@ const IndicatorSparkline = (props: IndicatorSparklineProps) => {
const { indicatorId } = props;
const theme = useTheme();
const t = useTranslations();
const format = useFormatter();
const plan = usePlan();
const { loading, error, data } = useQuery<IndicatorGraphDataQuery>(
GET_INDICATOR_GRAPH_DATA,
Expand Down Expand Up @@ -140,6 +141,9 @@ const IndicatorSparkline = (props: IndicatorSparklineProps) => {
showMaxLabel: true,
hideOverlap: false,
fontSize: 10,
formatter: function (value: number) {
return format.number(value);
},
},
data: allYears,
axisTick: {
Expand All @@ -163,7 +167,7 @@ const IndicatorSparkline = (props: IndicatorSparklineProps) => {
inside: false,
fontSize: 10,
formatter: function (value: number) {
return value.toLocaleString();
return format.number(value);
},
margin: 12,
align: 'right',
Expand Down Expand Up @@ -237,7 +241,7 @@ const IndicatorSparkline = (props: IndicatorSparklineProps) => {
params.forEach((param) => {
const value = param.value[param.dimensionNames[param.encode.y]];
if (value !== null) {
result += `${param.seriesName}: ${value.toLocaleString()} ${
result += `${param.seriesName}: ${format.number(value)} ${
indicator.unit.shortName || indicator.unit.name
}<br/>`;
}
Expand Down
Loading

0 comments on commit be94c65

Please sign in to comment.