Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improved Comparative Formula UI #573

Merged
merged 10 commits into from
Jan 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## Not released

- Improved Comparative Formula UI props interface [#573](https://github.com/CartoDB/carto-react/pull/573)

## 1.5

## 1.5.0-alpha.11 (2023-01-18)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import ComparativeFormulaWidgetUI from '../../src/widgets/comparative/ComparativeFormulaWidgetUI';

const SAMPLE_DATA = [
{
value: 1234
},
{
value: 12
},
{
value: 0
}
];

describe('ComparativeFormulaWidgetUI', () => {
test('empty', () => {
const { container } = render(
<ComparativeFormulaWidgetUI data={[]} animated={false} />
);
expect(container).toBeInTheDocument();
});

test('simple', async () => {
render(<ComparativeFormulaWidgetUI data={SAMPLE_DATA} animated={false} />);
expect(await screen.findByText(SAMPLE_DATA[0].value)).toBeInTheDocument();
});

test('multiple', async () => {
render(<ComparativeFormulaWidgetUI data={SAMPLE_DATA} animated={false} />);
const data = await Promise.all(
SAMPLE_DATA.map(async (d) => await screen.findByText(d.value))
);
data.forEach((d) => expect(d).toBeInTheDocument());
});

test('simple - data as object', async () => {
const DATA = { value: 1234 };
render(<ComparativeFormulaWidgetUI data={SAMPLE_DATA} animated={false} />);
expect(await screen.findByText(DATA.value)).toBeInTheDocument();
});

test('with currency formatter', () => {
render(
<ComparativeFormulaWidgetUI
data={SAMPLE_DATA}
animated={false}
formatter={(value) => {
return Intl.NumberFormat('en-US', {
maximumFractionDigits: 2,
minimumFractionDigits: 2,
notation: 'compact',
compactDisplay: 'short'
}).format(value);
}}
/>
);
expect(screen.getByText(/1\.23K/)).toBeInTheDocument();
});
});
2 changes: 1 addition & 1 deletion packages/react-ui/src/custom-components/AnimatedNumber.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ function AnimatedNumber({ enabled, value, options, formatter }) {
animateOnMount: true,
disabled: enabled === false || value === null || value === undefined
};
const animated = useAnimatedNumber(value, { ...defaultOptions, ...options });
const animated = useAnimatedNumber(value || 0, { ...defaultOptions, ...options });
return <span>{formatter ? formatter(animated) : animated}</span>;
}

Expand Down
16 changes: 5 additions & 11 deletions packages/react-ui/src/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,22 +202,16 @@ export type AnimatedNumber = {
formatter: (n: number) => React.ReactNode;
};

