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

Feature/test rechart #723

Open
wants to merge 9 commits into
base: development/1.0
Choose a base branch
from
311 changes: 305 additions & 6 deletions package-lock.json

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -101,10 +101,10 @@
"@fortawesome/react-fontawesome": "^0.1.14",
"@js-temporal/polyfill": "^0.4.4",
"@storybook/preview-api": "^7.6.17",
"downshift": "^7.0.5",
"framer-motion": "^4.1.17",
"polished": "3.4.1",
"pretty-bytes": "^5.6.0",
"downshift": "^7.0.5",
"react": "^17.0.2",
"react-debounce-input": "3.2.2",
"react-dom": "^17.0.2",
Expand All @@ -118,6 +118,7 @@
"react-virtualized": "9.22.3",
"react-virtualized-auto-sizer": "^1.0.5",
"react-window": "^1.8.6",
"recharts": "^2.12.2",
"styled-components": "^5.2.1",
"styled-system": "^5.1.5",
"vega": "^5.17.3",
Expand Down
88 changes: 88 additions & 0 deletions src/lib/components/globalhealthbar/CustomTooltip.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { useEffect, useRef, useState } from 'react';
import styled, { css, useTheme } from 'styled-components';
import { Box } from '../../next';
import { Text, FormattedDateTime, Wrap, spacing } from '../../index';

const TootlipContainer = styled.div<{ tooltipInset }>`
${(props) => {
const theme = useTheme();
return css`
border: 1px solid ${theme.border};
width: 24rem;
color: ${theme.textSecondary};
background-color: ${theme.backgroundLevel1};
border-radius: 4px;
position: absolute;
inset: ${props.tooltipInset.top}px auto auto ${props.tooltipInset.left}px;
padding: ${spacing.r8};
font-size: 1rem;
`;
}}
`;

