fix: Customize 24h vs 12h time formatting globally (#63)

## What does this Pull Request Do?

Opening up this PR in order to discuss implementation of 12h and 24h time formats. I added the tokens used for formatting (ex: `MMM d h:mm:ss a`) as [constant](4b001cf1dd/packages/app/src/utils.tsx (L155-L158)) in `utils.ts`, in order to avoid copy and pasting these in all the places its needed. 

Then, I used the `userUserPreferences` hook to read what the preference is in the Context, get the required token, and then format the graph accordingly.

At the moment, all the line charts and the logger are changing when the [`initialState`](https://github.com/treypisano/hyperdx/blob/main/packages/app/src/useUserPreferences.tsx#L19) is changed. Of course in the future this will be changed with a UI component, but I wanted to make sure the base implementation is solid first.

## How did I test this?

1. Launch the dev build using docker compose
2. Open up either the logger or dashboard
3. Change initial state from `24hr` to `12hr` , refresh, and observe how it changes
This commit is contained in:
Trey Pisano 2023-11-30 16:28:15 -05:00 committed by GitHub
parent 6f2c75e362
commit e8c26d84fd
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 94 additions and 9 deletions

View file

@ -0,0 +1,6 @@
---
'@hyperdx/api': minor
'@hyperdx/app': minor
---
feat: time format ui addition

View file

@ -19,7 +19,9 @@ import Link from 'next/link';
import pick from 'lodash/pick';
import { AggFn, Granularity, convertGranularityToSeconds } from './ChartUtils';
import { semanticKeyedColor, truncateMiddle } from './utils';
import { semanticKeyedColor, truncateMiddle, TIME_TOKENS } from './utils';
import useUserPreferences, { TimeFormat } from './useUserPreferences';
import api from './api';
function ExpandableLegendItem({ value, entry }: any) {
@ -88,6 +90,9 @@ const MemoChart = memo(function MemoChart({
}, [groupKeys, displayType]);
const sizeRef = useRef<[number, number]>([0, 0]);
const timeFormat: TimeFormat = useUserPreferences().timeFormat;
const tsFormat = TIME_TOKENS[timeFormat];
// Gets the preffered time format from User Preferences, then converts it to a formattable token
return (
<ResponsiveContainer
@ -136,7 +141,7 @@ const MemoChart = memo(function MemoChart({
interval="preserveStartEnd"
scale="time"
type="number"
tickFormatter={tick => format(new Date(tick * 1000), 'MMM d HH:mm')}
tickFormatter={tick => format(new Date(tick * 1000), tsFormat)}
minTickGap={50}
tick={{ fontSize: 12, fontFamily: 'IBM Plex Mono, monospace' }}
/>
@ -193,7 +198,8 @@ const MemoChart = memo(function MemoChart({
});
const HDXLineChartTooltip = (props: any) => {
const tsFormat = 'MMM d HH:mm:ss.SSS';
const timeFormat: TimeFormat = useUserPreferences().timeFormat;
const tsFormat = TIME_TOKENS[timeFormat];
const { active, payload, label } = props;
if (active && payload && payload.length) {
return (

View file

@ -25,6 +25,9 @@ import api from './api';
import { useLocalStorage, usePrevious, useWindowSize } from './utils';
import { useSearchEventStream } from './search';
import { useHotkeys } from 'react-hotkeys-hook';
import { TIME_TOKENS } from './utils';
import useUserPreferences from './useUserPreferences';
import type { TimeFormat } from './useUserPreferences';
import { UNDEFINED_WIDTH } from './tableUtils';
import styles from '../styles/LogTable.module.scss';
@ -273,12 +276,13 @@ export const RawLogTable = memo(
const { width } = useWindowSize();
const isSmallScreen = (width ?? 1000) < 900;
const timeFormat: TimeFormat = useUserPreferences().timeFormat;
const tsFormat = TIME_TOKENS[timeFormat];
const [columnSizeStorage, setColumnSizeStorage] = useLocalStorage<
Record<string, number>
>(`${tableId}-column-sizes`, {});
const tsFormat = 'MMM d HH:mm:ss.SSS';
const tsShortFormat = 'HH:mm:ss';
//once the user has scrolled within 500px of the bottom of the table, fetch more data if there is any
const FETCH_NEXT_PAGE_PX = 500;

View file

@ -37,7 +37,7 @@ export default function SearchTimeRangePicker({
setInputValue,
onSearch,
showLive = false,
timeFormat = '24h',
timeFormat = '12h',
}: {
inputValue: string;
setInputValue: (str: string) => any;

View file

@ -3,6 +3,8 @@ import Link from 'next/link';
import {
Badge,
Button,
ToggleButton,
ToggleButtonGroup,
Container,
Form,
Modal,
@ -13,6 +15,8 @@ import { CopyToClipboard } from 'react-copy-to-clipboard';
import { toast } from 'react-toastify';
import { useState } from 'react';
import useUserPreferences from './useUserPreferences';
import { TimeFormat } from './useUserPreferences';
import AppNav from './AppNav';
import api from './api';
import { isValidUrl } from './utils';
@ -34,6 +38,9 @@ export default function TeamPage() {
const rotateTeamApiKey = api.useRotateTeamApiKey();
const saveWebhook = api.useSaveWebhook();
const deleteWebhook = api.useDeleteWebhook();
const setTimeFormat = useUserPreferences().setTimeFormat;
const timeFormat = useUserPreferences().timeFormat;
const handleTimeButtonClick = (val: TimeFormat) => setTimeFormat(val);
const hasAllowedAuthMethods =
team?.allowedAuthMethods != null && team?.allowedAuthMethods.length > 0;
@ -442,6 +449,42 @@ export default function TeamPage() {
</Modal.Body>
</Modal>
</div>
<div className="text-muted my-2">
Note: Only affects your own view and does not propagate to other
team members.
</div>
<div>
<h2 className="mt-5">Time Format</h2>
<ToggleButtonGroup
type="radio"
value={timeFormat}
onChange={handleTimeButtonClick}
name="buttons"
>
<ToggleButton
id="tbg-btn-1"
value="24h"
variant={
timeFormat === '24h'
? 'outline-success'
: 'outline-secondary'
}
>
24h
</ToggleButton>
<ToggleButton
id="tbg-btn-2"
value="12h"
variant={
timeFormat === '12h'
? 'outline-success'
: 'outline-secondary'
}
>
12h
</ToggleButton>
</ToggleButtonGroup>
</div>
</>
)}
</Container>

View file

@ -1,5 +1,5 @@
import React, { useContext, useState } from 'react';
import React, { useContext, useState, useEffect } from 'react';
import { useLocalStorage } from './utils';
export type TimeFormat = '12h' | '24h';
export const UserPreferences = React.createContext({
@ -14,16 +14,37 @@ export const UserPreferencesProvider = ({
}: {
children: React.ReactNode;
}) => {
const [storedTF, setTF] = useLocalStorage('timeFormat', '24h');
const setTimeFormat = (timeFormat: TimeFormat) => {
setState(state => ({ ...state, timeFormat }));
setTF(timeFormat);
};
const initState = {
isUTC: false,
timeFormat: '24h' as TimeFormat,
setTimeFormat: (timeFormat: TimeFormat) =>
setState(state => ({ ...state, timeFormat })),
setTimeFormat,
setIsUTC: (isUTC: boolean) => setState(state => ({ ...state, isUTC })),
};
const [state, setState] = useState(initState);
// This only runs once in order to grab and set the initial timeFormat from localStorage
useEffect(() => {
if (typeof window === 'undefined') {
return;
}
try {
let timeFormat = window.localStorage.getItem('timeFormat') as TimeFormat;
if (timeFormat !== null) timeFormat = JSON.parse(timeFormat);
if (timeFormat !== null) {
setState(state => ({ ...state, timeFormat }));
}
} catch (error) {
console.log(error);
}
}, []);
return (
<UserPreferences.Provider value={state}>
{children}

View file

@ -151,6 +151,11 @@ export const useDebounce = <T,>(
return debouncedValue;
};
export const TIME_TOKENS = {
'12h': 'MMM d h:mm:ss a',
'24h': 'MMM d HH:mm:ss.SSS',
};
export function useLocalStorage<T>(key: string, initialValue: T) {
// State to store our value
// Pass initial state function to useState so logic is only executed once