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

feat: Moving Event graph to Chart.js for more interactions #427

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -30,6 +30,9 @@
"@tabler/icons-react": "^3.3.0",
"@types/js-cookie": "^3.0.3",
"axios": "^1.4.0",
"chart.js": "^4.4.7",
"chartjs-plugin-annotation": "^3.1.0",
"chartjs-plugin-zoom": "^2.2.0",
"dayjs": "^1.11.10",
"embla-carousel-react": "7.1.0",
"html2canvas": "^1.4.1",
@@ -48,6 +51,7 @@
"protobufjs": "^7.2.5",
"react": "^18.2.0",
"react-beautiful-dnd": "^13.1.1",
"react-chartjs-2": "^5.3.0",
"react-dom": "^18.2.0",
"react-error-boundary": "^4.0.10",
"react-grid-layout": "^1.4.4",
67 changes: 67 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions src/pages/Correlation/components/SavedCorrelationItem.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Stack, Box, Button, Text, px, Code } from '@mantine/core';
import { IconClock, IconEye, IconEyeOff, IconTrash, IconX } from '@tabler/icons-react';
import { useState, useCallback, Fragment } from 'react';
import { useState, useCallback, Fragment, FC } from 'react';
import classes from '../styles/SavedCorrelationItem.module.css';
import { Correlation } from '@/@types/parseable/api/correlation';
import dayjs from 'dayjs';
@@ -42,7 +42,7 @@ interface JoinConfig {
joinConditions: JoinCondition[];
}

