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

Comparative Formula Widget #504

Merged
merged 19 commits into from
Oct 28, 2022
Merged
Show file tree
Hide file tree
Changes from 6 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

- Implement ComparativeFormulaWidgetUI [#504](https://github.com/CartoDB/carto-react/pull/504)

## 1.5

### 1.5.0-alpha.4 (2022-10-14)
Expand Down
3 changes: 2 additions & 1 deletion packages/react-ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,8 @@
"webpack-cli": "^4.5.0"
},
"dependencies": {
"@babel/runtime": "^7.13.9"
"@babel/runtime": "^7.13.9",
"use-animate-number": "^1.0.5"
VictorVelarde marked this conversation as resolved.
Show resolved Hide resolved
},
"peerDependencies": {
"@carto/react-core": "^1.5.0-alpha.4",
Expand Down
51 changes: 51 additions & 0 deletions packages/react-ui/src/custom-components/AnimatedNumber.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import React from 'react';
import PropTypes from 'prop-types';
import useAnimateNumber from 'use-animate-number';

function countDecimals(n) {
if (Math.floor(n) === n) return 0;
return String(n).split('.')[1]?.length || 0;
}

/**
* Renders a <AnimatedNumber /> widget
* @param {Object} props
* @param {boolean} props.enabled
* @param {number} props.value
* @param {{ duration?: number; enterance?: boolean; direct?: boolean; disabled?: boolean; decimals?: number; }} [props.options]
* @param {(n: number) => React.ReactNode} [props.formatter]
*/
function AnimatedNumber({ enabled, value, options, formatter }) {
const defaultOptions = {
direct: true,
decimals: countDecimals(value),
disabled: enabled === false || value === null || value === undefined
};
const [animated] = useAnimateNumber(value, { ...defaultOptions, ...options });
return <span>{formatter ? formatter(animated) : animated}</span>;
}

AnimatedNumber.displayName = 'AnimatedNumber';
AnimatedNumber.defaultProps = {
enabled: true,
value: 0,
options: {},
formatter: null
};

export const animationOptionsPropTypes = PropTypes.shape({
duration: PropTypes.number,
enterance: PropTypes.bool,
direct: PropTypes.bool,
disabled: PropTypes.bool,
decimals: PropTypes.number
});

AnimatedNumber.propTypes = {
enabled: PropTypes.bool,
value: PropTypes.number.isRequired,
options: animationOptionsPropTypes,
formatter: PropTypes.func
};

export default AnimatedNumber;
2 changes: 2 additions & 0 deletions packages/react-ui/src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { CHART_TYPES } from './widgets/TimeSeriesWidgetUI/utils/constants';
import TableWidgetUI from './widgets/TableWidgetUI/TableWidgetUI';
import NoDataAlert from './widgets/NoDataAlert';
import FeatureSelectionWidgetUI from './widgets/FeatureSelectionWidgetUI';
import ComparativeFormulaWidgetUI from './widgets/ComparativeFormulaWidgetUI';

export {
cartoThemeOptions,
Expand All @@ -42,6 +43,7 @@ export {
TableWidgetUI,
LegendWidgetUI,
RangeWidgetUI,
ComparativeFormulaWidgetUI,
LEGEND_TYPES,
NoDataAlert,
LegendCategories,
Expand Down
2 changes: 2 additions & 0 deletions packages/react-ui/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import ScatterPlotWidgetUI from './widgets/ScatterPlotWidgetUI';
import TimeSeriesWidgetUI from './widgets/TimeSeriesWidgetUI/TimeSeriesWidgetUI';
import FeatureSelectionWidgetUI from './widgets/FeatureSelectionWidgetUI';
import RangeWidgetUI from './widgets/RangeWidgetUI';
import ComparativeFormulaWidgetUI from './widgets/ComparativeFormulaWidgetUI';
import { CHART_TYPES } from './widgets/TimeSeriesWidgetUI/utils/constants';
import TableWidgetUI from './widgets/TableWidgetUI/TableWidgetUI';
import NoDataAlert from './widgets/NoDataAlert';
Expand Down Expand Up @@ -42,6 +43,7 @@ export {
ScatterPlotWidgetUI,
TimeSeriesWidgetUI,
FeatureSelectionWidgetUI,
ComparativeFormulaWidgetUI,
CHART_TYPES as TIME_SERIES_CHART_TYPES,
TableWidgetUI,
LegendWidgetUI,
Expand Down
36 changes: 36 additions & 0 deletions packages/react-ui/src/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,3 +188,39 @@ export type LegendRamp = {
colors?: string | string[] | number[][];
};
};

export type AnimationOptions = Partial<{
duration: number;
enterance: boolean;
direct: boolean;
disabled: boolean;
decimals: number;
}>;

export type AnimatedNumber = {
enabled: boolean;
value: number;
options?: AnimationOptions;
formatter: (n: number) => React.ReactNode;
};

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

export type FormulaColors = {
[key in keyof FormulaLabels]?: string;
} & {
value?: string;
};

export type ComparativeFormulaWidgetUI = {
data: number[];
labels?: FormulaLabels[];
colors?: FormulaColors[];
animated?: boolean;
animationOptions?: AnimationOptions;
formatter?: (n: number) => React.ReactNode;
};
152 changes: 152 additions & 0 deletions packages/react-ui/src/widgets/ComparativeFormulaWidgetUI.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
import React from 'react';
import PropTypes from 'prop-types';
import { Box, makeStyles, Typography } from '@material-ui/core';
import { useTheme } from '@material-ui/core';
import AnimatedNumber, {
animationOptionsPropTypes
} from '../custom-components/AnimatedNumber';

const IDENTITY_FN = (v) => v;
const EMPTY_ARRAY = [];

const useStyles = makeStyles((theme) => ({
formulaChart: {},
formulaGroup: {
'& + $formulaGroup': {
marginTop: theme.spacing(2)
}
},
firstLine: {
margin: 0,
...theme.typography.h5,
fontWeight: Number(theme.typography.fontWeightMedium),
color: theme.palette.text.primary,
display: 'flex'
},
unit: {
marginLeft: theme.spacing(0.5)
},
unitBefore: {
marginLeft: 0,
marginRight: theme.spacing(0.5)
},
note: {
display: 'inline-block',
marginTop: theme.spacing(0.5)
}
}));

/**
* 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 {boolean} [props.animated]
* @param {Object} [props.animationOptions]
* @param {(v: number) => React.ReactNode} [props.formatter]
*/
function ComparativeFormulaWidgetUI({
data = EMPTY_ARRAY,
labels = EMPTY_ARRAY,
colors = EMPTY_ARRAY,
animated = true,
animationOptions,
formatter = IDENTITY_FN
}) {
const theme = useTheme();
const classes = useStyles();

function getColor(index) {
return colors[index] || {};
}
function getLabel(index) {
return labels[index] || {};
}

return (
<div className={classes.formulaChart}>
{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}
/>
</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}
</Typography>
</Box>
) : null}
</div>
))}
</div>
);
}

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({
prefix: PropTypes.string,
suffix: PropTypes.string,
note: PropTypes.string,
value: PropTypes.string
});

