BUR-62 переработана отрисовка графика на отрезки по грануляции #13

Merged
APervov merged 1 commits from bur-62 into dev 2026-07-05 08:05:36 +00:00
6 changed files with 141 additions and 84 deletions
Showing only changes of commit 1a994f36bd - Show all commits

View File

@@ -34,7 +34,7 @@ export function HistoryChart({
}: HistoryChartProps) { }: HistoryChartProps) {
const dataZoomRef = useRef<DataZoomState | null>(null); const dataZoomRef = useRef<DataZoomState | null>(null);
const lines = useHistoryChartQueries({ edge, from, granulate, tags, to, tagLabels }); const lines = useHistoryChartQueries({ edge, from, granulate, tags, to, tagLabels });
const series = useHistoryChartSeries(lines); const series = useHistoryChartSeries(lines, granulate);
const legendData = useMemo(() => lines.map((line) => line.label), [lines]); const legendData = useMemo(() => lines.map((line) => line.label), [lines]);
const loading = lines.some((line) => line.loading); const loading = lines.some((line) => line.loading);

View File

@@ -1,5 +1,7 @@
export type AvgPointValue = [time: number, avg: number, min: number, max: number, count: number]; export type AvgPointValue = [time: number, avg: number, min: number, max: number, count: number];
export type HistoryBucketValue = [...AvgPointValue, slotMs: number];
export type TooltipParam = { export type TooltipParam = {
color?: string; color?: string;
marker?: string; marker?: string;

View File

@@ -1,4 +1,4 @@
import { LineChart, ScatterChart } from 'echarts/charts'; import { CustomChart } from 'echarts/charts';
import { import {
DataZoomComponent, DataZoomComponent,
GridComponent, GridComponent,
@@ -9,8 +9,7 @@ import * as echarts from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers'; import { CanvasRenderer } from 'echarts/renderers';
echarts.use([ echarts.use([
LineChart, CustomChart,
ScatterChart,
GridComponent, GridComponent,
LegendComponent, LegendComponent,
TooltipComponent, TooltipComponent,

View File

@@ -1,6 +1,13 @@
import type { SeriesOption } from 'echarts'; import type {
CustomSeriesRenderItemAPI,
CustomSeriesRenderItemParams,
CustomSeriesRenderItemReturn,
SeriesOption,
} from 'echarts';
import { graphic } from 'echarts/core';
import type { HistoryPoint } from '../../entities/history/types'; import type { HistoryPoint } from '../../entities/history/types';
import type { AvgPointValue } from './chartTypes'; import { parseGranulateMs } from '../../utils/historyGranularity';
import type { HistoryBucketValue } from './chartTypes';
export const SERIES_COLORS = [ export const SERIES_COLORS = [
'#5B8FF9', '#5B8FF9',
@@ -13,93 +20,120 @@ export const SERIES_COLORS = [
'#A7B3FF', '#A7B3FF',
]; ];
/** Создает avg-линию, вертикальные min/max-отрезки и точки экстремумов для одной серии. */ type CartesianCoordSys = {
export function createSeriesOptions(points: HistoryPoint[], index: number, label: string): SeriesOption[] { x: number;
y: number;
width: number;
height: number;
};
function isFinitePoint(point: HistoryPoint): boolean {
return [point.avg_value, point.min_value, point.max_value].every(Number.isFinite);
}
/** Упаковывает один bucket API в компактный tuple для custom series ECharts. */
function createBucketData(points: HistoryPoint[], slotMs: number): HistoryBucketValue[] {
return points.filter(isFinitePoint).map((point) => [
new Date(point.time).getTime(),
point.avg_value,
point.min_value,
point.max_value,
point.point_count,
slotMs,
]);
}
/** Рисует один bucket как временной слот: затухающий min..max и яркий маркер avg. */
function renderBucket(color: string) {
return (params: CustomSeriesRenderItemParams, api: CustomSeriesRenderItemAPI): CustomSeriesRenderItemReturn => {
const time = Number(api.value(0));
const avg = Number(api.value(1));
const min = Number(api.value(2));
const max = Number(api.value(3));
const slotMs = Number(api.value(5));
// ECharts отдает размеры области графика в runtime, но в публичных типах
// они не описаны. Поэтому держим cast локально рядом с clipping-логикой.
const coordSys = params.coordSys as unknown as CartesianCoordSys;
// Переводим координаты данных (time/value) в пиксели canvas.
const avgPoint = api.coord([time, avg]);
const minPoint = api.coord([time, min]);
const maxPoint = api.coord([time, max]);
const slotStart = api.coord([time - slotMs / 2, avg]);
const slotEnd = api.coord([time + slotMs / 2, avg]);
// Слот занимает один интервал грануляции по X и диапазон min..max по Y.
const x = Math.min(slotStart[0], slotEnd[0]);
const rawHeight = Math.abs(maxPoint[1] - minPoint[1]);
const width = Math.max(2, Math.abs(slotEnd[0] - slotStart[0]));
const height = Math.max(2, rawHeight);
const y = Math.min(minPoint[1], maxPoint[1]) - (height - rawHeight) / 2;
const avgY = avgPoint[1];
const chartArea = { x: coordSys.x, y: coordSys.y, width: coordSys.width, height: coordSys.height };
// Обрезаем фигуры, чтобы при Y-зуме они не выходили за область графика.
const rangeShape = graphic.clipRectByRect(
{ x, y, width, height },
chartArea,
);
const avgShape = graphic.clipRectByRect(
{ x, y: avgY - 1, width, height: 2 },
chartArea,
);
if (!rangeShape) {
return null;
}
return {
type: 'group',
children: [
{
type: 'rect',
shape: rangeShape,
style: {
fill: new graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: `${color}00` },
{ offset: 0.5, color: `${color}66` },
{ offset: 1, color: `${color}00` },
]),
},
},
...(avgShape ? [{
type: 'rect' as const,
shape: avgShape,
style: {
fill: color,
},
}] : []),
],
};
};
}
/** Создает отдельный временной слот min..max с акцентом на avg для каждой точки history. */
export function createSeriesOptions(points: HistoryPoint[], index: number, label: string, granulate: string): SeriesOption[] {
const color = SERIES_COLORS[index % SERIES_COLORS.length]; const color = SERIES_COLORS[index % SERIES_COLORS.length];
const avgData: AvgPointValue[] = points.map((point) => { const data = createBucketData(points, parseGranulateMs(granulate));
const time = new Date(point.time).getTime();
return [time, point.avg_value, point.min_value, point.max_value, point.point_count];
});
const spreadData = points.flatMap((point) => {
const time = new Date(point.time).getTime();
return [
[time, point.min_value],
[time, point.max_value],
[time, null],
];
});
return [ return [
{ {
name: label, name: label,
type: 'line', type: 'custom',
data: spreadData, data,
showSymbol: false, renderItem: renderBucket(color),
connectNulls: false, encode: {
silent: true, x: 0,
tooltip: { show: false }, y: [1, 2, 3],
legendHoverLink: false,
lineStyle: {
width: 1,
opacity: 0.42,
color,
}, },
emphasis: {
disabled: true,
},
z: 1,
},
{
name: label,
type: 'scatter',
data: points.map((point) => [new Date(point.time).getTime(), point.min_value]),
symbolSize: 4,
silent: true,
tooltip: { show: false },
itemStyle: { itemStyle: {
color, color,
opacity: 0.72,
}, },
emphasis: { emphasis: {
disabled: true, disabled: true,
}, },
z: 2,
},
{
name: label,
type: 'scatter',
data: points.map((point) => [new Date(point.time).getTime(), point.max_value]),
symbolSize: 4,
silent: true,
tooltip: { show: false },
itemStyle: {
color,
opacity: 0.72,
},
emphasis: {
disabled: true,
},
z: 2,
},
{
name: label,
type: 'line',
showSymbol: false,
smooth: false,
sampling: 'lttb',
data: avgData,
lineStyle: {
width: 1.8,
color,
},
emphasis: {
disabled: true,
lineStyle: {
width: 1.8,
color,
},
},
z: 3, z: 3,
}, } as SeriesOption,
]; ];
} }

View File

@@ -3,12 +3,12 @@ import type { SeriesOption } from 'echarts';
import { createSeriesOptions } from './historyChartSeries'; import { createSeriesOptions } from './historyChartSeries';
import type { HistoryChartLineData } from './useHistoryChartQueries'; import type { HistoryChartLineData } from './useHistoryChartQueries';
export function useHistoryChartSeries(lines: HistoryChartLineData[]): SeriesOption[] { export function useHistoryChartSeries(lines: HistoryChartLineData[], granulate: string): SeriesOption[] {
return useMemo( return useMemo(
() => () =>
lines.flatMap((line) => lines.flatMap((line) =>
line.rows.length ? createSeriesOptions(line.rows, line.index, line.label) : [], line.rows.length ? createSeriesOptions(line.rows, line.index, line.label, granulate) : [],
), ),
[lines], [granulate, lines],
); );
} }

View File

@@ -25,6 +25,19 @@ const WEEK = 7 * DAY;
const MONTH = 30 * DAY; const MONTH = 30 * DAY;
const YEAR = 365 * DAY; const YEAR = 365 * DAY;
const GRANULATE_UNIT_MS: Record<string, number> = {
second: SECOND,
seconds: SECOND,
minute: MINUTE,
minutes: MINUTE,
hour: HOUR,
hours: HOUR,
day: DAY,
days: DAY,
week: WEEK,
weeks: WEEK,
};
type Rule = { type Rule = {
maxMs: number; maxMs: number;
granulate: string; granulate: string;
@@ -60,3 +73,12 @@ export function getHistoryGranularity(from: string, to: string): HistoryGranular
} }
); );
} }
/** Переводит текст грануляции API вроде "10 minutes" в миллисекунды. */
export function parseGranulateMs(granulate: string): number {
const [amountText, unit = ''] = granulate.trim().split(/\s+/);
const amount = Number(amountText);
const unitMs = GRANULATE_UNIT_MS[unit.toLowerCase()];
return Number.isFinite(amount) && unitMs ? amount * unitMs : MINUTE;
}