const SelectedFields: React.FC<{ tableConfigs: TableConfig[] }> = ({ tableConfigs }) => {
const SelectedFields: FC<{ tableConfigs: TableConfig[] }> = ({ tableConfigs }) => {
const fields = tableConfigs.flatMap((config) =>
config.selectedFields.map((field) => ({
key: `${config.tableName}-${field}`,
@@ -63,7 +63,7 @@ const SelectedFields: React.FC<{ tableConfigs: TableConfig[] }> = ({ tableConfig
);
};

const JoinConditions: React.FC<{ joinConfig: JoinConfig }> = ({ joinConfig }) => {
const JoinConditions: FC<{ joinConfig: JoinConfig }> = ({ joinConfig }) => {
return (
<>
{joinConfig.joinConditions.map((join, index) => {
201 changes: 201 additions & 0 deletions src/pages/Stream/components/AreaChartComponent.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
import React from 'react';
import { Line } from 'react-chartjs-2';
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Tooltip,
ChartOptions,
Filler,
} from 'chart.js';
import Annotation from 'chartjs-plugin-annotation';
import zoomPlugin from 'chartjs-plugin-zoom';
import { HumanizeNumber } from '@/utils/formatBytes';
import timeRangeUtils from '@/utils/timeRangeUtils';

const { makeTimeRangeLabel } = timeRangeUtils;

ChartJS.register(CategoryScale, LinearScale, PointElement, LineElement, Tooltip, Annotation, Filler, zoomPlugin);

interface ChartComponentProps {
graphData: any;
avgEventCount: number;
setTimeRangeFromGraph: (minute: string) => void;
hasData: boolean;
onZoomOrPanComplete: (startTime: string, endTime: string) => void;
}

const AreaChartComponent: React.FC<ChartComponentProps> = ({
graphData,
avgEventCount,
setTimeRangeFromGraph,
hasData,
onZoomOrPanComplete,
}) => {
const chartData = {
labels: graphData.map((item: any) => item.minute),
datasets: [
{
label: 'Events',
data: graphData.map((item: any) => item.events),
fill: true,
// backgroundColor: 'rgba(99, 102, 241, 0.5)',
borderColor: 'rgb(99, 102, 241)',
borderWidth: 1.25,
pointRadius: 2.5,
pointBorderWidth: 1,
pointBackgroundColor: 'rgb(99, 102, 241)',
tension: 0.4,
backgroundColor: (context: any) => {
const ctx = context.chart.ctx;
const gradient = ctx.createLinearGradient(0, 0, 0, context.chart.height);
gradient.addColorStop(0, 'rgba(99, 102, 241, 0.5)');
gradient.addColorStop(1, 'rgba(99, 102, 241, 0)');
return gradient;
},
},
],
};

const handleRangeComplete = (chart: any) => {
const { min, max } = chart.scales.x;
const startIndex = Math.floor(min);
const endIndex = Math.ceil(max);
// Get the time range for the zoomed area
if (startIndex >= 0 && endIndex < graphData.length) {
const startTime = graphData[startIndex].startTime;
const endTime = graphData[endIndex].endTime;
onZoomOrPanComplete(startTime, endTime);
}
};

const chartOptions: ChartOptions<'line'> = {
responsive: true,
maintainAspectRatio: false,
plugins: {
tooltip: {
position: 'nearest',
backgroundColor: 'white',
titleColor: 'black',
bodyColor: 'black',
footerColor: 'black',
borderColor: 'rgb(99, 102, 241)',
borderWidth: 1,
callbacks: {
title: (tooltipItems: any) => {
const index = tooltipItems[0].dataIndex;
const { startTime, endTime } = graphData[index];
return makeTimeRangeLabel(new Date(startTime), new Date(endTime));
},
label: (tooltipItem: any) => {
return `Events: ${new Intl.NumberFormat('en-US').format(tooltipItem.raw)}`;
},
// footer: (tooltipItems: any) => {
// const index = tooltipItems[0].dataIndex;
// const { aboveAvgPercent } = graphData[index];
// const isAboveAvg = aboveAvgPercent > 0;
// return `${isAboveAvg ? '+' : ''}${aboveAvgPercent}% ${
// isAboveAvg ? 'above' : 'below'
// } average in the given time-range`;
// },
},
},
annotation: {
annotations: {
avgLine: {
type: 'line',
yMin: avgEventCount,
yMax: avgEventCount,
borderColor: 'rgb(156, 163, 175)',
borderWidth: 1,
label: {
content: 'Avg',
position: 'start',
backgroundColor: 'transparent',
color: 'black',
font: {
size: 12,
},
},
},
},
},
zoom: {
limits: {
x: { min: 'original', max: 'original' },
y: { min: 'original', max: 'original' },
},
zoom: {
wheel: {
enabled: false,
},
pinch: {
enabled: true,
},
mode: 'x',
drag: {
enabled: true,
backgroundColor: 'rgba(99, 102, 241, 0.1)',
},
onZoomComplete: ({ chart }) => {
handleRangeComplete(chart);
},
},
},
},
scales: {
x: {
type: 'category',
display: false,
},
y: {
display: hasData,
ticks: {
count: 2,
callback: (value: string | number) => {
const numericValue = typeof value === 'number' ? value : parseFloat(value);
return HumanizeNumber(numericValue);
},
},
grid: {
drawTicks: false,
},
},
},
elements: {
line: {
borderWidth: 1.25,
},
point: {
radius: 2.5,
hitRadius: 6,
},
},
layout: {
padding: {
top: 0,
},
},
hover: {
mode: 'nearest',
axis: 'x',
intersect: false,
},
onClick: (_event, elements) => {
if (elements && elements.length > 0) {
const index = elements[0].index;
setTimeRangeFromGraph(graphData[index].minute);
}
},
};

return (
<div style={{ height: '100%', width: '100%', cursor: 'pointer' }}>
<Line data={chartData} options={chartOptions} />
</div>
);
};

export default AreaChartComponent;
62 changes: 12 additions & 50 deletions src/pages/Stream/components/EventTimeLineGraph.tsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,16 @@
import { Paper, Skeleton, Stack, Text } from '@mantine/core';
import { Skeleton, Stack, Text } from '@mantine/core';
import classes from '../styles/EventTimeLineGraph.module.css';
import { useGraphData } from '@/hooks/useQueryResult';
import { useCallback, useEffect, useMemo, useState } from 'react';
import dayjs from 'dayjs';
import { ChartTooltipProps, AreaChart } from '@mantine/charts';
import { HumanizeNumber } from '@/utils/formatBytes';
import { logsStoreReducers, useLogsStore } from '../providers/LogsProvider';
import { appStoreReducers, useAppStore } from '@/layouts/MainLayout/providers/AppProvider';
import { LogsResponseWithHeaders } from '@/@types/parseable/api/query';
import _ from 'lodash';
import timeRangeUtils from '@/utils/timeRangeUtils';
import { useStreamStore } from '../providers/StreamProvider';
import AreaChartComponent from './AreaChartComponent';

const { setTimeRange } = appStoreReducers;
const { makeTimeRangeLabel } = timeRangeUtils;
const { getCleanStoreForRefetch } = logsStoreReducers;

type CompactInterval = 'minute' | 'day' | 'hour' | 'quarter-hour' | 'half-hour' | 'month';
@@ -132,31 +129,6 @@ const parseGraphData = (data: LogsResponseWithHeaders | undefined, avg: number,
return parsedData;
};

function ChartTooltip({ payload }: ChartTooltipProps) {
if (!payload || (Array.isArray(payload) && payload.length === 0)) return null;

const { aboveAvgPercent, events, startTime, endTime } = payload[0]?.payload as GraphTickItem;
const isAboveAvg = aboveAvgPercent > 0;
const label = makeTimeRangeLabel(startTime.toDate(), endTime.toDate());

return (
<Paper px="md" py="sm" withBorder shadow="md" radius="md">
<Text fw={600} mb={5}>
{label}
</Text>
<Stack style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
<Text>Events</Text>
<Text>{events}</Text>
</Stack>
<Stack mt={4} style={{ flexDirection: 'row' }}>
<Text size="sm" c={isAboveAvg ? 'red.6' : 'green.8'}>{`${isAboveAvg ? '+' : ''}${aboveAvgPercent}% ${
isAboveAvg ? 'above' : 'below'
} average in the given time-range`}</Text>
</Stack>
</Paper>
);
}

const EventTimeLineGraph = () => {
const { fetchGraphDataMutation } = useGraphData();
const [currentStream] = useAppStore((store) => store.currentStream);
@@ -223,27 +195,17 @@ const EventTimeLineGraph = () => {
w={isLoading ? '98%' : '100%'}
style={isLoading ? { marginLeft: '1.8rem', alignSelf: 'center' } : !hasData ? { marginLeft: '1rem' } : {}}>
{hasData ? (
<AreaChart
h="100%"
w="100%"
data={graphData}
dataKey="minute"
series={[{ name: 'events', color: 'indigo.5', label: 'Events' }]}
tooltipProps={{
content: ({ label, payload }) => <ChartTooltip label={label} payload={payload} />,
position: { y: -20 },
<AreaChartComponent
graphData={graphData}
avgEventCount={avgEventCount}
setTimeRangeFromGraph={setTimeRangeFromGraph}
hasData={graphData.length > 0}
onZoomOrPanComplete={(start, end) => {
setLogStore((store) => getCleanStoreForRefetch(store));
setAppStore((store) =>
setTimeRange(store, { type: 'custom', startTime: dayjs(start), endTime: dayjs(end) }),
);
}}
valueFormatter={(value) => new Intl.NumberFormat('en-US').format(value)}
withXAxis={false}
withYAxis={hasData}
yAxisProps={{ tickCount: 2, tickFormatter: (value) => `${HumanizeNumber(value)}` }}
referenceLines={[{ y: avgEventCount, color: 'gray.5', label: 'Avg' }]}
tickLine="none"
areaChartProps={{ onClick: setTimeRangeFromGraph, style: { cursor: 'pointer' } }}
gridAxis="xy"
fillOpacity={0.5}
strokeWidth={1.25}
dotProps={{ strokeWidth: 1, r: 2.5 }}
/>
) : (
<NoDataView isError={fetchGraphDataMutation.isError} />
2 changes: 1 addition & 1 deletion src/pages/Stream/components/SecondaryToolbar.tsx
Original file line number Diff line number Diff line change
@@ -5,7 +5,7 @@ import EventTimeLineGraph from './EventTimeLineGraph';

const SecondaryToolbar = () => {
return (
<Stack className={classes.logsSecondaryToolbar} style={{ height: STREAM_SECONDARY_TOOLBAR_HRIGHT }}>
<Stack className={classes.logsSecondaryToolbar} style={{ height: STREAM_SECONDARY_TOOLBAR_HRIGHT + 30 }}>
<EventTimeLineGraph />
</Stack>
);