export type FormulaLabels = {
export type FormulaData = {
prefix?: React.ReactNode;
suffix?: React.ReactNode;
note?: React.ReactNode;
};

export type FormulaColors = {
[key in keyof FormulaLabels]?: string;
} & {
value?: string;
label?: React.ReactNode;
value: number;
};

export type ComparativeFormulaWidgetUI = {
data: number[];
labels?: FormulaLabels[];
colors?: FormulaColors[];
data: FormulaData[];
colors?: string[];
animated?: boolean;
animationOptions?: AnimationOptions;
formatter?: (n: number) => React.ReactNode;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React from 'react';
import React, { useMemo } from 'react';
import PropTypes from 'prop-types';
import { Box, makeStyles, Typography } from '@material-ui/core';
import { useTheme } from '@material-ui/core';
Expand Down Expand Up @@ -39,17 +39,15 @@ const useStyles = makeStyles((theme) => ({
* Renders a `<ComparativeFormulaWidgetUI />` widget
* <!--
* @param {Object} props
* @param {number[]} props.data
* @param {{ prefix?: string; suffix?: string; note?: string }[]} [props.labels]
* @param {{ prefix?: string; suffix?: string; note?: string; value?: string }[]} [props.colors]
* @param {{ prefix?: React.ReactNode; suffix?: React.ReactNode; label?: React.ReactNode, value: number }[]} [props.data]
* @param {string[]} [props.colors]
* @param {boolean} [props.animated]
* @param {{ duration?: number; animateOnMount?: boolean; initialValue?: number; }} [props.animationOptions]
* @param {(v: number) => React.ReactNode} [props.formatter]
* -->
*/
function ComparativeFormulaWidgetUI({
data = EMPTY_ARRAY,
labels = EMPTY_ARRAY,
colors = EMPTY_ARRAY,
animated = true,
animationOptions,
Expand All @@ -58,93 +56,93 @@ function ComparativeFormulaWidgetUI({
const theme = useTheme();
const classes = useStyles();

function getColor(index) {
return colors[index] || {};
}
function getLabel(index) {
return labels[index] || {};
}
const processedData = useMemo(
() =>
data
.map((d, i) => ({
...d,
color: getColor(colors, i)
}))
.filter((d) => d.value !== undefined),
Comment on lines +62 to +66
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're doing here first .map and then .filter, vs previous .filter > .map. Is it intended @aaranadev?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, we need to remove the undefined values, but we need to assign the correct color index before the element is removed it.

Example:

If the second value is undefined, we need the value after the first to have the third color and not the second.

[data, colors]
);

const isReference = processedData.length > 1;

return (
<div>
{data
.filter((n) => n !== undefined)
.map((d, i) => (
<div className={classes.formulaGroup} key={i}>
<div className={classes.firstLine}>
{getLabel(i).prefix ? (
<Box color={getColor(i).prefix || theme.palette.text.secondary}>
<Typography
color='inherit'
component='span'
variant='subtitle2'
className={[classes.unit, classes.unitBefore].join(' ')}
>
{getLabel(i).prefix}
</Typography>
</Box>
) : null}
<Box color={getColor(i).value}>
<AnimatedNumber
value={d || 0}
enabled={animated}
options={animationOptions}
formatter={formatter}
/>
{processedData.map((d, i) => (
<div className={classes.formulaGroup} key={i}>
<div className={classes.firstLine}>
{d.prefix ? (
<Box color={theme.palette.text.secondary}>
<Typography
color='inherit'
component='span'
variant='subtitle2'
className={[classes.unit, classes.unitBefore].join(' ')}
>
{d.prefix}
</Typography>
</Box>
{getLabel(i).suffix ? (
<Box color={getColor(i).suffix || theme.palette.text.secondary}>
<Typography
color='inherit'
component='span'
variant='subtitle2'
className={classes.unit}
>
{getLabel(i).suffix}
</Typography>
</Box>
) : null}
</div>
{getLabel(i).note ? (
<Box color={getColor(i).note}>
<Typography className={classes.note} color='inherit' variant='caption'>
{getLabel(i).note}
) : null}
<Box fontWeight={isReference && !i ? 'bold' : ''}>
<AnimatedNumber
value={d.value}
enabled={animated}
options={animationOptions}
formatter={formatter}
/>
</Box>
{d.suffix ? (
<Box color={theme.palette.text.secondary}>
<Typography
color='inherit'
component='span'
variant='subtitle2'
className={classes.unit}
>
{d.suffix}
</Typography>
</Box>
) : null}
</div>
))}
{d.label ? (
<Box color={d.color || theme.palette.text.secondary}>
<Typography className={classes.note} color='inherit' variant='caption'>
{d.label}
</Typography>
</Box>
) : null}
</div>
))}
</div>
);
}

function getColor(colors, index) {
return colors[index];
}

ComparativeFormulaWidgetUI.displayName = 'ComparativeFormulaWidgetUI';
ComparativeFormulaWidgetUI.defaultProps = {
data: EMPTY_ARRAY,
labels: EMPTY_ARRAY,
colors: EMPTY_ARRAY,
animated: true,
animationOptions: {},
formatter: IDENTITY_FN
};

const formulaLabelsPropTypes = PropTypes.shape({
prefix: PropTypes.string,
suffix: PropTypes.string,
note: PropTypes.string
});

const formulaColorsPropTypes = PropTypes.shape({
const formulaDataPropTypes = PropTypes.shape({
prefix: PropTypes.string,
suffix: PropTypes.string,
note: PropTypes.string,
value: PropTypes.string
value: PropTypes.number
});

ComparativeFormulaWidgetUI.propTypes = {
data: PropTypes.arrayOf(PropTypes.number).isRequired,
labels: PropTypes.arrayOf(formulaLabelsPropTypes),
colors: PropTypes.arrayOf(formulaColorsPropTypes),
data: PropTypes.arrayOf(formulaDataPropTypes).isRequired,
colors: PropTypes.arrayOf(PropTypes.string),
animated: PropTypes.bool,
animationOptions: animationOptionsPropTypes,
formatter: PropTypes.func
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from 'react';
import ComparativeFormulaWidgetUI from '../../../src/widgets/comparative/ComparativeFormulaWidgetUI';
import { buildReactPropsAsString } from '../../utils'
import { buildReactPropsAsString } from '../../utils';

const options = {
title: 'Custom Components/ComparativeFormulaWidgetUI',
Expand All @@ -11,12 +11,11 @@ export default options;

const Template = (args) => <ComparativeFormulaWidgetUI {...args} />;
const sampleProps = {
data: [1245, 3435.9],
labels: [
{ prefix: '$', suffix: ' sales', note: 'label 1' },
{ prefix: '$', suffix: ' sales', note: 'label 2' }
data: [
{ prefix: '$', suffix: ' sales', label: 'label 1', value: 1245 },
{ prefix: '$', suffix: ' sales', label: 'label 2', value: 3435.9 }
],
colors: [{ note: '#ff9900' }, { note: '#6732a8' }]
colors: ['#ff9900']
};

export const Default = Template.bind({});
Expand Down