Replace recharts with custom canvas

This commit is contained in:
2024-05-06 15:02:35 +01:00
parent d528712061
commit f6e933f784
13 changed files with 226 additions and 153 deletions

View File

@@ -0,0 +1,29 @@
import { Legend, type LegendProps } from '@/components/chart-cards/common/legend';
import type { FormatOptions } from '@/utils/format';
import type { ReactNode } from 'react';
import { CanvasChart } from './chart';
type Props = {
title: ReactNode;
subtitle?: ReactNode;
legend?: Omit<LegendProps, 'values'> & Partial<Pick<LegendProps, 'values'>>;
formatOptions?: FormatOptions;
domain?: [number, number];
hueOffset?: number;
data: number[];
total: number;
};
export const ChartCard = ({ data, domain, legend, hueOffset = 0, title, subtitle, formatOptions, total }: Props) => {
return (
<div className='chart-card'>
<h2>{title}</h2>
{subtitle}
{legend && <Legend hueOffset={hueOffset} formatOptions={formatOptions} values={data} {...legend} />}
<CanvasChart data={data} hueOffset={hueOffset} domain={domain} total={total} formatOptions={formatOptions} />
</div>
);
};

View File

@@ -0,0 +1,40 @@
.chart {
color: var(--color-neutral2);
display: grid;
font-size: 16px;
gap: 4px;
grid-template-columns: max-content 1fr;
height: 100%;
line-height: 1;
overflow: hidden;
}
.chart > .y-axis {
display: flex;
flex-direction: column;
height: 100%;
justify-content: space-between;
> div {
text-align: right;
}
}
.chart .cartesian-grid {
height: calc(100% - 16px);
position: absolute;
top: 8px;
width: 100%;
}
.chart .canvas-wrapper {
position: relative;
> canvas {
height: calc(100% - 16px);
left: 8px;
position: absolute;
top: 8px;
width: calc(100% - 8px);
}
}

View File

