Skip to content

Commit

Permalink
fix: Customize 24h vs 12h time formatting globally (#63)
Browse files Browse the repository at this point in the history
## 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](https://github.com/treypisano/hyperdx/blob/4b001cf1ddfa9047e5818023e77ca0eef280255b/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
  • Loading branch information
treypisano committed Nov 30, 2023
1 parent 6f2c75e commit e8c26d8
Show file tree
Hide file tree
Showing 7 changed files with 94 additions and 9 deletions.
6 changes: 6 additions & 0 deletions .changeset/three-forks-eat.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@hyperdx/api': minor
'@hyperdx/app': minor
---

feat: time format ui addition
12 changes: 9 additions & 3 deletions packages/app/src/HDXLineChart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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' }}
/>
Expand Down Expand Up @@ -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 (
Expand Down
6 changes: 5 additions & 1 deletion packages/app/src/LogTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion packages/app/src/SearchTimeRangePicker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export default function SearchTimeRangePicker({
setInputValue,
onSearch,
showLive = false,
timeFormat = '24h',
timeFormat = '12h',
}: {
inputValue: string;
setInputValue: (str: string) => any;
Expand Down
43 changes: 43 additions & 0 deletions packages/app/src/TeamPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import Link from 'next/link';
import {
Badge,
Button,
ToggleButton,
ToggleButtonGroup,
Container,
Form,
Modal,
Expand All @@ -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';
Expand All @@ -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;
Expand Down Expand Up @@ -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>
Expand Down
29 changes: 25 additions & 4 deletions packages/app/src/useUserPreferences.tsx
Original file line number Diff line number Diff line change
@@ -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({
Expand All @@ -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}
Expand Down
5 changes: 5 additions & 0 deletions packages/app/src/utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit e8c26d8

Please sign in to comment.