From 672b0f9101514c0196f0cefd547baac208b75350 Mon Sep 17 00:00:00 2001 From: Justin Campbell Date: Thu, 21 Jan 2021 11:55:40 -0500 Subject: [PATCH] Refactir timeToBackgroundColor and inject background color into props --- .../LastUpdatedCell/LastUpdatedCell.js | 50 ++++++++++++------- 1 file changed, 33 insertions(+), 17 deletions(-) diff --git a/src/components/LastUpdatedCell/LastUpdatedCell.js b/src/components/LastUpdatedCell/LastUpdatedCell.js index 8ffc778..9bce6b4 100644 --- a/src/components/LastUpdatedCell/LastUpdatedCell.js +++ b/src/components/LastUpdatedCell/LastUpdatedCell.js @@ -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 ( - + ); -} +}; 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": {}, }; \ No newline at end of file