Skip to content

Commit

Permalink
Refactir timeToBackgroundColor and inject background color into props
Browse files Browse the repository at this point in the history
  • Loading branch information
campb303 committed Jan 21, 2021
1 parent 813438a commit 672b0f9
Showing 1 changed file with 33 additions and 17 deletions.
50 changes: 33 additions & 17 deletions src/components/LastUpdatedCell/LastUpdatedCell.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,51 +4,67 @@ import { red } from '@material-ui/core/colors';
import RelativeTime from 'react-relative-time';
import ItemTableCell from '../ItemTableCell';

export default function LastUpdatedCell({ time, reactTableCellProps, classes }) {
/**
* Returns a color showing how old an item is.
* @param {string} time ISO 8601 formatted time string.
* @example
* // Returns "#e57373"
* timeToBackgroundColor("2021-01-04T11:47:00-0500")
* @returns {string} Hex color code.
*/
const timeToBackgroundColor = (time) => {
const lastUpdated = new Date(time).getTime();
const now = new Date().getTime();
const timeDelta = now - lastUpdated;

const day = 24 * 60 * 60 * 1000;
const week = day * 7;
const month = week * 4;

let backgroundColor = "white";

// 1-6 days old
if (timeDelta > day && timeDelta <= week) {
backgroundColor = red[100]
backgroundColor = red[100];
}
// 7-28 days old
else if (timeDelta > week && timeDelta <= month) {
backgroundColor = red[300]
backgroundColor = red[300];
}
// 29+ days old
else if (timeDelta > month) {
backgroundColor = red[500]
backgroundColor = red[500];
}

return backgroundColor;
}

export default function LastUpdatedCell({ time, reactTableCellProps }) {
// Insert the calculated background color into props so it isn't overriden.
// Inspired by: https://github.com/mui-org/material-ui/issues/19479
reactTableCellProps = {
...reactTableCellProps,
style: {
...reactTableCellProps.style,
backgroundColor: timeToBackgroundColor(time)
}
};

return (
<ItemTableCell
classes={classes}
// Expands table cell props to allow access to style props.
{...reactTableCellProps}
// Expands style prop of table cell to allow addtion of custom styling without losing default styling.
style={{ ...reactTableCellProps.style, backgroundColor: backgroundColor }}
backgroundColor={backgroundColor}
>
<ItemTableCell TableCellProps={reactTableCellProps}>
<RelativeTime value={time} />
</ItemTableCell>
);
}
};

LastUpdatedCell.propTypes = {
/** Time value in ISO8601. */
"time": PropTypes.string,
/** Props passed from ItemTable. */
"reactTableProps": PropTypes.object,
/**Object that passes classes to the component. */
"classes": PropTypes.object,

};

LastUpdatedCell.defaultProps = {
"time": "",
"reactTableProps": {},
"classes": {},
};

0 comments on commit 672b0f9

Please sign in to comment.