@@ -0,0 +1,143 @@
import { useAnimationFrame } from '@/hooks/use-animation-frame';
import { getFillColor, getStrokeColor } from '@/utils/colors';
import { type FormatOptions, formatValue } from '@/utils/format';
import { useEffect, useMemo, useRef, useState } from 'react';
import './chart.css';
const stepWindow = Number(import.meta.env.CLIENT_GRAPH_STEPS);
const stepPeriod = Number(import.meta.env.CLIENT_REFETCH_INTERVAL);
const width = 640;
const height = 480;
const xMargin = 4;
const fps = 30;
const framePeriod = 1000 / fps;
type Props = {
total: number;
data: number[];
domain?: [number, number];
formatOptions?: FormatOptions;
hueOffset?: number;
};
const xFromTimestamp = (timestamp: number) =>
((timestamp - Date.now()) / stepPeriod) * (width / stepWindow) + width + (width / stepWindow) * 2;
const YAxis = ({ max, formatOptions }: Pick<Props, 'formatOptions'> & { max: number }) => (
<div className='y-axis'>
{Array.from({ length: 5 }).map((_, index) => (
// biome-ignore lint/suspicious/noArrayIndexKey: supress react console error
<div key={index}>{formatValue((max * (4 - index)) / 4, formatOptions)}</div>
))}
</div>
);
const CartesianGrid = () => (
<svg
className='cartesian-grid'
version='1.1'
xmlns='http://www.w3.org/2000/svg'
width='100%'
height='100%'
viewBox={`0 0 ${width} ${height}`}
preserveAspectRatio='none'
vectorEffect='non-scaling-stroke'
>
<title>{'Cartesian grid'}</title>
{Array.from({ length: 5 }).map((_, index) => (
<line
x1={'0'}
x2={'100%'}
// biome-ignore lint/suspicious/noArrayIndexKey: supress react console error
key={index}
y1={Math.max(1, Math.min(height - 1, (height * index) / 4))}
y2={Math.max(1, Math.min(height - 1, (height * index) / 4))}
stroke='var(--color-neutral1)'
strokeWidth={1}
/>
))}
</svg>
);
export const CanvasChart = ({ total, hueOffset = 0, domain, data, formatOptions }: Props) => {
const canvasRef = useRef<HTMLCanvasElement>(null!);
const ignored = useRef(0);
const now = useMemo(() => Date.now(), []);
const [history, setHistory] = useState<[number, number[]][]>([[now, []]]);
const max = useMemo(() => {
if (domain) {
return domain[1];
}
return 1.25 * history.reduce((max, [_, values]) => Math.max(max, ...values), 0);
}, [history, domain]);
useEffect(() => {
if (data) {
setHistory(history => {
const firstValidIndex = history.findIndex(([timestamp]) => xFromTimestamp(timestamp) >= -xMargin);
const newHistory = history.slice(firstValidIndex);
newHistory.push([Date.now(), data]);
return newHistory;
});
}
}, [data]);
useEffect(() => {
const ctx = canvasRef.current.getContext('2d');
if (!ctx) {
return;
}
ctx.lineWidth = 2;
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
}, []);
useAnimationFrame(dt => {
ignored.current += dt;
if (ignored.current < framePeriod) {
return;
}
ignored.current = 0;
const ctx = canvasRef.current.getContext('2d');
if (!ctx) {
return;
}
ctx.clearRect(0, 0, width, height);
for (let i = 0; i < total; i++) {
ctx.fillStyle = getFillColor(hueOffset + (360 * Number(i)) / total);
ctx.strokeStyle = getStrokeColor(hueOffset + (360 * Number(i)) / total);
ctx.beginPath();
ctx.moveTo(-xMargin, height);
ctx.lineTo(-xMargin, height - (height * (history[0][1][i] ?? 0)) / max);
for (const [timestamp, values] of history) {
const x = xFromTimestamp(timestamp);
const y = height - (height * (values[i] ?? 0)) / max;
ctx.lineTo(x, y);
}
ctx.lineTo(width + xMargin, height - (height * (history[0][1][i] ?? 0)) / max);
ctx.lineTo(width + xMargin, height);
ctx.stroke();
ctx.fill();
ctx.closePath();
}
});
return (
<div className='chart'>
<YAxis max={max} formatOptions={formatOptions} />
<div className='canvas-wrapper'>
<CartesianGrid />
<canvas ref={canvasRef} width={width} height={height} />
</div>
</div>
);
};

View File

