Compare commits
28 Commits
ca78c0b17b
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 782d3d4430 | |||
| e7d489bcee | |||
| 5d0408c533 | |||
| 1127b14946 | |||
| 9a542ce33e | |||
| 5ffe9192c1 | |||
| 88d628b696 | |||
|
|
486221b980 | ||
| 1632bfb3d8 | |||
|
|
e796dced6c | ||
| 074d45d695 | |||
| 44b52785dd | |||
|
|
3024ff90b0 | ||
| 19f30ff4db | |||
|
|
e8c5dbc489 | ||
| cf1dea2767 | |||
|
|
3d395aaa8d | ||
| e396fbbb8a | |||
|
|
c6e073c5dd | ||
| 2750f0efaf | |||
|
|
f84b15b2d0 | ||
| 688e883996 | |||
|
|
e057f55c73 | ||
|
|
f4cefe376c | ||
| 646424d44f | |||
|
|
8bb19f3f9d | ||
| 4e3cc0eb33 | |||
|
|
01d05b4331 |
@@ -1,5 +1,6 @@
|
||||
branch=
|
||||
DEV_API_URL=http://localhost:3101
|
||||
BRANCH=
|
||||
#DEV_API_URL=http://localhost:3101
|
||||
DEV_API_URL=https://beta.drill.greact.ru
|
||||
VITE_DIAGRAM_API_URL=http://localhost:3002
|
||||
VITE_TOIR_LIGHT_ORIGIN=https://toir-light.greact.ru
|
||||
VITE_KEYCLOAK_URL=https://sso.greact.ru
|
||||
|
||||
@@ -6,6 +6,21 @@ type CameraViewProps = {
|
||||
wsUrl: string;
|
||||
};
|
||||
|
||||
const CAMERA_PLAYER_CONFIG = {
|
||||
enableWorker: true,
|
||||
enableStashBuffer: true,
|
||||
stashInitialSize: 512,
|
||||
autoCleanupSourceBuffer: true,
|
||||
autoCleanupMaxBackwardDuration: 10,
|
||||
autoCleanupMinBackwardDuration: 5,
|
||||
liveBufferLatencyChasing: true,
|
||||
liveBufferLatencyMaxLatency: 5.0,
|
||||
liveBufferLatencyMinRemain: 2.0,
|
||||
liveSync: false,
|
||||
lazyLoad: false,
|
||||
deferLoadAfterSourceOpen: false,
|
||||
};
|
||||
|
||||
export function CameraView({ title = 'Камера', wsUrl }: CameraViewProps) {
|
||||
const videoRef = useRef<HTMLVideoElement | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
@@ -13,6 +28,7 @@ export function CameraView({ title = 'Камера', wsUrl }: CameraViewProps) {
|
||||
useEffect(() => {
|
||||
const video = videoRef.current;
|
||||
let player: ReturnType<typeof mpegts.createPlayer> | null = null;
|
||||
const handlePlayerError = () => setError('Ошибка видеопотока');
|
||||
|
||||
if (!video) {
|
||||
return;
|
||||
@@ -30,20 +46,22 @@ export function CameraView({ title = 'Камера', wsUrl }: CameraViewProps) {
|
||||
}
|
||||
|
||||
player = mpegts.createPlayer(
|
||||
{ type: 'mpegts', isLive: true, url: wsUrl },
|
||||
{ liveBufferLatencyChasing: true, liveBufferLatencyMaxLatency: 1.5 },
|
||||
{ type: 'mpegts', isLive: true, url: wsUrl, hasAudio: false },
|
||||
CAMERA_PLAYER_CONFIG,
|
||||
);
|
||||
|
||||
player.on(mpegts.Events.ERROR, handlePlayerError);
|
||||
player.attachMediaElement(video);
|
||||
player.load();
|
||||
|
||||
const playResult = player.play();
|
||||
if (playResult instanceof Promise) {
|
||||
void playResult.then(() => setError(null)).catch(() => setError('Не удалось запустить воспроизведение'));
|
||||
void playResult.then(() => setError(null)).catch(() => undefined);
|
||||
}
|
||||
|
||||
return () => {
|
||||
video.removeEventListener('playing', clearError);
|
||||
player?.off(mpegts.Events.ERROR, handlePlayerError);
|
||||
player?.pause();
|
||||
player?.unload();
|
||||
player?.detachMediaElement();
|
||||
|
||||
@@ -6,12 +6,17 @@ type MetricWidgetProps = {
|
||||
};
|
||||
|
||||
export function MetricWidget({ item }: MetricWidgetProps) {
|
||||
const title = item.name?.trim() || item.tag;
|
||||
const name = item.name?.trim() || item.tag;
|
||||
const unit = item.unitOfMeasurement?.trim();
|
||||
|
||||
return (
|
||||
<article className="metric-widget" title={`${title} (${item.tag})`}>
|
||||
<span className="metric-widget__tag">{title}</span>
|
||||
<article className="metric-widget" title={`${name} (${item.tag})`}>
|
||||
<span className="metric-widget__id">{item.tag}</span>
|
||||
<span className="metric-widget__name">{name}</span>
|
||||
<span className="metric-widget__reading">
|
||||
<strong className="metric-widget__value">{formatNumber(item.value)}</strong>
|
||||
{unit ? <span className="metric-widget__unit">{unit}</span> : null}
|
||||
</span>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
export type CurrentItem = {
|
||||
edge: string;
|
||||
tag: string;
|
||||
value: number;
|
||||
value: number | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
time: string;
|
||||
|
||||
@@ -4,8 +4,10 @@ import { useRef } from 'react';
|
||||
import { CalendarDays, CalendarClock, Check, ChevronDown, Clock3, DatabaseZap, Search } from 'lucide-react';
|
||||
import type { CurrentItem } from '../../../entities/current/types';
|
||||
import { HistoryChart } from '../../../features/history-chart/HistoryChart';
|
||||
import { HistoryChartAvgLineModeControl } from '../../../features/history-chart/HistoryChartAvgLineModeControl';
|
||||
import type { AvgLineMode } from '../../../features/history-chart/chartTypes';
|
||||
import { RANGE_PRESETS, createRange, type DateRangeState } from '../../../features/history/dateRange';
|
||||
import { toIsoFromInput } from '../../../utils/format';
|
||||
import { formatNumber, toIsoFromInput } from '../../../utils/format';
|
||||
import type { HistoryGranularity } from '../../../utils/historyGranularity';
|
||||
|
||||
type ArchiveViewProps = {
|
||||
@@ -93,6 +95,8 @@ export function ArchiveView({
|
||||
onSelectVisibleTags,
|
||||
onToggleTag,
|
||||
}: ArchiveViewProps) {
|
||||
const [avgLineMode, setAvgLineMode] = useState<AvgLineMode>('auto');
|
||||
const [selectedRangePresetId, setSelectedRangePresetId] = useState<string>('24h');
|
||||
const [selectorOpen, setSelectorOpen] = useState(false);
|
||||
const selectedPreview = selectedTags.slice(0, 10);
|
||||
const hiddenSelectedCount = Math.max(0, selectedTags.length - selectedPreview.length);
|
||||
@@ -103,6 +107,7 @@ export function ArchiveView({
|
||||
const fromIso = toIsoFromInput(range.from) as string;
|
||||
const toIso = toIsoFromInput(range.to) as string;
|
||||
const updateRangePart = (rangePart: RangePart, inputPart: RangeInputPart, value: string) => {
|
||||
setSelectedRangePresetId('');
|
||||
onRangeChange({
|
||||
...range,
|
||||
[rangePart]: updateRangeInputPart(range[rangePart], inputPart, value),
|
||||
@@ -149,14 +154,14 @@ export function ArchiveView({
|
||||
<input value={search} onChange={(event) => onSearchChange(event.target.value)} placeholder="Поиск" />
|
||||
</label>
|
||||
<div className="tag-selector__tools">
|
||||
<button type="button" onClick={onSelectFirstTags}>
|
||||
{/* <button type="button" onClick={onSelectFirstTags}>
|
||||
Первый
|
||||
</button>
|
||||
</button> */}
|
||||
<button type="button" onClick={onSelectVisibleTags}>
|
||||
Выбрать найденный
|
||||
Выбрать все
|
||||
</button>
|
||||
<button type="button" onClick={onClearVisibleTags}>
|
||||
Снять найденные
|
||||
Снять все
|
||||
</button>
|
||||
<button type="button" onClick={onClearTags}>
|
||||
Сбросить все
|
||||
@@ -191,7 +196,7 @@ export function ArchiveView({
|
||||
{label !== item.tag ? <small>{item.tag}</small> : null}
|
||||
</span>
|
||||
<span className="tag-select-item__side">
|
||||
<strong>{item.value.toLocaleString('ru-RU', { maximumFractionDigits: item.precision ?? 3 })}</strong>
|
||||
<strong>{formatNumber(item.value)}</strong>
|
||||
{selected ? <Check size={15} /> : null}
|
||||
</span>
|
||||
</button>
|
||||
@@ -209,13 +214,23 @@ export function ArchiveView({
|
||||
onPointerEnter={() => setSelectorOpen(false)}
|
||||
>
|
||||
<div className="toolbar">
|
||||
<div className="segmented">
|
||||
<div className="archive-toolbar-segmented-control">
|
||||
<div className="segmented segmented--range-preset">
|
||||
{RANGE_PRESETS.map((preset) => (
|
||||
<button key={preset.id} type="button" onClick={() => onRangeChange(createRange(preset.hours))}>
|
||||
<button
|
||||
key={preset.id}
|
||||
type="button"
|
||||
className={preset.id === selectedRangePresetId ? 'segmented__button--active' : undefined}
|
||||
onClick={() => {
|
||||
setSelectedRangePresetId(preset.id);
|
||||
onRangeChange(createRange(preset.hours));
|
||||
}}
|
||||
>
|
||||
{preset.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="archive-date-range">
|
||||
<span>С</span>
|
||||
<DateRangeField
|
||||
@@ -250,11 +265,13 @@ export function ArchiveView({
|
||||
onChange={(value) => updateRangePart('to', 'time', value)}
|
||||
/>
|
||||
</div>
|
||||
<HistoryChartAvgLineModeControl value={avgLineMode} onChange={setAvgLineMode} />
|
||||
</div>
|
||||
|
||||
{selectedTags.length ? (
|
||||
<HistoryChart
|
||||
key={`${range.from}:${range.to}:${historyAxis.granulate}`}
|
||||
key={`${range.from}:${range.to}:${historyAxis.granulate}:${historyAxis.tickIntervalMs ?? ''}`}
|
||||
avgLineMode={avgLineMode}
|
||||
edge={edgeId}
|
||||
from={fromIso}
|
||||
to={toIso}
|
||||
|
||||
@@ -29,8 +29,8 @@ export function ElectricalNode({ liveValues, node, ownerEdgeId }: ElectricalNode
|
||||
? getLiveValue(liveValues, node.edgeId || ownerEdgeId, node.tagId)
|
||||
: getLiveValue(liveValues, bindingEdgeId, bindings?.stateTagId);
|
||||
const alarmValue = node.kind === 'decoration' ? getLiveValue(liveValues, bindingEdgeId, bindings?.alarmTagId) : undefined;
|
||||
const alarmActive = Boolean(alarmValue && Number(alarmValue.value) !== 0);
|
||||
const stateActive = Boolean(mainValue && Number(mainValue.value) !== 0);
|
||||
const alarmActive = Boolean(alarmValue && alarmValue.value !== null && alarmValue.value !== 0);
|
||||
const stateActive = Boolean(mainValue && mainValue.value !== null && mainValue.value !== 0);
|
||||
const title = getNodeTitle(node, mainValue);
|
||||
const style: CSSProperties = {
|
||||
left: node.position.x,
|
||||
|
||||
@@ -1,12 +1,22 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { getHistoryGranularity, type HistoryAxisLabelFormat } from '../../utils/historyGranularity';
|
||||
import type { DataZoomEventBatch, DataZoomState, HistoryZoomRange } from './chartTypes';
|
||||
import type { EChartsOption } from 'echarts';
|
||||
import { parseGranulateMs, type HistoryAxisLabelFormat } from '../../utils/historyGranularity';
|
||||
import type { AvgLineMode, DataZoomEventBatch, HistoryZoomRange } from './chartTypes';
|
||||
import { HistoryChartArea } from './HistoryChartArea';
|
||||
import { createHistoryChartOptions } from './historyChartOptions';
|
||||
import {
|
||||
createDataZoomState,
|
||||
createInitialZoomRange,
|
||||
getZoomRangeFromEvent,
|
||||
isSameZoomRange,
|
||||
isXAxisDataZoom,
|
||||
ZOOM_REQUEST_DELAY_MS,
|
||||
} from './historyChartZoom';
|
||||
import { useHistoryChartQueries } from './useHistoryChartQueries';
|
||||
import { useHistoryChartSeries } from './useHistoryChartSeries';
|
||||
|
||||
type HistoryChartProps = {
|
||||
avgLineMode: AvgLineMode;
|
||||
edge: string;
|
||||
from: string;
|
||||
granulate: string;
|
||||
@@ -17,76 +27,23 @@ type HistoryChartProps = {
|
||||
tagLabels?: Record<string, string>;
|
||||
};
|
||||
|
||||
const ZOOM_REQUEST_DELAY_MS = 350;
|
||||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
function isXAxisDataZoom(state: DataZoomState): boolean {
|
||||
return state.dataZoomId?.startsWith('history-x-') || state.dataZoomIndex === 0 || state.dataZoomIndex === 1;
|
||||
/** Определяет видимость соединительной avg-линии с учетом ручного режима и масштаба X-шкалы. */
|
||||
function shouldShowAvgLine(mode: AvgLineMode, range: HistoryZoomRange): boolean {
|
||||
if (mode === 'show') {
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Собирает начальный zoom-диапазон из внешних props графика. */
|
||||
function createInitialZoomRange({
|
||||
from,
|
||||
granulate,
|
||||
labelFormat,
|
||||
tickIntervalMs,
|
||||
to,
|
||||
}: Pick<HistoryChartProps, 'from' | 'granulate' | 'labelFormat' | 'tickIntervalMs' | 'to'>): HistoryZoomRange {
|
||||
return { from, to, granulate, labelFormat, tickIntervalMs };
|
||||
if (mode === 'hide') {
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Создает zoom-диапазон из миллисекунд и подбирает для него грануляцию. */
|
||||
function createZoomRange(fromMs: number, toMs: number): HistoryZoomRange {
|
||||
const from = new Date(fromMs).toISOString();
|
||||
const to = new Date(toMs).toISOString();
|
||||
|
||||
return {
|
||||
from,
|
||||
to,
|
||||
...getHistoryGranularity(from, to),
|
||||
};
|
||||
}
|
||||
|
||||
/** Достает подинтервал X-зума из события ECharts. */
|
||||
function getZoomRangeFromEvent(state: DataZoomState, baseRange: HistoryZoomRange): HistoryZoomRange | null {
|
||||
const baseFromMs = new Date(baseRange.from).getTime();
|
||||
const baseToMs = new Date(baseRange.to).getTime();
|
||||
const baseSpanMs = baseToMs - baseFromMs;
|
||||
|
||||
if (!Number.isFinite(baseFromMs) || !Number.isFinite(baseToMs) || baseSpanMs <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const startValue = Number(state.startValue);
|
||||
const endValue = Number(state.endValue);
|
||||
let nextFromMs = Number.isFinite(startValue) ? startValue : undefined;
|
||||
let nextToMs = Number.isFinite(endValue) ? endValue : undefined;
|
||||
|
||||
// ECharts иногда не передает startValue/endValue, поэтому используем start/end.
|
||||
if (nextFromMs === undefined || nextToMs === undefined) {
|
||||
const start = Number(state.start);
|
||||
const end = Number(state.end);
|
||||
|
||||
if (!Number.isFinite(start) || !Number.isFinite(end)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
nextFromMs = baseFromMs + (baseSpanMs * start) / 100;
|
||||
nextToMs = baseFromMs + (baseSpanMs * end) / 100;
|
||||
}
|
||||
|
||||
// Проверка на выход из диапазона
|
||||
const fromMs = Math.max(baseFromMs, Math.min(nextFromMs, nextToMs));
|
||||
const toMs = Math.min(baseToMs, Math.max(nextFromMs, nextToMs));
|
||||
|
||||
return toMs > fromMs ? createZoomRange(fromMs, toMs) : null;
|
||||
}
|
||||
|
||||
/** Проверяет, что lazy zoom не пытается повторно применить тот же диапазон. */
|
||||
function isSameZoomRange(left: HistoryZoomRange, right: HistoryZoomRange): boolean {
|
||||
return left.from === right.from && left.to === right.to && left.granulate === right.granulate;
|
||||
return (range.tickIntervalMs ?? parseGranulateMs(range.granulate)) < DAY_MS;
|
||||
}
|
||||
|
||||
export function HistoryChart({
|
||||
avgLineMode,
|
||||
edge,
|
||||
from,
|
||||
granulate,
|
||||
@@ -96,11 +53,17 @@ export function HistoryChart({
|
||||
to,
|
||||
tagLabels = {},
|
||||
}: HistoryChartProps) {
|
||||
const baseRange = useMemo(
|
||||
() => createInitialZoomRange({ from, granulate, labelFormat, tickIntervalMs, to }),
|
||||
[from, granulate, labelFormat, tickIntervalMs, to],
|
||||
);
|
||||
const [zoomRange, setZoomRange] = useState(() =>
|
||||
createInitialZoomRange({ from, granulate, labelFormat, tickIntervalMs, to }),
|
||||
);
|
||||
const baseRangeRef = useRef(baseRange);
|
||||
const zoomRangeRef = useRef(zoomRange);
|
||||
const zoomTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const lastReadyOptionRef = useRef<EChartsOption | null>(null);
|
||||
const lines = useHistoryChartQueries({
|
||||
edge,
|
||||
from: zoomRange.from,
|
||||
@@ -109,15 +72,17 @@ export function HistoryChart({
|
||||
to: zoomRange.to,
|
||||
tagLabels,
|
||||
});
|
||||
const series = useHistoryChartSeries(lines, zoomRange.granulate);
|
||||
const showAvgLine = shouldShowAvgLine(avgLineMode, zoomRange);
|
||||
const series = useHistoryChartSeries(lines, zoomRange.granulate, avgLineMode, showAvgLine);
|
||||
const legendData = useMemo(() => lines.map((line) => line.label), [lines]);
|
||||
const loading = lines.some((line) => line.loading);
|
||||
const hasData = series.length > 0;
|
||||
|
||||
useEffect(() => {
|
||||
const nextRange = createInitialZoomRange({ from, granulate, labelFormat, tickIntervalMs, to });
|
||||
zoomRangeRef.current = nextRange;
|
||||
setZoomRange(nextRange);
|
||||
}, [from, granulate, labelFormat, tickIntervalMs, to]);
|
||||
baseRangeRef.current = baseRange;
|
||||
zoomRangeRef.current = baseRange;
|
||||
setZoomRange(baseRange);
|
||||
}, [baseRange]);
|
||||
|
||||
useEffect(() => {
|
||||
zoomRangeRef.current = zoomRange;
|
||||
@@ -135,17 +100,29 @@ export function HistoryChart({
|
||||
const option = useMemo(
|
||||
() =>
|
||||
createHistoryChartOptions({
|
||||
dataZoomState: { start: 0, end: 100 },
|
||||
from: zoomRange.from,
|
||||
to: zoomRange.to,
|
||||
dataZoomState: createDataZoomState(baseRange, zoomRange),
|
||||
from: baseRange.from,
|
||||
to: baseRange.to,
|
||||
labelFormat: zoomRange.labelFormat,
|
||||
legendData,
|
||||
series,
|
||||
tickIntervalMs: zoomRange.tickIntervalMs,
|
||||
}),
|
||||
[legendData, series, zoomRange],
|
||||
[baseRange, legendData, series, zoomRange],
|
||||
);
|
||||
|
||||
// Во время lazy-загрузки нового zoom-диапазона оставляем на экране последний готовый график.
|
||||
// Так canvas не заменяется loader-ом и пользователь не теряет визуальный контекст.
|
||||
const fallbackOption = loading && !hasData ? lastReadyOptionRef.current : null;
|
||||
const displayOption = fallbackOption ?? option;
|
||||
const displayHasData = hasData || Boolean(fallbackOption);
|
||||
|
||||
useEffect(() => {
|
||||
if (hasData) {
|
||||
lastReadyOptionRef.current = option;
|
||||
}
|
||||
}, [hasData, option]);
|
||||
|
||||
const handleDataZoom = useCallback((event: DataZoomEventBatch) => {
|
||||
const state = (event.batch ?? [event]).find(isXAxisDataZoom);
|
||||
|
||||
@@ -153,8 +130,9 @@ export function HistoryChart({
|
||||
return;
|
||||
}
|
||||
|
||||
const baseRange = baseRangeRef.current;
|
||||
const currentRange = zoomRangeRef.current;
|
||||
const nextRange = getZoomRangeFromEvent(state, currentRange);
|
||||
const nextRange = getZoomRangeFromEvent(state, baseRange);
|
||||
|
||||
if (!nextRange || isSameZoomRange(nextRange, currentRange)) {
|
||||
return;
|
||||
@@ -172,10 +150,11 @@ export function HistoryChart({
|
||||
|
||||
return (
|
||||
<HistoryChartArea
|
||||
hasData={series.length > 0}
|
||||
avgLineMode={avgLineMode}
|
||||
hasData={displayHasData}
|
||||
hasSelection={tags.length > 0}
|
||||
loading={loading}
|
||||
option={option}
|
||||
option={displayOption}
|
||||
onDataZoom={handleDataZoom}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import type { EChartsOption } from 'echarts';
|
||||
import ReactEChartsCore from 'echarts-for-react/esm/core.js';
|
||||
import { useMemo } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useRef } from 'react';
|
||||
import type { WheelEvent } from 'react';
|
||||
import type { DataZoomEventBatch } from './chartTypes';
|
||||
import { echarts } from './historyChartEcharts';
|
||||
import type { AvgLineMode } from './chartTypes';
|
||||
|
||||
type HistoryChartAreaProps = {
|
||||
avgLineMode: AvgLineMode;
|
||||
hasData: boolean;
|
||||
hasSelection: boolean;
|
||||
loading: boolean;
|
||||
@@ -12,26 +15,85 @@ type HistoryChartAreaProps = {
|
||||
onDataZoom: (event: DataZoomEventBatch) => void;
|
||||
};
|
||||
|
||||
/** Включает или выключает нативный X-зум колесом, чтобы Shift + колесо работал только по Y. */
|
||||
function setXAxisWheelZoom(chart: ReturnType<ReactEChartsCore['getEchartsInstance']>, enabled: boolean): void {
|
||||
chart.setOption(
|
||||
{
|
||||
dataZoom: [
|
||||
{
|
||||
id: 'history-x-inside',
|
||||
zoomOnMouseWheel: enabled,
|
||||
},
|
||||
],
|
||||
},
|
||||
{ lazyUpdate: true },
|
||||
);
|
||||
}
|
||||
|
||||
/** Отвечает только за визуальную область графика: placeholder или ECharts canvas. */
|
||||
export function HistoryChartArea({
|
||||
avgLineMode,
|
||||
hasData,
|
||||
hasSelection,
|
||||
loading,
|
||||
option,
|
||||
onDataZoom,
|
||||
}: HistoryChartAreaProps) {
|
||||
const chartRef = useRef<InstanceType<typeof ReactEChartsCore> | null>(null);
|
||||
const xWheelZoomEnabledRef = useRef(true);
|
||||
const onChartEvents = useMemo(
|
||||
() => ({
|
||||
datazoom: onDataZoom,
|
||||
}),
|
||||
[onDataZoom],
|
||||
);
|
||||
const updateXAxisWheelZoom = useCallback((enabled: boolean) => {
|
||||
const chart = chartRef.current?.getEchartsInstance();
|
||||
|
||||
if (!chart || xWheelZoomEnabledRef.current === enabled) {
|
||||
return;
|
||||
}
|
||||
|
||||
xWheelZoomEnabledRef.current = enabled;
|
||||
setXAxisWheelZoom(chart, enabled);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Shift') {
|
||||
updateXAxisWheelZoom(false);
|
||||
}
|
||||
};
|
||||
const handleKeyUp = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Shift') {
|
||||
updateXAxisWheelZoom(true);
|
||||
}
|
||||
};
|
||||
const handleBlur = () => updateXAxisWheelZoom(true);
|
||||
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
window.addEventListener('keyup', handleKeyUp);
|
||||
window.addEventListener('blur', handleBlur);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('keydown', handleKeyDown);
|
||||
window.removeEventListener('keyup', handleKeyUp);
|
||||
window.removeEventListener('blur', handleBlur);
|
||||
};
|
||||
}, [updateXAxisWheelZoom]);
|
||||
|
||||
const handleWheelCapture = useCallback(
|
||||
(event: WheelEvent<HTMLDivElement>) => {
|
||||
updateXAxisWheelZoom(!event.shiftKey);
|
||||
},
|
||||
[updateXAxisWheelZoom],
|
||||
);
|
||||
|
||||
if (!hasSelection) {
|
||||
return <div className="chart-placeholder">Разверните список показателей и выберите серию для графика</div>;
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
if (!hasData && loading) {
|
||||
return <div className="chart-placeholder">Загрузка графика...</div>;
|
||||
}
|
||||
|
||||
@@ -39,5 +101,17 @@ export function HistoryChartArea({
|
||||
return <div className="chart-placeholder">Нет данных для выбранного диапазона</div>;
|
||||
}
|
||||
|
||||
return <ReactEChartsCore echarts={echarts} option={option} className="history-chart" onEvents={onChartEvents} lazyUpdate />;
|
||||
return (
|
||||
<div className="history-chart-shell" onWheelCapture={handleWheelCapture}>
|
||||
<ReactEChartsCore
|
||||
key={avgLineMode}
|
||||
ref={chartRef}
|
||||
echarts={echarts}
|
||||
option={option}
|
||||
className="history-chart"
|
||||
onEvents={onChartEvents}
|
||||
lazyUpdate
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import type { AvgLineMode } from './chartTypes';
|
||||
|
||||
type HistoryChartAvgLineModeControlProps = {
|
||||
value: AvgLineMode;
|
||||
onChange: (mode: AvgLineMode) => void;
|
||||
};
|
||||
|
||||
const AVG_LINE_MODES: Array<{ value: AvgLineMode; label: string }> = [
|
||||
{ value: 'auto', label: 'Авто' },
|
||||
{ value: 'show', label: 'Рисовать' },
|
||||
{ value: 'hide', label: 'Скрывать' },
|
||||
];
|
||||
|
||||
export function HistoryChartAvgLineModeControl({ value, onChange }: HistoryChartAvgLineModeControlProps) {
|
||||
return (
|
||||
<div className="archive-toolbar-segmented-control archive-avgline-mode-control" aria-label="Режим соединительной линии avg">
|
||||
<span>Соединительная линия</span>
|
||||
<div className="segmented history-chart-line-mode">
|
||||
{AVG_LINE_MODES.map((mode) => (
|
||||
<button
|
||||
key={mode.value}
|
||||
type="button"
|
||||
className={mode.value === value ? 'segmented__button--active' : undefined}
|
||||
onClick={() => onChange(mode.value)}
|
||||
aria-pressed={mode.value === value}
|
||||
>
|
||||
{mode.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,17 @@
|
||||
import type { HistoryAxisLabelFormat } from '../../utils/historyGranularity';
|
||||
|
||||
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, slotMs?: number];
|
||||
|
||||
export type HistoryBucketValue = [...AvgPointValue, slotMs: number];
|
||||
export type HistoryBucketValue = [
|
||||
time: number,
|
||||
avg: number,
|
||||
min: number,
|
||||
max: number,
|
||||
count: number,
|
||||
slotMs: number,
|
||||
];
|
||||
|
||||
export type AvgLineMode = 'auto' | 'show' | 'hide';
|
||||
|
||||
export type HistoryZoomRange = {
|
||||
from: string;
|
||||
|
||||
92
src/features/history-chart/historyChartAvgLineSeries.ts
Normal file
92
src/features/history-chart/historyChartAvgLineSeries.ts
Normal file
@@ -0,0 +1,92 @@
|
||||
import type { LineSeriesOption, SeriesOption } from 'echarts';
|
||||
import type { HistoryPoint } from '../../entities/history/types';
|
||||
import { parseGranulateMs } from '../../utils/historyGranularity';
|
||||
import { SERIES_COLORS } from './historyChartSeries';
|
||||
|
||||
type AvgLineSeriesValue = [time: number, avg: number, min: number, max: number, count: number, slotMs: number];
|
||||
type AvgLineSeriesPoint = AvgLineSeriesValue | null;
|
||||
|
||||
function isFinitePoint(point: HistoryPoint): boolean {
|
||||
return [point.avg_value, point.min_value, point.max_value].every(Number.isFinite);
|
||||
}
|
||||
|
||||
function createAvgLineData(points: HistoryPoint[], granulate: string, breakOnGaps: boolean): AvgLineSeriesPoint[] {
|
||||
const slotMs = parseGranulateMs(granulate);
|
||||
const finitePoints = points.filter(isFinitePoint);
|
||||
|
||||
if (!breakOnGaps) {
|
||||
return finitePoints.map((point) => [
|
||||
new Date(point.time).getTime(),
|
||||
point.avg_value,
|
||||
point.min_value,
|
||||
point.max_value,
|
||||
point.point_count,
|
||||
slotMs,
|
||||
]);
|
||||
}
|
||||
|
||||
return finitePoints.flatMap((point, index) => {
|
||||
const currentTime = new Date(point.time).getTime();
|
||||
const currentPoint: AvgLineSeriesValue = [
|
||||
currentTime,
|
||||
point.avg_value,
|
||||
point.min_value,
|
||||
point.max_value,
|
||||
point.point_count,
|
||||
slotMs,
|
||||
];
|
||||
|
||||
if (index === 0) {
|
||||
return [currentPoint];
|
||||
}
|
||||
|
||||
const previousTime = new Date(finitePoints[index - 1].time).getTime();
|
||||
const hasAcceptableGap = currentTime - previousTime <= slotMs * 50;
|
||||
|
||||
return hasAcceptableGap ? [currentPoint] : [null, currentPoint];
|
||||
});
|
||||
}
|
||||
|
||||
export function createAvgLineSeries(
|
||||
points: HistoryPoint[],
|
||||
index: number,
|
||||
label: string,
|
||||
granulate: string,
|
||||
showAvgLine: boolean,
|
||||
breakOnGaps: boolean,
|
||||
): SeriesOption[] {
|
||||
if (!showAvgLine) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const color = SERIES_COLORS[index % SERIES_COLORS.length];
|
||||
|
||||
return [
|
||||
{
|
||||
name: `${label} avg-line`,
|
||||
type: 'line',
|
||||
data: createAvgLineData(points, granulate, breakOnGaps),
|
||||
encode: {
|
||||
x: 0,
|
||||
y: 1,
|
||||
},
|
||||
smooth: true,
|
||||
connectNulls: false,
|
||||
showSymbol: false,
|
||||
symbol: 'none',
|
||||
silent: true,
|
||||
tooltip: {
|
||||
show: false,
|
||||
},
|
||||
lineStyle: {
|
||||
color,
|
||||
width: 1.5,
|
||||
opacity: 0.78,
|
||||
},
|
||||
emphasis: {
|
||||
disabled: true,
|
||||
},
|
||||
z: 4,
|
||||
} as LineSeriesOption,
|
||||
];
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { CustomChart } from 'echarts/charts';
|
||||
import { CustomChart, LineChart } from 'echarts/charts';
|
||||
import {
|
||||
DataZoomComponent,
|
||||
GridComponent,
|
||||
@@ -10,6 +10,7 @@ import { CanvasRenderer } from 'echarts/renderers';
|
||||
|
||||
echarts.use([
|
||||
CustomChart,
|
||||
LineChart,
|
||||
GridComponent,
|
||||
LegendComponent,
|
||||
TooltipComponent,
|
||||
|
||||
@@ -56,11 +56,68 @@ export function formatAxisDate(value: number, labelFormat: HistoryAxisLabelForma
|
||||
|
||||
function formatChartValue(value: number): string {
|
||||
return new Intl.NumberFormat('ru-RU', {
|
||||
maximumFractionDigits: Math.abs(value) >= 100 ? 2 : 3,
|
||||
maximumFractionDigits:
|
||||
Math.abs(value) >= 1000 ? 0
|
||||
: Math.abs(value) >= 100 ? 1
|
||||
: Math.abs(value) >= 10 ? 2
|
||||
: Math.abs(value) >= 1 ? 3
|
||||
: 4,
|
||||
}).format(value);
|
||||
}
|
||||
|
||||
/** Показывает одно значение, если min/avg/max визуально совпадают. */
|
||||
/** Форматирует полную дату и время для начала/конца интервала в tooltip. */
|
||||
function formatTooltipDateTime(value: number): string {
|
||||
return new Intl.DateTimeFormat('ru-RU', {
|
||||
day: '2-digit',
|
||||
month: '2-digit',
|
||||
year: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
}).format(new Date(value));
|
||||
}
|
||||
|
||||
/** Форматирует только время, когда конец интервала находится в тот же день. */
|
||||
function formatTooltipTime(value: number): string {
|
||||
return new Intl.DateTimeFormat('ru-RU', {
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
}).format(new Date(value));
|
||||
}
|
||||
|
||||
/** Проверяет, можно ли показать конец интервала без повторения даты. */
|
||||
function isSameDate(first: number, second: number): boolean {
|
||||
const firstDate = new Date(first);
|
||||
const secondDate = new Date(second);
|
||||
|
||||
return (
|
||||
firstDate.getFullYear() === secondDate.getFullYear()
|
||||
&& firstDate.getMonth() === secondDate.getMonth()
|
||||
&& firstDate.getDate() === secondDate.getDate()
|
||||
);
|
||||
}
|
||||
|
||||
/** Показывает bucket графика как интервал текущей грануляции, а не как одну точку времени. */
|
||||
function formatTooltipInterval(value: AvgPointValue): string {
|
||||
const time = value[0];
|
||||
const slotMs = value[5];
|
||||
|
||||
if (!slotMs) {
|
||||
return formatTooltipDateTime(time);
|
||||
}
|
||||
|
||||
const from = time - slotMs / 2;
|
||||
const to = time + slotMs / 2;
|
||||
|
||||
if (isSameDate(from, to)) {
|
||||
return `${formatTooltipDateTime(from)} — ${formatTooltipTime(to)}`;
|
||||
}
|
||||
|
||||
return `${formatTooltipDateTime(from)} — ${formatTooltipDateTime(to)}`;
|
||||
}
|
||||
|
||||
/** Форматирует значение tooltip: одно число для min=avg=max или среднее с диапазоном. */
|
||||
function formatTooltipValue(value: AvgPointValue): string {
|
||||
const avg = formatChartValue(value[1]);
|
||||
const min = formatChartValue(value[2]);
|
||||
@@ -70,7 +127,7 @@ function formatTooltipValue(value: AvgPointValue): string {
|
||||
return avg;
|
||||
}
|
||||
|
||||
return `min ${min} · avg ${avg} · max ${max}`;
|
||||
return `сред. ${avg} (${min} .. ${max})`;
|
||||
}
|
||||
|
||||
function isAvgPointValue(value: unknown): value is AvgPointValue {
|
||||
@@ -89,14 +146,8 @@ export function formatTooltip(params: unknown): string {
|
||||
return '';
|
||||
}
|
||||
|
||||
const header = new Intl.DateTimeFormat('ru-RU', {
|
||||
day: '2-digit',
|
||||
month: '2-digit',
|
||||
year: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
}).format(new Date(firstValue[0]));
|
||||
const time = firstValue[0];
|
||||
const header = formatTooltipDateTime(time);
|
||||
|
||||
const rows = avgItems.map((item) => {
|
||||
const value = item.value as AvgPointValue;
|
||||
@@ -104,8 +155,7 @@ export function formatTooltip(params: unknown): string {
|
||||
'<div class="chart-tooltip-row">',
|
||||
`<span class="chart-tooltip-label" style="--chart-tooltip-marker-color:${item.color ?? 'currentColor'};">${item.seriesName ?? ''}</span>`,
|
||||
'<strong>',
|
||||
formatTooltipValue(value),
|
||||
value[4] > 1 ? ` · ${value[4]} точек` : '',
|
||||
formatChartValue(value[1]),
|
||||
'</strong>',
|
||||
'</div>',
|
||||
].join('');
|
||||
|
||||
@@ -20,6 +20,15 @@ export const SERIES_COLORS = [
|
||||
'#A7B3FF',
|
||||
];
|
||||
|
||||
const BUCKET = {
|
||||
time: 0,
|
||||
avg: 1,
|
||||
min: 2,
|
||||
max: 3,
|
||||
count: 4,
|
||||
slotMs: 5,
|
||||
} as const;
|
||||
|
||||
type CartesianCoordSys = {
|
||||
x: number;
|
||||
y: number;
|
||||
@@ -27,13 +36,44 @@ type CartesianCoordSys = {
|
||||
height: number;
|
||||
};
|
||||
|
||||
type ChartArea = CartesianCoordSys;
|
||||
|
||||
type BucketValues = {
|
||||
time: number;
|
||||
avg: number;
|
||||
min: number;
|
||||
max: number;
|
||||
slotMs: number;
|
||||
};
|
||||
|
||||
/** Ограничивает число заданными границами, чтобы фигуры не выходили за canvas графика. */
|
||||
function clamp(value: number, min: number, max: number): number {
|
||||
return Math.min(max, Math.max(min, value));
|
||||
}
|
||||
|
||||
/** Создает вертикальный градиент min..max с максимальной яркостью в позиции avg. */
|
||||
function createAvgGradientStops(color: string, avgOffset: number) {
|
||||
const softZone = 0.18;
|
||||
|
||||
return [
|
||||
{ offset: 0, color: `${color}00` },
|
||||
{ offset: clamp(avgOffset - softZone, 0, 1), color: `${color}22` },
|
||||
{ offset: avgOffset, color: `${color}70` },
|
||||
{ offset: clamp(avgOffset + softZone, 0, 1), color: `${color}22` },
|
||||
{ offset: 1, color: `${color}00` },
|
||||
].sort((first, second) => first.offset - second.offset);
|
||||
}
|
||||
|
||||
/** Проверяет, что точку можно безопасно отрисовать на графике. */
|
||||
function isFinitePoint(point: HistoryPoint): boolean {
|
||||
return [point.avg_value, point.min_value, point.max_value].every(Number.isFinite);
|
||||
}
|
||||
|
||||
/** Упаковывает один bucket API в компактный tuple для custom series ECharts. */
|
||||
/** Упаковывает bucket в tuple для custom series ECharts. */
|
||||
function createBucketData(points: HistoryPoint[], slotMs: number): HistoryBucketValue[] {
|
||||
return points.filter(isFinitePoint).map((point) => [
|
||||
const finitePoints = points.filter(isFinitePoint);
|
||||
|
||||
return finitePoints.map((point) => [
|
||||
new Date(point.time).getTime(),
|
||||
point.avg_value,
|
||||
point.min_value,
|
||||
@@ -43,89 +83,108 @@ function createBucketData(points: HistoryPoint[], slotMs: number): HistoryBucket
|
||||
]);
|
||||
}
|
||||
|
||||
/** Рисует один 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));
|
||||
/** Читает tuple bucket-а из ECharts API и возвращает значения с понятными именами. */
|
||||
function readBucketValues(api: CustomSeriesRenderItemAPI): BucketValues {
|
||||
return {
|
||||
time: Number(api.value(BUCKET.time)),
|
||||
avg: Number(api.value(BUCKET.avg)),
|
||||
min: Number(api.value(BUCKET.min)),
|
||||
max: Number(api.value(BUCKET.max)),
|
||||
slotMs: Number(api.value(BUCKET.slotMs)),
|
||||
};
|
||||
}
|
||||
|
||||
// ECharts отдает размеры области графика в runtime, но в публичных типах
|
||||
// они не описаны. Поэтому держим cast локально рядом с clipping-логикой.
|
||||
const coordSys = params.coordSys as unknown as CartesianCoordSys;
|
||||
/** Считает пиксельные фигуры одного bucket-а и обрезает их по области графика. */
|
||||
function createBucketShapes(api: CustomSeriesRenderItemAPI, values: BucketValues, chartArea: ChartArea) {
|
||||
const avgPoint = api.coord([values.time, values.avg]);
|
||||
const minPoint = api.coord([values.time, values.min]);
|
||||
const maxPoint = api.coord([values.time, values.max]);
|
||||
const slotStart = api.coord([values.time - values.slotMs / 2, values.avg]);
|
||||
const slotEnd = api.coord([values.time + values.slotMs / 2, values.avg]);
|
||||
|
||||
// Переводим координаты данных (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,
|
||||
);
|
||||
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 {
|
||||
avgPoint,
|
||||
avgShape,
|
||||
avgY,
|
||||
rangeShape,
|
||||
};
|
||||
}
|
||||
|
||||
/** Рисует один bucket: min..max слот и горизонтальный avg-маркер. */
|
||||
function renderBucket(color: string) {
|
||||
return (params: CustomSeriesRenderItemParams, api: CustomSeriesRenderItemAPI): CustomSeriesRenderItemReturn => {
|
||||
const values = readBucketValues(api);
|
||||
|
||||
// ECharts отдает размеры области графика в runtime, но в публичных типах они не описаны.
|
||||
const chartArea = params.coordSys as unknown as ChartArea;
|
||||
const bucketShapes = createBucketShapes(api, values, chartArea);
|
||||
|
||||
if (!bucketShapes) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const avgOffset = clamp(
|
||||
(bucketShapes.avgY - bucketShapes.rangeShape.y) / bucketShapes.rangeShape.height,
|
||||
0,
|
||||
1,
|
||||
);
|
||||
|
||||
return {
|
||||
type: 'group',
|
||||
children: [
|
||||
{
|
||||
type: 'rect',
|
||||
shape: rangeShape,
|
||||
shape: bucketShapes.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` },
|
||||
]),
|
||||
fill: new graphic.LinearGradient(0, 0, 0, 1, createAvgGradientStops(color, avgOffset)),
|
||||
},
|
||||
},
|
||||
...(avgShape ? [{
|
||||
...(bucketShapes.avgShape
|
||||
? [{
|
||||
type: 'rect' as const,
|
||||
shape: avgShape,
|
||||
shape: bucketShapes.avgShape,
|
||||
style: {
|
||||
fill: color,
|
||||
},
|
||||
}] : []),
|
||||
}]
|
||||
: []),
|
||||
],
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
/** Создает отдельный временной слот min..max с акцентом на avg для каждой точки history. */
|
||||
export function createSeriesOptions(points: HistoryPoint[], index: number, label: string, granulate: string): SeriesOption[] {
|
||||
/** Создает bucket-серию на тег: min..max слот и горизонтальный avg-маркер. */
|
||||
export function createSeriesOptions(
|
||||
points: HistoryPoint[],
|
||||
index: number,
|
||||
label: string,
|
||||
granulate: string,
|
||||
): SeriesOption[] {
|
||||
const color = SERIES_COLORS[index % SERIES_COLORS.length];
|
||||
const data = createBucketData(points, parseGranulateMs(granulate));
|
||||
|
||||
return [
|
||||
{
|
||||
name: label,
|
||||
type: 'custom',
|
||||
data,
|
||||
data: createBucketData(points, parseGranulateMs(granulate)),
|
||||
renderItem: renderBucket(color),
|
||||
encode: {
|
||||
x: 0,
|
||||
y: [1, 2, 3],
|
||||
x: BUCKET.time,
|
||||
y: [BUCKET.avg, BUCKET.min, BUCKET.max],
|
||||
},
|
||||
itemStyle: {
|
||||
color,
|
||||
|
||||
97
src/features/history-chart/historyChartZoom.ts
Normal file
97
src/features/history-chart/historyChartZoom.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
import { getHistoryGranularity } from '../../utils/historyGranularity';
|
||||
import type { DataZoomState, HistoryZoomRange } from './chartTypes';
|
||||
|
||||
export const ZOOM_REQUEST_DELAY_MS = 180;
|
||||
|
||||
export function isXAxisDataZoom(state: DataZoomState): boolean {
|
||||
return state.dataZoomId?.startsWith('history-x-') || state.dataZoomIndex === 0 || state.dataZoomIndex === 1;
|
||||
}
|
||||
|
||||
/** Собирает начальный zoom-диапазон из внешних props графика. */
|
||||
export function createInitialZoomRange(range: HistoryZoomRange): HistoryZoomRange {
|
||||
return range;
|
||||
}
|
||||
|
||||
/** Создает zoom-диапазон из миллисекунд и подбирает для него грануляцию. */
|
||||
function createZoomRange(fromMs: number, toMs: number): HistoryZoomRange {
|
||||
const from = new Date(fromMs).toISOString();
|
||||
const to = new Date(toMs).toISOString();
|
||||
|
||||
return {
|
||||
from,
|
||||
to,
|
||||
...getHistoryGranularity(from, to),
|
||||
};
|
||||
}
|
||||
|
||||
/** Достает подинтервал X-зума из события ECharts. */
|
||||
export function getZoomRangeFromEvent(state: DataZoomState, baseRange: HistoryZoomRange): HistoryZoomRange | null {
|
||||
const baseFromMs = new Date(baseRange.from).getTime();
|
||||
const baseToMs = new Date(baseRange.to).getTime();
|
||||
const baseSpanMs = baseToMs - baseFromMs;
|
||||
|
||||
if (!Number.isFinite(baseFromMs) || !Number.isFinite(baseToMs) || baseSpanMs <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const startValue = Number(state.startValue);
|
||||
const endValue = Number(state.endValue);
|
||||
let nextFromMs = Number.isFinite(startValue) ? startValue : undefined;
|
||||
let nextToMs = Number.isFinite(endValue) ? endValue : undefined;
|
||||
|
||||
// ECharts иногда не передает startValue/endValue, поэтому используем проценты start/end.
|
||||
if (nextFromMs === undefined || nextToMs === undefined) {
|
||||
const start = Number(state.start);
|
||||
const end = Number(state.end);
|
||||
|
||||
if (!Number.isFinite(start) || !Number.isFinite(end)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
nextFromMs = baseFromMs + (baseSpanMs * start) / 100;
|
||||
nextToMs = baseFromMs + (baseSpanMs * end) / 100;
|
||||
}
|
||||
|
||||
const fromMs = Math.max(baseFromMs, Math.min(nextFromMs, nextToMs));
|
||||
const toMs = Math.min(baseToMs, Math.max(nextFromMs, nextToMs));
|
||||
|
||||
return toMs > fromMs ? createZoomRange(fromMs, toMs) : null;
|
||||
}
|
||||
|
||||
/** Проверяет, что lazy zoom не пытается повторно применить тот же диапазон. */
|
||||
export function isSameZoomRange(left: HistoryZoomRange, right: HistoryZoomRange): boolean {
|
||||
return left.from === right.from && left.to === right.to && left.granulate === right.granulate;
|
||||
}
|
||||
|
||||
/** Вычисляет, какую часть верхнеуровневого периода занимает текущий пользовательский zoom. */
|
||||
export function createDataZoomState(baseRange: HistoryZoomRange, zoomRange: HistoryZoomRange): DataZoomState {
|
||||
// Верхнеуровневый период берем из инпутов "С/По" и считаем его полными 0..100%.
|
||||
const baseFromMs = new Date(baseRange.from).getTime();
|
||||
const baseToMs = new Date(baseRange.to).getTime();
|
||||
|
||||
// Пользовательский zoom живет внутри верхнеуровневого периода и выделяется на нижней шкале.
|
||||
const zoomFromMs = new Date(zoomRange.from).getTime();
|
||||
const zoomToMs = new Date(zoomRange.to).getTime();
|
||||
const baseSpanMs = baseToMs - baseFromMs;
|
||||
|
||||
// Если даты некорректны, показываем весь период, чтобы не ломать управление графиком.
|
||||
if (
|
||||
!Number.isFinite(baseFromMs) ||
|
||||
!Number.isFinite(baseToMs) ||
|
||||
!Number.isFinite(zoomFromMs) ||
|
||||
!Number.isFinite(zoomToMs) ||
|
||||
baseSpanMs <= 0
|
||||
) {
|
||||
return { start: 0, end: 100 };
|
||||
}
|
||||
|
||||
// Переводим абсолютные даты zoom-а в проценты относительно верхнеуровневого периода.
|
||||
const start = ((zoomFromMs - baseFromMs) / baseSpanMs) * 100;
|
||||
const end = ((zoomToMs - baseFromMs) / baseSpanMs) * 100;
|
||||
|
||||
// Ограничиваем значения диапазоном 0..100, чтобы ECharts не получил выход за шкалу.
|
||||
return {
|
||||
start: Math.max(0, Math.min(100, start)),
|
||||
end: Math.max(0, Math.min(100, end)),
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useMemo } from 'react';
|
||||
import { useQueries } from '@tanstack/react-query';
|
||||
import { keepPreviousData, useQueries } from '@tanstack/react-query';
|
||||
import { getHistory } from '../../entities/history/api';
|
||||
import type { HistoryPoint } from '../../entities/history/types';
|
||||
|
||||
@@ -35,6 +35,7 @@ export function useHistoryChartQueries({
|
||||
queryKey: ['history', edge, tag, from, to, granulate],
|
||||
queryFn: ({ signal }: { signal: AbortSignal }) => getHistory({ edge, tag, from, to, granulate }, signal),
|
||||
enabled,
|
||||
placeholderData: keepPreviousData,
|
||||
})),
|
||||
});
|
||||
|
||||
|
||||
@@ -1,14 +1,26 @@
|
||||
import { useMemo } from 'react';
|
||||
import type { SeriesOption } from 'echarts';
|
||||
import { createAvgLineSeries } from './historyChartAvgLineSeries';
|
||||
import { createSeriesOptions } from './historyChartSeries';
|
||||
import type { HistoryChartLineData } from './useHistoryChartQueries';
|
||||
import type { AvgLineMode } from './chartTypes';
|
||||
|
||||
export function useHistoryChartSeries(lines: HistoryChartLineData[], granulate: string): SeriesOption[] {
|
||||
export function useHistoryChartSeries(
|
||||
lines: HistoryChartLineData[],
|
||||
granulate: string,
|
||||
avgLineMode: AvgLineMode,
|
||||
showAvgLine: boolean,
|
||||
): SeriesOption[] {
|
||||
return useMemo(
|
||||
() =>
|
||||
lines.flatMap((line) =>
|
||||
line.rows.length ? createSeriesOptions(line.rows, line.index, line.label, granulate) : [],
|
||||
line.rows.length
|
||||
? [
|
||||
...createSeriesOptions(line.rows, line.index, line.label, granulate),
|
||||
...createAvgLineSeries(line.rows, line.index, line.label, granulate, showAvgLine, avgLineMode === 'auto'),
|
||||
]
|
||||
: [],
|
||||
),
|
||||
[granulate, lines],
|
||||
[granulate, lines, showAvgLine, avgLineMode],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,66 @@
|
||||
.history-chart-shell,
|
||||
.history-chart {
|
||||
width: 100%;
|
||||
height: 440px;
|
||||
}
|
||||
|
||||
.history-chart-shell .history-chart {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.history-chart-shell {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.history-chart-controls {
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
right: 12px;
|
||||
z-index: 2;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.history-chart-line-mode {
|
||||
padding: 3px;
|
||||
}
|
||||
|
||||
.archive-avgline-mode-control .history-chart-line-mode button {
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
.archive-avgline-mode-control .history-chart-line-mode button:first-child {
|
||||
border-top-left-radius: var(--radius);
|
||||
border-bottom-left-radius: var(--radius);
|
||||
}
|
||||
|
||||
.archive-avgline-mode-control .history-chart-line-mode button:last-child {
|
||||
border-top-right-radius: var(--radius);
|
||||
border-bottom-right-radius: var(--radius);
|
||||
}
|
||||
|
||||
.segmented--range-preset button {
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
.segmented--range-preset button:first-child {
|
||||
border-top-left-radius: var(--radius);
|
||||
border-bottom-left-radius: var(--radius);
|
||||
}
|
||||
|
||||
.segmented--range-preset button:last-child {
|
||||
border-top-right-radius: var(--radius);
|
||||
border-bottom-right-radius: var(--radius);
|
||||
}
|
||||
|
||||
.history-chart-line-mode button {
|
||||
font-size: inherit;
|
||||
}
|
||||
|
||||
.chart-section--archive .history-chart-shell,
|
||||
.chart-section--archive .history-chart {
|
||||
flex: 1;
|
||||
min-height: 520px;
|
||||
@@ -18,10 +76,6 @@
|
||||
border-radius: var(--radius);
|
||||
}
|
||||
|
||||
.chart-tooltip {
|
||||
min-width: 240px;
|
||||
}
|
||||
|
||||
.chart-tooltip-title {
|
||||
margin-bottom: 8px;
|
||||
color: #e5e7eb;
|
||||
@@ -30,7 +84,7 @@
|
||||
|
||||
.chart-tooltip-row {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(90px, 1fr) auto;
|
||||
grid-template-columns: 1fr auto;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
margin-top: 5px;
|
||||
@@ -67,6 +121,7 @@
|
||||
}
|
||||
|
||||
@media (max-width: 680px) {
|
||||
.chart-section--archive .history-chart-shell,
|
||||
.chart-section--archive .history-chart,
|
||||
.chart-section--archive .chart-placeholder {
|
||||
min-height: 420px;
|
||||
|
||||
@@ -73,6 +73,12 @@
|
||||
background: rgba(201, 122, 61, 0.18);
|
||||
}
|
||||
|
||||
.segmented__button--active {
|
||||
border-color: rgba(212, 165, 116, 0.34);
|
||||
background: rgba(201, 122, 61, 0.14);
|
||||
color: #f8fafc;
|
||||
}
|
||||
|
||||
.source-chip,
|
||||
.status-pill,
|
||||
.metric-card__state {
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
gap: 5px;
|
||||
padding: 12px;
|
||||
border: 1px solid rgba(88, 103, 121, 0.42);
|
||||
border-radius: 8px;
|
||||
@@ -27,28 +27,74 @@
|
||||
0 6px 14px rgba(0, 0, 0, 0.28);
|
||||
}
|
||||
|
||||
.metric-widget__tag {
|
||||
flex: 0 0 auto;
|
||||
.metric-widget__id,
|
||||
.metric-widget__name,
|
||||
.metric-widget__reading,
|
||||
.metric-widget__value {
|
||||
min-width: 0;
|
||||
color: #cbd5e1;
|
||||
font-size: 0.74rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.metric-widget__id,
|
||||
.metric-widget__name {
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.metric-widget__id {
|
||||
flex: 0 0 auto;
|
||||
color: #64748b;
|
||||
font-size: 0.62rem;
|
||||
font-weight: 650;
|
||||
letter-spacing: 0.02em;
|
||||
line-height: 1.2;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.metric-widget__name {
|
||||
flex: 0 0 auto;
|
||||
color: #e5e7eb;
|
||||
font-size: 0.82rem;
|
||||
font-weight: 760;
|
||||
line-height: 1.35;
|
||||
white-space: normal;
|
||||
overflow-wrap: anywhere;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
.metric-widget__value {
|
||||
.metric-widget__reading {
|
||||
margin-top: auto;
|
||||
align-self: flex-end;
|
||||
min-width: 0;
|
||||
display: inline-flex;
|
||||
align-items: baseline;
|
||||
justify-content: flex-end;
|
||||
gap: 5px;
|
||||
max-width: 100%;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.metric-widget__value {
|
||||
color: #f8fafc;
|
||||
font-size: 1.1rem;
|
||||
font-weight: 700;
|
||||
font-size: 1.22rem;
|
||||
font-weight: 800;
|
||||
font-variant-numeric: tabular-nums;
|
||||
line-height: 1.2;
|
||||
overflow: hidden;
|
||||
text-align: right;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.metric-widget__unit {
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
color: #94a3b8;
|
||||
font-size: 0.72rem;
|
||||
font-weight: 650;
|
||||
line-height: 1.2;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.metric-mosaic {
|
||||
|
||||
@@ -216,6 +216,14 @@
|
||||
font-size: 0.84rem;
|
||||
}
|
||||
|
||||
.archive-toolbar-segmented-control {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
color: var(--muted);
|
||||
font-size: 0.84rem;
|
||||
}
|
||||
|
||||
.archive-date-input {
|
||||
color-scheme: dark;
|
||||
min-height: 36px;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/** Форматирует числовое значение показателя для карточек и мини-плиток. */
|
||||
export function formatNumber(value: number): string {
|
||||
if (!Number.isFinite(value)) {
|
||||
return '-';
|
||||
export function formatNumber(value: number | null): string {
|
||||
if (value === null || !Number.isFinite(value)) {
|
||||
return '—';
|
||||
}
|
||||
|
||||
return new Intl.NumberFormat('ru-RU', {
|
||||
|
||||
@@ -16,8 +16,9 @@ function isConfiguredLimit(value: number | null): value is number {
|
||||
export function getMetricStatus(item: CurrentItem, now = Date.now()): MetricStatusInfo {
|
||||
const measuredAt = new Date(item.time).getTime();
|
||||
const ageSeconds = Number.isFinite(measuredAt) ? Math.max(0, Math.round((now - measuredAt) / 1000)) : Number.POSITIVE_INFINITY;
|
||||
const belowMin = isConfiguredLimit(item.min) && item.value < item.min;
|
||||
const aboveMax = isConfiguredLimit(item.max) && item.value > item.max;
|
||||
const value = item.value;
|
||||
const belowMin = isConfiguredLimit(value) && isConfiguredLimit(item.min) && value < item.min;
|
||||
const aboveMax = isConfiguredLimit(value) && isConfiguredLimit(item.max) && value > item.max;
|
||||
|
||||
if (belowMin || aboveMax) {
|
||||
return { status: 'critical', label: 'за пределами уставки', ageSeconds };
|
||||
|
||||
@@ -15,7 +15,6 @@ export default defineConfig(({ mode }) => {
|
||||
'/api': {
|
||||
target: DEV_API_URL,
|
||||
changeOrigin: true,
|
||||
rewrite: (path) => path.replace(/^\/api/, ''),
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user