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

Updating time labels to be consistent across the app #711

Merged
merged 5 commits into from
Jul 6, 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
6 changes: 5 additions & 1 deletion common/components/charts/AggregateLineChart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { DownloadButton } from '../general/DownloadButton';
import { useBreakpoint } from '../../hooks/useBreakpoint';
import { watermarkLayout } from '../../constants/charts';
import { writeError } from '../../utils/chartError';
import { getFormattedTimeString } from '../../utils/time';
import { LegendLongTerm } from './Legend';
import { ChartBorder } from './ChartBorder';
import { ChartDiv } from './ChartDiv';
Expand Down Expand Up @@ -146,7 +147,10 @@ export const AggregateLineChart: React.FC<AggregateLineProps> = ({
position: 'nearest',
callbacks: {
label: (tooltipItem) => {
return `${tooltipItem.dataset.label}: ${tooltipItem.parsed.y} minutes`;
return `${tooltipItem.dataset.label}: ${getFormattedTimeString(
tooltipItem.parsed.y,
'minutes'
)}`;
},
},
},
Expand Down
6 changes: 5 additions & 1 deletion common/components/charts/SingleDayLineChart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { DownloadButton } from '../general/DownloadButton';
import { useBreakpoint } from '../../hooks/useBreakpoint';
import { watermarkLayout } from '../../constants/charts';
import { writeError } from '../../utils/chartError';
import { getFormattedTimeString } from '../../utils/time';
import { Legend as LegendView } from './Legend';
import { ChartDiv } from './ChartDiv';
import { ChartBorder } from './ChartBorder';
Expand Down Expand Up @@ -128,7 +129,10 @@ export const SingleDayLineChart: React.FC<SingleDayLineProps> = ({
) {
return '';
}
return `${tooltipItem.dataset.label}: ${tooltipItem.parsed.y} minutes`;
return `${tooltipItem.dataset.label}: ${getFormattedTimeString(
tooltipItem.parsed.y,
'minutes'
)}`;
},
afterBody: (tooltipItems) => {
return departureFromNormalString(
Expand Down
68 changes: 17 additions & 51 deletions common/utils/time.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,54 +3,6 @@ import dayjs from 'dayjs';
import { WidgetText } from '../components/widgets/internal/WidgetText';
import { UnitText } from '../components/widgets/internal/UnitText';

type StringifyTimeOptions = {
truncateLeadingHoursZeros?: boolean;
truncateLeadingMinutesZeros?: boolean;
showSeconds?: boolean;
showHours?: boolean;
use12Hour?: boolean;
};

export const stringifyTime = (totalSeconds: number, options: StringifyTimeOptions = {}): string => {
const {
truncateLeadingHoursZeros = true,
truncateLeadingMinutesZeros = false,
showSeconds = false,
showHours = true,
use12Hour = false,
} = options;
let seconds = Math.round(totalSeconds),
minutes = 0,
hours = 0;
const minutesToAdd = Math.floor(seconds / 60);
seconds = seconds % 60;
minutes = minutes += minutesToAdd;
const hoursToAdd = Math.floor(minutes / 60);
minutes = minutes % 60;
hours += hoursToAdd;
const isPM = hours >= 12 && hours < 24;
hours = (use12Hour && hours > 12 ? hours - 12 : hours) % 24;
// We never reassign to secondString but it's nice to destructure this way
// eslint-disable-next-line prefer-const
let [hoursString, minutesString, secondsString] = [hours, minutes, seconds].map((num) =>
num.toString().padStart(2, '0')
);
if (truncateLeadingHoursZeros && hoursString.startsWith('0')) {
hoursString = hoursString.slice(1);
}
if (truncateLeadingMinutesZeros && minutesString.startsWith('0')) {
minutesString = minutesString.slice(1);
}
const timeString = [hoursString, minutesString, secondsString]
.slice(showHours ? 0 : 1)
.slice(0, showSeconds ? 3 : 2)
.join(':');
if (use12Hour) {
return `${timeString} ${isPM ? 'PM' : 'AM'}`;
}
return timeString;
};

export const getTimeUnit = (value: number) => {
const secondsAbs = Math.abs(value);
switch (true) {
Expand All @@ -64,7 +16,7 @@ export const getTimeUnit = (value: number) => {
};

export const getFormattedTimeValue = (value: number) => {
const absValue = Math.abs(value);
const absValue = Math.round(Math.abs(value));
const duration = dayjs.duration(absValue, 'seconds');
switch (true) {
case absValue < 100:
Expand All @@ -78,17 +30,31 @@ export const getFormattedTimeValue = (value: number) => {
return (
<p>
<WidgetText text={duration.format('m')} />
<UnitText text={'m'} /> <WidgetText text={duration.format('s')} />
<UnitText text={'m'} /> <WidgetText text={duration.format('s').padStart(2, '0')} />
<UnitText text={'s'} />
</p>
);
default:
return (
<p>
<WidgetText text={duration.format('H')} />
<UnitText text={'h'} /> <WidgetText text={duration.format('m')} />
<UnitText text={'h'} /> <WidgetText text={duration.format('m').padStart(2, '0')} />
<UnitText text={'m'} />
</p>
);
}
};

export const getFormattedTimeString = (value: number, unit: 'minutes' | 'seconds' = 'seconds') => {
const secondsValue = unit === 'seconds' ? value : value * 60;
const absValue = Math.round(Math.abs(secondsValue));
const duration = dayjs.duration(absValue, 'seconds');
switch (true) {
case absValue < 100:
return `${absValue}s`;
case absValue < 3600:
return `${duration.format('m')}m ${duration.format('s').padStart(2, '0')}s`;
default:
return `${duration.format('H')}h ${duration.format('m').padStart(2, '0')}m`;
}
};
11 changes: 11 additions & 0 deletions modules/slowzones/charts/TotalSlowTime.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { useBreakpoint } from '../../../common/hooks/useBreakpoint';
import { watermarkLayout } from '../../../common/constants/charts';
import { ChartBorder } from '../../../common/components/charts/ChartBorder';
import { ChartDiv } from '../../../common/components/charts/ChartDiv';
import { getFormattedTimeString } from '../../../common/utils/time';

interface TotalSlowTimeProps {
// Data is always all data. We filter it by adjusting the X axis of the graph.
Expand Down Expand Up @@ -145,6 +146,16 @@ export const TotalSlowTime: React.FC<TotalSlowTimeProps> = ({
plugins: {
tooltip: {
intersect: false,
mode: 'index',
position: 'nearest',
callbacks: {
label: (tooltipItem) => {
return `${tooltipItem.dataset.label}: ${getFormattedTimeString(
tooltipItem.parsed.y,
'minutes'
)}`;
},
},
},
title: {
// empty title to set font and leave room for drawTitle fn
Expand Down
13 changes: 3 additions & 10 deletions modules/slowzones/map/SlowSegmentLabel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import React, { useMemo } from 'react';

import type { SlowZoneResponse } from '../../../common/types/dataPoints';
import type { LineMetadata } from '../../../common/types/lines';
import { stringifyTime } from '../../../common/utils/time';

import { getFormattedTimeString } from '../../../common/utils/time';
import type { SlowZoneDirection, SlowZonesSegment } from './segment';
import { DIRECTIONS } from './segment';

Expand All @@ -23,15 +23,7 @@ const SlowZoneLabel: React.FC<SlowZoneLabelProps> = ({
color,
slowZone: { delay, baseline },
}) => {
const delayString = useMemo(
() =>
stringifyTime(delay, {
showHours: false,
showSeconds: true,
truncateLeadingMinutesZeros: true,
}),
[delay]
);
const delayString = useMemo(() => getFormattedTimeString(delay), [delay]);

const fractionOverBaseline = -1 + (delay + baseline) / baseline;

Expand All @@ -40,6 +32,7 @@ const SlowZoneLabel: React.FC<SlowZoneLabelProps> = ({
style={{
flexDirection: isHorizontal && direction === '0' ? 'row-reverse' : 'row',
fontWeight: fractionOverBaseline >= 0.5 ? 'bold' : 'normal',
whiteSpace: 'nowrap',
}}
className={styles.slowZoneLabel}
>
Expand Down