@@ -0,0 +1,19 @@
.legend-wrapper {
display: flex;
flex-wrap: wrap;
gap: 12;
width: 100%;
overflow: hidden;
> div {
flex: 1;
}
small {
display: inline-block;
max-width: 128px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
}

View File

@@ -0,0 +1,26 @@
import { getTextColor } from '@/utils/colors';
import { type FormatOptions, formatValue } from '@/utils/format';
import './index.css';
export type LegendProps = {
labels: string[];
values: string[] | number[];
formatOptions?: FormatOptions;
hueOffset?: number;
};
export const Legend = ({ labels, values, formatOptions, hueOffset = 0 }: LegendProps) => (
<div className='legend-wrapper'>
{labels.map((label, index) => (
<div key={labels[index]}>
<small style={{ color: getTextColor((hueOffset + (360 * index) / values.length) % 360) }}>{label}</small>
<h4>
{(() => {
const value = values[index];
return typeof value === 'string' ? value : formatValue(value, formatOptions);
})()}
</h4>
</div>
))}
</div>
);

View File

@@ -1,22 +1,9 @@
import { useQuery } from '@tanstack/react-query';
import { useEffect, useState } from 'react';
import { ChartCard } from './index';
import { ChartCard } from './common/card';
export const Cpu = () => {
const { data: staticData } = useQuery<StaticData>({ queryKey: ['static'] });
const { data: dynamicData } = useQuery<DynamicData>({ queryKey: ['dynamic'] });
const [history, setHistory] = useState<number[][]>(new Array(Number(import.meta.env.CLIENT_GRAPH_STEPS)).fill([]));
useEffect(() => {
if (dynamicData) {
setHistory(history => {
const newHistory = history.slice(1);
newHistory.push(dynamicData.cpu_usage);
return newHistory;
});
}
}, [dynamicData]);
if (!staticData || !dynamicData) {
return <div />;
@@ -36,7 +23,7 @@ export const Cpu = () => {
}
domain={[0, 100]}
formatOptions={{ prefix: false, units: '%' }}
data={history}
data={dynamicData.cpu_usage}
total={total_cpus}
/>
)

View File

@@ -1,21 +1,8 @@
import { useQuery } from '@tanstack/react-query';
import { useEffect, useState } from 'react';
import { ChartCard } from './index';
import { ChartCard } from './common/card';
export const Disks = () => {
const { data: dynamicData } = useQuery<DynamicData>({ queryKey: ['dynamic'] });
const [history, setHistory] = useState<number[][]>(new Array(Number(import.meta.env.CLIENT_GRAPH_STEPS)).fill([]));
useEffect(() => {
if (dynamicData) {
setHistory(history => {
const newHistory = history.slice(1);
newHistory.push([dynamicData.disks.read, dynamicData.disks.write]);
return newHistory;
});
}
}, [dynamicData]);
if (!dynamicData) {
return <div />;
@@ -25,12 +12,11 @@ export const Disks = () => {
<ChartCard
title='Disk activity'
legend={{
values: [dynamicData.disks.read, dynamicData.disks.write],
labels: ['Read', 'Write'],
}}
hueOffset={120}
formatOptions={{ units: 'B/s' }}
data={history}
data={[dynamicData.disks.read, dynamicData.disks.write]}
total={2}
/>
);

View File

@@ -1,71 +0,0 @@
import { Legend, type LegendProps } from '@/components/legend';
import { getFillColor, getStrokeColor } from '@/utils/colors';
import { type FormatOptions, formatValue } from '@/utils/format';
import { type ReactNode, useMemo } from 'react';
import { Area, AreaChart, CartesianGrid, ResponsiveContainer, XAxis, YAxis } from 'recharts';
import type { AxisDomain } from 'recharts/types/util/types';
type Props = {
title: ReactNode;
subtitle?: ReactNode;
legend?: LegendProps;
formatOptions?: FormatOptions;
domain?: AxisDomain;
hueOffset?: number;
data: number[][];
total: number;
};
export const ChartCard = ({ data, domain, legend, hueOffset = 0, title, subtitle, formatOptions, total }: Props) => {
const estimateTickWidth = useMemo(
() => ((formatOptions?.units?.length ?? 0) + (formatOptions?.prefix === false ? 0 : 2)) * 8,
[formatOptions],
);
return (
<div className='chart-card'>
<h2>{title}</h2>
{subtitle}
{legend && <Legend hueOffset={hueOffset} formatOptions={formatOptions} {...legend} />}
<ResponsiveContainer>
<AreaChart
width={500}
height={300}
data={data}
margin={{
bottom: -16,
left: estimateTickWidth,
}}
>
<CartesianGrid vertical={false} stroke='var(--color-neutral1)' />
<YAxis
axisLine={false}
domain={domain}
stroke='var(--color-neutral1)'
tick={{ fill: 'var(--color-neutral2)' }}
tickFormatter={value => formatValue(value, formatOptions)}
/>
{Array.from({ length: total }).map((_, index) => (
// biome-ignore lint/correctness/useJsxKeyInIterable: order irrelevant
<Area
isAnimationActive={false}
type='monotone'
dataKey={index}
fill={getFillColor(((index * 360) / total + hueOffset) % 360)}
stroke={getStrokeColor(((index * 360) / total + hueOffset) % 360)}
strokeWidth={2}
dot={false}
/>
))}
<XAxis tick={false} stroke='var(--color-neutral0)' strokeWidth={2} transform='translate(0 1)' />
</AreaChart>
</ResponsiveContainer>
</div>
);
};

View File

@@ -1,25 +1,13 @@
import { formatValue } from '@/utils/format';
import { useQuery } from '@tanstack/react-query';
import { useEffect, useMemo, useState } from 'react';
import { ChartCard } from './index';
import { useMemo } from 'react';
import { ChartCard } from './common/card';
const formatOptions = { units: 'B' };
export const Memory = () => {
const { data: staticData } = useQuery<StaticData>({ queryKey: ['static'] });
const { data: dynamicData } = useQuery<DynamicData>({ queryKey: ['dynamic'] });
const [history, setHistory] = useState<number[][]>(new Array(Number(import.meta.env.CLIENT_GRAPH_STEPS)).fill([]));
useEffect(() => {
if (dynamicData) {
setHistory(history => {
const newHistory = history.slice(1);
newHistory.push([dynamicData.mem_usage, dynamicData.swap_usage]);
return newHistory;
});
}
}, [dynamicData]);
const formatedTotals = useMemo(() => {
if (!staticData) {
@@ -44,7 +32,7 @@ export const Memory = () => {
}}
domain={[0, Math.max(staticData.total_memory, staticData.total_swap)]}
formatOptions={formatOptions}
data={history}
data={[dynamicData.mem_usage, dynamicData.swap_usage]}
total={2}
/>
);

View File

@@ -1,21 +1,8 @@
import { useQuery } from '@tanstack/react-query';
import { useEffect, useState } from 'react';
import { ChartCard } from './index';
import { ChartCard } from './common/card';
export const Network = () => {
const { data: dynamicData } = useQuery<DynamicData>({ queryKey: ['dynamic'] });
const [history, setHistory] = useState<number[][]>(new Array(Number(import.meta.env.CLIENT_GRAPH_STEPS)).fill([]));
useEffect(() => {
if (dynamicData) {
setHistory(history => {
const newHistory = history.slice(1);
newHistory.push([dynamicData.network.down, dynamicData.network.up]);
return newHistory;
});
}
}, [dynamicData]);
if (!dynamicData) {
return <div />;
@@ -25,12 +12,11 @@ export const Network = () => {
<ChartCard
title='Network'
legend={{
values: [dynamicData.network.down, dynamicData.network.up],
labels: ['Down', 'Up'],
}}
hueOffset={60}
formatOptions={{ units: 'B/s' }}
data={history}
data={[dynamicData.network.down, dynamicData.network.up]}
total={2}
/>
);

View File

@@ -1,22 +1,9 @@
import { useQuery } from '@tanstack/react-query';
import { useEffect, useState } from 'react';
import { ChartCard } from './index';
import { ChartCard } from './common/card';
export const Temps = () => {
const { data: staticData } = useQuery<StaticData>({ queryKey: ['static'] });
const { data: dynamicData } = useQuery<DynamicData>({ queryKey: ['dynamic'] });
const [history, setHistory] = useState<number[][]>(new Array(Number(import.meta.env.CLIENT_GRAPH_STEPS)).fill([]));
useEffect(() => {
if (dynamicData) {
setHistory(history => {
const newHistory = history.slice(1);
newHistory.push(dynamicData.temps);
return newHistory;
});
}
}, [dynamicData]);
if (!staticData || !dynamicData) {
return <div />;
@@ -26,12 +13,11 @@ export const Temps = () => {
<ChartCard
title='Temperatures'
legend={{
values: dynamicData.temps,
labels: staticData.components,
}}
domain={[0, (max: number) => Math.max(100, Math.ceil(1.25*max))]}
domain={[0, 100]} //(max: number) => Math.max(100, Math.ceil(1.25 * max))]}
formatOptions={{ si: true, prefix: false, units: 'ºC' }}
data={history}
data={dynamicData.temps}
total={staticData.components.length}
/>
);