Sync internal canvas dimensions to element

This commit is contained in:
2024-05-06 17:20:47 +01:00
parent c20dee969a
commit 62de8ccafa
6 changed files with 85 additions and 73 deletions

View File

@@ -0,0 +1,30 @@
const width = 640;
const height = 480;
export 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>
);

View File

@@ -0,0 +1,41 @@
.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%;
gap: 8px;
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,123 @@
import { useAnimationFrame } from '@/hooks/use-animation-frame';
import { getFillColor, getStrokeColor } from '@/utils/colors';
import type { FormatOptions } from '@/utils/format';
import { useEffect, useMemo, useRef, useState } from 'react';
import { CartesianGrid } from './cartesian-grid';
import './index.css';
import { YAxis } from './y-axis';
const stepWindow = Number(import.meta.env.CLIENT_GRAPH_STEPS);
const stepPeriod = Number(import.meta.env.CLIENT_REFETCH_INTERVAL);
const xMargin = 4;
const fps = 30;
type Props = {
total: number;
data: number[];
domain?: [number, number];
hardDomain?: boolean;
formatOptions?: FormatOptions;
hueOffset?: number;
};
const xFromTimestamp = (timestamp: number, width: number) =>
((timestamp - Date.now()) / stepPeriod) * (width / stepWindow) + width + (width / stepWindow) * 2;
export const CanvasChart = ({ total, hueOffset = 0, domain, hardDomain, data, formatOptions }: Props) => {
const canvasRef = useRef<HTMLCanvasElement>(null!);
const now = useMemo(() => Date.now(), []);
const [history, setHistory] = useState<[number, number[]][]>([[now, []]]);
const targetMax = useMemo(() => {
if (domain && hardDomain) {
return domain[1];
}
const historyMax = history.reduce((max, [_, values]) => Math.max(max, ...values), 0);
if (!domain || historyMax > domain[1]) {
return 1.25 * historyMax;
}
return domain[1];
}, [history, domain, hardDomain]);
const max = useRef(targetMax);
const [width, setWidth] = useState(640);
const [height, setHeight] = useState(480);
// Record data changes
useEffect(() => {
if (data) {
setHistory(history => {
const firstValidIndex = history.findIndex(([timestamp]) => xFromTimestamp(timestamp, width) >= -xMargin);
const newHistory = history.slice(firstValidIndex);
newHistory.push([Date.now(), data]);
return newHistory;
});
}
}, [data, width]);
// Sync canvas size to actual element dimensions
useEffect(() => {
const onResize = () => {
const dimensions = canvasRef.current.getBoundingClientRect();
const newWidth = dimensions.width * window.devicePixelRatio;
setWidth(newWidth);
setHeight(dimensions.height * window.devicePixelRatio);
};
onResize();
window.addEventListener('resize', onResize);
return () => window.removeEventListener('resize', onResize);
}, []);
// Redraw chart
useAnimationFrame(() => {
const ctx = canvasRef.current.getContext('2d');
if (!ctx) {
return;
}
if (!hardDomain) {
max.current = (max.current + targetMax) / 2;
}
ctx.clearRect(0, 0, width, height);
ctx.lineWidth = 2 * window.devicePixelRatio;
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
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.current);
for (const [timestamp, values] of history) {
const x = xFromTimestamp(timestamp, width);
const y = height - (height * (values[i] ?? 0)) / max.current;
ctx.lineTo(x, y);
}
ctx.lineTo(width + xMargin, height - (height * (history[0][1][i] ?? 0)) / max.current);
ctx.lineTo(width + xMargin, height);
ctx.stroke();
ctx.fill();
ctx.closePath();
}
}, fps);
return (
<div className='chart'>
<YAxis max={targetMax} formatOptions={formatOptions} />
<div className='canvas-wrapper'>
<CartesianGrid />
<canvas ref={canvasRef} width={width} height={height} />
</div>
</div>
);
};

View File

@@ -0,0 +1,15 @@
import { type FormatOptions, formatValue } from '@/utils/format';
type Props = {
formatOptions?: FormatOptions;
max: number;
};
export const YAxis = ({ max, formatOptions }: Props) => (
<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>
);