ComparativeFormulaWidgetUI.propTypes = {
data: PropTypes.arrayOf(PropTypes.number).isRequired,
labels: PropTypes.arrayOf(formulaLabelsPropTypes),
colors: PropTypes.arrayOf(formulaColorsPropTypes),
animated: PropTypes.bool,
animationOptions: animationOptionsPropTypes,
formatter: PropTypes.func
};

export default ComparativeFormulaWidgetUI;
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import React from 'react';
import ComparativeFormulaWidgetUI from '../../../src/widgets/ComparativeFormulaWidgetUI';

const options = {
title: 'Custom Components/ComparativeFormulaWidgetUI',
component: ComparativeFormulaWidgetUI
};

export default options;

const Template = (args) => <ComparativeFormulaWidgetUI {...args} />;

export const Default = Template.bind({});
Default.args = {
data: [1245, 3435.9],
labels: [
{ prefix: '$', suffix: ' sales', note: 'label 1' },
{ prefix: '$', suffix: ' sales', note: 'label 2' }
],
colors: [{ note: '#ff9900' }, { note: '#6732a8' }]
};
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -17667,6 +17667,11 @@ url@^0.11.0:
punycode "1.3.2"
querystring "0.2.0"

use-animate-number@^1.0.5:
version "1.0.5"
resolved "https://registry.yarnpkg.com/use-animate-number/-/use-animate-number-1.0.5.tgz#c224fd3ce81d0b563a5215d714aaa98ad8c67470"
integrity sha512-zAavKn83Z6V6wlatpEp+fmbAS6vMA3tISudw04eSeyXc0AZG98JDDK1U+gmMxV/oATcub+ijgrENMPqHue+SiA==

use@^3.1.0:
version "3.1.1"
resolved "https://registry.yarnpkg.com/use/-/use-3.1.1.tgz#d50c8cac79a19fbc20f2911f56eb973f4e10070f"
Expand Down