export const CustomTooltip = (props) => {
const { tooltipData, coordinate } = props;
const tooltipRef = useRef<HTMLDivElement>(null);
const [tooltipInset, setTooltipInset] = useState({ top: 0, left: 0 });

useEffect(() => {
if (tooltipRef.current) {
// console.log('tooltip', tooltipRef.current);
// console.log('tooltipCoord', tooltipRef.current.getBoundingClientRect());
// left and top < 0 = tooltip is out of the screen
// right or bottom > window.innerWidth or window.innerheight = tooltip is out of the screen
Comment on lines +30 to +33
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// console.log('tooltip', tooltipRef.current);
// console.log('tooltipCoord', tooltipRef.current.getBoundingClientRect());
// left and top < 0 = tooltip is out of the screen
// right or bottom > window.innerWidth or window.innerheight = tooltip is out of the screen
// left and top < 0 = tooltip is out of the screen
// right or bottom > window.innerWidth or window.innerheight = tooltip is out of the screen


setTooltipInset({
left: coordinate.x - tooltipRef.current.offsetWidth / 2,
top: coordinate.y + 20,
});
}
}, [tooltipRef.current, coordinate]);
if (tooltipData) {
const { payload, name } = tooltipData[0];
const tooltipName = name.replace('range', '');
return (
<TootlipContainer ref={tooltipRef} tooltipInset={tooltipInset}>
<Box
style={{
display: 'flex',
justifyContent: 'center',
marginBottom: spacing.r8,
}}
>
<Text isEmphazed>View details on Alert Page</Text>
</Box>
<Wrap style={{ flexDirection: 'column', gap: spacing.r8 }}>
<Wrap>
<span>Severity:</span>
<Text>{payload[`${tooltipName}Severity`]}</Text>
</Wrap>
<Wrap>
<span>Start:</span>
<Text>
<FormattedDateTime
format="date-time-second"
value={payload[`range${tooltipName}`][0]}
/>
</Text>
</Wrap>
<Wrap>
<span>End:</span>
<Text>
<FormattedDateTime
format="date-time-second"
value={payload[`range${tooltipName}`][1]}
/>
</Text>
</Wrap>
<Wrap>
<span>Description:</span>
<Text>{payload[`${tooltipName}Description`]}</Text>
</Wrap>
</Wrap>
</TootlipContainer>
);
}

return null;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
import { Bar, BarChart, XAxis, YAxis, Tooltip, Rectangle } from 'recharts';
import { useTheme } from 'styled-components';
import { useEffect, useState } from 'react';
import { useHistoryAlert } from './HistoryProvider';
import { getDataListOptions, getRadius, getTickFormatter } from './utils';
import { HistoryAlertSlider } from './HistorySlider';
import { CustomTooltip } from './CustomTooltip';

export type GlobalHealthProps = {
id: string;
alerts: {
description: string;
startsAt: string;
endsAt: string;
severity: string;
}[];
start: string;
end: string;
};
const barWidth = 600; // width of the bar chart

export function GlobalHealthBar({ id, alerts, start, end }: GlobalHealthProps) {
const history = useHistoryAlert();
const [tooltipData, setTooltipData] = useState(null);
const theme = useTheme();

useEffect(() => {
if (history.selectedDate === 0) {
history.setSelectedDate(endDate);
}
}, []);

const startDate = new Date(start).getTime();
const endDate = new Date(end).getTime();

const data = [
{
start: startDate,
end: endDate,
range: [startDate, endDate],
...alerts.reduce((acc, alert, index) => {
const key = `${alert.severity}${index}`;
acc['range' + key] = [
new Date(alert.startsAt).getTime(),
new Date(alert.endsAt).getTime(),
];
acc[`${key}Severity`] = alert.severity;
acc[`${key}Description`] = alert.description;
return acc;
}, {}),
id,
},
];
const warningKeys = Object.keys(data[0]).filter((key) =>
key.startsWith('rangewarning'),
);
const criticalKeys = Object.keys(data[0]).filter((key) =>
key.startsWith('rangecritical'),
);

const rectangleRenderer = (props, key) => {
const { x, y, height, fill } = props;

const start = props[key][0] < startDate ? startDate : props[key][0];
const end = props[key][1] > endDate ? endDate : props[key][1];
const relativeSize = (end - start) / (endDate - startDate);
return (
<Rectangle
x={x < 0 ? 0 : x}
y={y}
width={relativeSize * barWidth}
height={height}
fill={fill}
radius={getRadius(start, end, startDate, endDate)}
></Rectangle>
);
};

return (
<div
style={{
padding: 60,
position: 'relative',
width: '100%',
}}
>
<HistoryAlertSlider
start={start}
end={end}
startDate={startDate}
endDate={endDate}
/>

<BarChart
width={barWidth}
height={60}
data={data}
layout="vertical"
margin={{ left: 0, right: 0, bottom: 10 }}
maxBarSize={barWidth}
>
<XAxis
allowDataOverflow={true}
dataKey="start"
type="number"
domain={[new Date(start).getTime(), new Date(end).getTime()]}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
domain={[new Date(start).getTime(), new Date(end).getTime()]}
domain={[startDate, endDate]}

tickSize={8}
minTickGap={0}
interval={0}
ticks={getDataListOptions(startDate, endDate)}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
ticks={getDataListOptions(startDate, endDate)}
ticks={getTicks(startDate, endDate)}

tick={(props) => {
const { x, y, payload } = props;
return (
<g transform={`translate(${x},${y})`} overflow={'visible'}>
<text
x={0}
y={0}
dy={12}
textAnchor={'middle'}
fill={theme.textSecondary}
fontSize={11}
>
{getTickFormatter(
startDate,
endDate,
new Date(payload.value),
)}
</text>
</g>
);
}}
tickLine={{ stroke: theme.textSecondary }}
axisLine={false}
/>
{!history.selectedDate && (
<Tooltip
allowEscapeViewBox={{ x: true, y: true }}
offset={20}
isAnimationActive={false}
cursor={false}
content={<CustomTooltip tooltipData={tooltipData}></CustomTooltip>}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: could be self-closed

/>
)}

<YAxis yAxisId={'background'} type="category" hide />
<YAxis yAxisId="clip" type="category" hide></YAxis>
{[...criticalKeys, ...warningKeys].map((key) => (
<YAxis key={`yAxis${key}`} yAxisId={key} type="category" hide />
))}

<Bar
dataKey="range"
fill={theme.statusHealthy}
radius={15}
yAxisId="background"
isAnimationActive={false}
/>

{warningKeys.map((key) => (
<Bar
dataKey={key}
yAxisId={key}
key={key}
onPointerEnter={(e) => {
setTooltipData(e.tooltipPayload);
}}
onPointerLeave={() => setTooltipData(null)}
fill={theme.statusWarning}
shape={(props) => rectangleRenderer(props, key)}
></Bar>
))}

{criticalKeys.map((key) => (
<Bar
dataKey={key}
yAxisId={key}
key={key}
fill={theme.statusCritical}
radius={15}
onPointerEnter={(e) => {
setTooltipData(e.tooltipPayload);
}}
onPointerLeave={() => setTooltipData(null)}
shape={(props) => rectangleRenderer(props, key)}
/>
))}
</BarChart>
</div>
);
}
26 changes: 26 additions & 0 deletions src/lib/components/globalhealthbar/HistoryProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { createContext, useContext, useState } from 'react';

type HistoryAlertContextType = {
selectedDate: number;
setSelectedDate: (date: number) => void;
};
export const HistoryAlertContext = createContext<
HistoryAlertContextType | undefined
>(undefined);

export const HistoryAlertProvider = ({ children }) => {
const [selectedDate, setSelectedDate] = useState<number>(Date.now());
return (
<HistoryAlertContext.Provider value={{ selectedDate, setSelectedDate }}>
{children}
</HistoryAlertContext.Provider>
);
};

export const useHistoryAlert = () => {
const context = useContext(HistoryAlertContext);
if (!context) {
return { selectedDate: null };
}
return context;
};
Comment on lines +3 to +26
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This component is not specific to alerts, it is more a "Point in time" selector/provider that can be used more widely.

Loading
Loading