decompose structure
This commit is contained in:
37
src/features/current/model.ts
Normal file
37
src/features/current/model.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import type { CurrentItem } from '../../entities/current/types';
|
||||
|
||||
export function getCurrentItemLabel(item: CurrentItem): string {
|
||||
return item.name?.trim() || item.tag;
|
||||
}
|
||||
|
||||
export function createCurrentTagLabels(items: CurrentItem[]): Record<string, string> {
|
||||
return Object.fromEntries(items.map((item) => [item.tag, getCurrentItemLabel(item)]));
|
||||
}
|
||||
|
||||
export function filterCurrentItems(items: CurrentItem[], search: string): CurrentItem[] {
|
||||
const query = search.trim().toLowerCase();
|
||||
if (!query) {
|
||||
return items;
|
||||
}
|
||||
|
||||
return items.filter((item) =>
|
||||
[item.tag, item.name, item.comment, item.tagGroup, item.unitOfMeasurement]
|
||||
.filter(Boolean)
|
||||
.join(' ')
|
||||
.toLowerCase()
|
||||
.includes(query),
|
||||
);
|
||||
}
|
||||
|
||||
export function getLatestCurrentUpdatedAt(items: CurrentItem[]): Date | undefined {
|
||||
const latest = items.reduce<number | null>((max, item) => {
|
||||
const updatedAt = new Date(item.updatedAt).getTime();
|
||||
return Number.isFinite(updatedAt) && (max === null || updatedAt > max) ? updatedAt : max;
|
||||
}, null);
|
||||
|
||||
return latest === null ? undefined : new Date(latest);
|
||||
}
|
||||
|
||||
export function countLiveCurrentItems(items: CurrentItem[], now = Date.now()): number {
|
||||
return items.filter((item) => (now - new Date(item.time).getTime()) / 1000 <= 30).length;
|
||||
}
|
||||
32
src/features/current/useCurrentEvents.ts
Normal file
32
src/features/current/useCurrentEvents.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { getCurrentEventsUrl } from '../../entities/current/api';
|
||||
import type { CurrentEvent, CurrentResponse } from '../../entities/current/types';
|
||||
|
||||
export function useCurrentEvents(edgeId: string): boolean {
|
||||
const queryClient = useQueryClient();
|
||||
const [connected, setConnected] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!edgeId || typeof EventSource === 'undefined') {
|
||||
setConnected(false);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const eventSource = new EventSource(getCurrentEventsUrl(edgeId));
|
||||
|
||||
eventSource.onopen = () => setConnected(true);
|
||||
eventSource.onerror = () => setConnected(false);
|
||||
eventSource.onmessage = (message) => {
|
||||
const event = JSON.parse(message.data) as CurrentEvent;
|
||||
queryClient.setQueryData<CurrentResponse>(['current', edgeId], event);
|
||||
};
|
||||
|
||||
return () => {
|
||||
eventSource.close();
|
||||
setConnected(false);
|
||||
};
|
||||
}, [edgeId, queryClient]);
|
||||
|
||||
return connected;
|
||||
}
|
||||
11
src/features/current/useCurrentQuery.ts
Normal file
11
src/features/current/useCurrentQuery.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { getCurrent } from '../../entities/current/api';
|
||||
|
||||
export function useCurrentQuery(edgeId: string, eventsConnected: boolean) {
|
||||
return useQuery({
|
||||
queryKey: ['current', edgeId],
|
||||
queryFn: () => getCurrent(edgeId),
|
||||
enabled: Boolean(edgeId),
|
||||
refetchInterval: eventsConnected ? false : 1_000,
|
||||
});
|
||||
}
|
||||
137
src/features/edge-detail/EdgeDetailPage.tsx
Normal file
137
src/features/edge-detail/EdgeDetailPage.tsx
Normal file
@@ -0,0 +1,137 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { useAuth } from '../../auth/authContext';
|
||||
import {
|
||||
countLiveCurrentItems,
|
||||
createCurrentTagLabels,
|
||||
filterCurrentItems,
|
||||
getLatestCurrentUpdatedAt,
|
||||
} from '../current/model';
|
||||
import { useCurrentEvents } from '../current/useCurrentEvents';
|
||||
import { useCurrentQuery } from '../current/useCurrentQuery';
|
||||
import { createRange } from '../history/dateRange';
|
||||
import { useHistoryQuery } from '../history/useHistoryQuery';
|
||||
import { ArchiveView } from './components/ArchiveView';
|
||||
import { EdgeSidebar } from './components/EdgeSidebar';
|
||||
import { EdgeTopbar } from './components/EdgeTopbar';
|
||||
import { EquipmentView } from './components/EquipmentView';
|
||||
import { IndicatorsView } from './components/IndicatorsView';
|
||||
import { OverviewView } from './components/OverviewView';
|
||||
import type { DetailView } from './types';
|
||||
|
||||
type EdgeDetailPageProps = {
|
||||
view: DetailView;
|
||||
};
|
||||
|
||||
/** Собирает раздел выбранной буровой из вкладок текущих данных, архива и оборудования. */
|
||||
export function EdgeDetailPage({ view }: EdgeDetailPageProps) {
|
||||
const navigate = useNavigate();
|
||||
const auth = useAuth();
|
||||
const { edgeId = '' } = useParams();
|
||||
const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
|
||||
const [search, setSearch] = useState('');
|
||||
const [range, setRange] = useState(() => createRange(24));
|
||||
const [selectedTags, setSelectedTags] = useState<string[]>([]);
|
||||
|
||||
const edgePath = `/edges/${encodeURIComponent(edgeId)}`;
|
||||
const currentEventsConnected = useCurrentEvents(edgeId);
|
||||
const current = useCurrentQuery(edgeId, currentEventsConnected);
|
||||
const currentItems = useMemo(() => current.data?.items ?? [], [current.data?.items]);
|
||||
|
||||
const tagLabels = useMemo(() => createCurrentTagLabels(currentItems), [currentItems]);
|
||||
const getTagLabel = (tag: string) => tagLabels[tag] ?? tag;
|
||||
const visibleItems = useMemo(() => filterCurrentItems(currentItems, search), [currentItems, search]);
|
||||
const latestUpdatedAt = useMemo(() => getLatestCurrentUpdatedAt(currentItems), [currentItems]);
|
||||
const liveCount = countLiveCurrentItems(currentItems);
|
||||
const { query: history, granularity: historyGranularity } = useHistoryQuery(edgeId, selectedTags[0], range);
|
||||
|
||||
const toggleTag = (tag: string) => {
|
||||
setSelectedTags((prev) => (prev.includes(tag) ? [] : [tag]));
|
||||
};
|
||||
|
||||
const selectFirstTags = () => {
|
||||
setSelectedTags(visibleItems[0] ? [visibleItems[0].tag] : []);
|
||||
};
|
||||
|
||||
const selectVisibleTags = () => {
|
||||
setSelectedTags(visibleItems[0] ? [visibleItems[0].tag] : []);
|
||||
};
|
||||
|
||||
const clearVisibleTags = () => {
|
||||
const visibleTags = new Set(visibleItems.map((item) => item.tag));
|
||||
setSelectedTags((prev) => prev.filter((tag) => !visibleTags.has(tag)));
|
||||
};
|
||||
|
||||
return (
|
||||
<main className={`app-shell ${sidebarCollapsed ? 'app-shell--sidebar-collapsed' : ''}`}>
|
||||
<EdgeSidebar
|
||||
collapsed={sidebarCollapsed}
|
||||
edgePath={edgePath}
|
||||
view={view}
|
||||
onNavigate={navigate}
|
||||
onToggleCollapsed={() => setSidebarCollapsed((collapsed) => !collapsed)}
|
||||
/>
|
||||
|
||||
<section className={`workspace workspace--${view}`}>
|
||||
<EdgeTopbar
|
||||
authEnabled={auth.enabled}
|
||||
currentEventsConnected={currentEventsConnected}
|
||||
edgeId={edgeId}
|
||||
onBack={() => navigate('/edges')}
|
||||
onLogout={() => void auth.logout()}
|
||||
onRefresh={() => void current.refetch()}
|
||||
/>
|
||||
|
||||
{view === 'overview' ? (
|
||||
<OverviewView
|
||||
edgeId={edgeId}
|
||||
totalTags={currentItems.length}
|
||||
liveCount={liveCount}
|
||||
latestUpdatedAt={latestUpdatedAt}
|
||||
selectedCount={selectedTags.length}
|
||||
onOpenArchive={() => navigate(`${edgePath}/archive`)}
|
||||
onOpenIndicators={() => navigate(`${edgePath}/indicators`)}
|
||||
onOpenEquipment={() => navigate(`${edgePath}/equipment`)}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{view === 'archive' ? (
|
||||
<ArchiveView
|
||||
items={visibleItems}
|
||||
search={search}
|
||||
selectedTags={selectedTags}
|
||||
history={history.data}
|
||||
historyLoading={history.isPending && selectedTags.length > 0}
|
||||
historyGranulate={history.data?.granulate ?? historyGranularity.granulate}
|
||||
historyAxis={historyGranularity}
|
||||
range={range}
|
||||
onSearchChange={setSearch}
|
||||
onRangeChange={setRange}
|
||||
onToggleTag={toggleTag}
|
||||
onSelectFirstTags={selectFirstTags}
|
||||
onSelectVisibleTags={selectVisibleTags}
|
||||
onClearVisibleTags={clearVisibleTags}
|
||||
onClearTags={() => setSelectedTags([])}
|
||||
getTagLabel={getTagLabel}
|
||||
tagLabels={tagLabels}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{view === 'indicators' ? (
|
||||
<IndicatorsView
|
||||
items={visibleItems}
|
||||
search={search}
|
||||
isError={current.isError}
|
||||
error={current.error}
|
||||
selectedTags={selectedTags}
|
||||
getTagLabel={getTagLabel}
|
||||
onSearchChange={setSearch}
|
||||
onToggleTag={toggleTag}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{view === 'equipment' ? <EquipmentView /> : null}
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
186
src/features/edge-detail/components/ArchiveView.tsx
Normal file
186
src/features/edge-detail/components/ArchiveView.tsx
Normal file
@@ -0,0 +1,186 @@
|
||||
import { useState } from 'react';
|
||||
import { CalendarClock, ChevronDown, DatabaseZap, Search } from 'lucide-react';
|
||||
import type { CurrentItem } from '../../../entities/current/types';
|
||||
import type { HistoryResponse } from '../../../entities/history/types';
|
||||
import { HistoryChart } from '../../../features/history-chart/HistoryChart';
|
||||
import { RANGE_PRESETS, createRange, type DateRangeState } from '../../../features/history/dateRange';
|
||||
import { toIsoFromInput } from '../../../utils/format';
|
||||
import type { HistoryGranularity } from '../../../utils/historyGranularity';
|
||||
|
||||
type ArchiveViewProps = {
|
||||
getTagLabel: (tag: string) => string;
|
||||
history?: HistoryResponse;
|
||||
historyAxis: HistoryGranularity;
|
||||
historyGranulate?: string;
|
||||
historyLoading: boolean;
|
||||
items: CurrentItem[];
|
||||
range: DateRangeState;
|
||||
search: string;
|
||||
selectedTags: string[];
|
||||
tagLabels: Record<string, string>;
|
||||
onClearTags: () => void;
|
||||
onClearVisibleTags: () => void;
|
||||
onRangeChange: (value: DateRangeState) => void;
|
||||
onSearchChange: (value: string) => void;
|
||||
onSelectFirstTags: () => void;
|
||||
onSelectVisibleTags: () => void;
|
||||
onToggleTag: (tag: string) => void;
|
||||
};
|
||||
|
||||
export function ArchiveView({
|
||||
getTagLabel,
|
||||
history,
|
||||
historyAxis,
|
||||
historyGranulate,
|
||||
historyLoading,
|
||||
items,
|
||||
range,
|
||||
search,
|
||||
selectedTags,
|
||||
tagLabels,
|
||||
onClearTags,
|
||||
onClearVisibleTags,
|
||||
onRangeChange,
|
||||
onSearchChange,
|
||||
onSelectFirstTags,
|
||||
onSelectVisibleTags,
|
||||
onToggleTag,
|
||||
}: ArchiveViewProps) {
|
||||
const [selectorOpen, setSelectorOpen] = useState(false);
|
||||
const selectedPreview = selectedTags.slice(0, 10);
|
||||
const hiddenSelectedCount = Math.max(0, selectedTags.length - selectedPreview.length);
|
||||
|
||||
return (
|
||||
<section className="chart-section chart-section--archive">
|
||||
<div className="section-header">
|
||||
<div>
|
||||
<span className="page-kicker">
|
||||
<CalendarClock size={14} />
|
||||
История
|
||||
</span>
|
||||
<h2>График параметров</h2>
|
||||
</div>
|
||||
<div className="source-chip">
|
||||
<DatabaseZap size={16} />
|
||||
cloud-v3 · {historyGranulate ?? 'ожидание'}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="archive-tag-panel">
|
||||
<button
|
||||
type="button"
|
||||
className="archive-tag-panel__toggle"
|
||||
onClick={() => setSelectorOpen((open) => !open)}
|
||||
aria-expanded={selectorOpen}
|
||||
>
|
||||
<span>
|
||||
Показатели
|
||||
<strong>
|
||||
{selectedTags.length} выбрано · {items.length} найдено
|
||||
</strong>
|
||||
</span>
|
||||
<ChevronDown size={18} />
|
||||
</button>
|
||||
|
||||
{selectorOpen ? (
|
||||
<div className="tag-selector">
|
||||
<div className="tag-selector__header">
|
||||
<label className="search-box">
|
||||
<Search size={16} />
|
||||
<input value={search} onChange={(event) => onSearchChange(event.target.value)} placeholder="Поиск" />
|
||||
</label>
|
||||
<div className="tag-selector__tools">
|
||||
<button type="button" onClick={onSelectFirstTags}>
|
||||
Первый
|
||||
</button>
|
||||
<button type="button" onClick={onSelectVisibleTags}>
|
||||
Выбрать найденный
|
||||
</button>
|
||||
<button type="button" onClick={onClearVisibleTags}>
|
||||
Снять найденные
|
||||
</button>
|
||||
<button type="button" onClick={onClearTags}>
|
||||
Сбросить все
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="selected-tags">
|
||||
{selectedPreview.length ? (
|
||||
selectedPreview.map((tag) => <span key={tag}>{getTagLabel(tag)}</span>)
|
||||
) : (
|
||||
<span>Не выбрано</span>
|
||||
)}
|
||||
{hiddenSelectedCount > 0 ? <span>+{hiddenSelectedCount}</span> : null}
|
||||
</div>
|
||||
|
||||
<div className="tag-select-list">
|
||||
{items.map((item) => {
|
||||
const selected = selectedTags.includes(item.tag);
|
||||
const label = getTagLabel(item.tag);
|
||||
return (
|
||||
<button
|
||||
key={item.tag}
|
||||
type="button"
|
||||
className={`tag-select-item ${selected ? 'tag-select-item--selected' : ''}`}
|
||||
title={item.tag}
|
||||
onClick={() => onToggleTag(item.tag)}
|
||||
>
|
||||
<span className="tag-select-item__name">
|
||||
<span>{label}</span>
|
||||
{label !== item.tag ? <small>{item.tag}</small> : null}
|
||||
</span>
|
||||
<strong>{item.value.toLocaleString('ru-RU', { maximumFractionDigits: item.precision ?? 3 })}</strong>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="archive-chart">
|
||||
<div className="toolbar">
|
||||
<div className="segmented">
|
||||
{RANGE_PRESETS.map((preset) => (
|
||||
<button key={preset.id} type="button" onClick={() => onRangeChange(createRange(preset.hours))}>
|
||||
{preset.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<label>
|
||||
С
|
||||
<input
|
||||
type="datetime-local"
|
||||
value={range.from}
|
||||
onChange={(event) => onRangeChange({ ...range, from: event.target.value })}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
По
|
||||
<input
|
||||
type="datetime-local"
|
||||
value={range.to}
|
||||
onChange={(event) => onRangeChange({ ...range, to: event.target.value })}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{selectedTags.length ? (
|
||||
<HistoryChart
|
||||
key={`${range.from}:${range.to}:${selectedTags.join(',')}`}
|
||||
data={history}
|
||||
loading={historyLoading}
|
||||
from={toIsoFromInput(range.from)}
|
||||
to={toIsoFromInput(range.to)}
|
||||
tickIntervalMs={historyAxis.tickIntervalMs}
|
||||
labelFormat={historyAxis.labelFormat}
|
||||
tagLabels={tagLabels}
|
||||
/>
|
||||
) : (
|
||||
<div className="chart-placeholder">Разверните список показателей и выберите серию для графика</div>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
70
src/features/edge-detail/components/EdgeSidebar.tsx
Normal file
70
src/features/edge-detail/components/EdgeSidebar.tsx
Normal file
@@ -0,0 +1,70 @@
|
||||
import { Activity, BarChart3, Gauge, Menu, PanelLeftClose, PanelLeftOpen, Wrench } from 'lucide-react';
|
||||
import type { DetailView } from '../types';
|
||||
|
||||
type EdgeSidebarProps = {
|
||||
collapsed: boolean;
|
||||
edgePath: string;
|
||||
view: DetailView;
|
||||
onNavigate: (path: string) => void;
|
||||
onToggleCollapsed: () => void;
|
||||
};
|
||||
|
||||
export function EdgeSidebar({ collapsed, edgePath, view, onNavigate, onToggleCollapsed }: EdgeSidebarProps) {
|
||||
return (
|
||||
<aside className="sidebar">
|
||||
<div className="brand">
|
||||
<img src="/logo.png" alt="" />
|
||||
<div className="brand__text">
|
||||
<strong>Drill UI</strong>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="sidebar-toggle"
|
||||
onClick={onToggleCollapsed}
|
||||
title={collapsed ? 'Развернуть меню' : 'Свернуть меню'}
|
||||
>
|
||||
{collapsed ? <PanelLeftOpen size={18} /> : <PanelLeftClose size={18} />}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<nav className="nav-list" aria-label="Основная навигация">
|
||||
<button className="nav-item nav-item--button" type="button" onClick={() => onNavigate('/edges')}>
|
||||
<Menu size={18} />
|
||||
<span className="nav-label">Буровые</span>
|
||||
</button>
|
||||
<button
|
||||
className={`nav-item nav-item--button ${view === 'overview' ? 'nav-item--active' : ''}`}
|
||||
type="button"
|
||||
onClick={() => onNavigate(edgePath)}
|
||||
>
|
||||
<Gauge size={18} />
|
||||
<span className="nav-label">Обзор</span>
|
||||
</button>
|
||||
<button
|
||||
className={`nav-item nav-item--button ${view === 'archive' ? 'nav-item--active' : ''}`}
|
||||
type="button"
|
||||
onClick={() => onNavigate(`${edgePath}/archive`)}
|
||||
>
|
||||
<BarChart3 size={18} />
|
||||
<span className="nav-label">Архив</span>
|
||||
</button>
|
||||
<button
|
||||
className={`nav-item nav-item--button ${view === 'indicators' ? 'nav-item--active' : ''}`}
|
||||
type="button"
|
||||
onClick={() => onNavigate(`${edgePath}/indicators`)}
|
||||
>
|
||||
<Activity size={18} />
|
||||
<span className="nav-label">Показатели</span>
|
||||
</button>
|
||||
<button
|
||||
className={`nav-item nav-item--button ${view === 'equipment' ? 'nav-item--active' : ''}`}
|
||||
type="button"
|
||||
onClick={() => onNavigate(`${edgePath}/equipment`)}
|
||||
>
|
||||
<Wrench size={18} />
|
||||
<span className="nav-label">Оборудование</span>
|
||||
</button>
|
||||
</nav>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
46
src/features/edge-detail/components/EdgeTopbar.tsx
Normal file
46
src/features/edge-detail/components/EdgeTopbar.tsx
Normal file
@@ -0,0 +1,46 @@
|
||||
import { LogOut, Menu, RefreshCw } from 'lucide-react';
|
||||
|
||||
type EdgeTopbarProps = {
|
||||
authEnabled: boolean;
|
||||
currentEventsConnected: boolean;
|
||||
edgeId: string;
|
||||
onBack: () => void;
|
||||
onLogout: () => void;
|
||||
onRefresh: () => void;
|
||||
};
|
||||
|
||||
export function EdgeTopbar({
|
||||
authEnabled,
|
||||
currentEventsConnected,
|
||||
edgeId,
|
||||
onBack,
|
||||
onLogout,
|
||||
onRefresh,
|
||||
}: EdgeTopbarProps) {
|
||||
return (
|
||||
<header className="topbar">
|
||||
<div>
|
||||
<span className="page-kicker">Операторская панель</span>
|
||||
<h1>Буровая установка {edgeId}</h1>
|
||||
<span className={`current-transport current-transport--${currentEventsConnected ? 'sse' : 'polling'}`}>
|
||||
{currentEventsConnected ? 'SSE live' : 'polling'}
|
||||
</span>
|
||||
</div>
|
||||
<div className="topbar-actions">
|
||||
<button type="button" className="ghost-button" onClick={onBack}>
|
||||
<Menu size={17} />
|
||||
К списку
|
||||
</button>
|
||||
<button type="button" className="icon-button" onClick={onRefresh} title="Обновить данные">
|
||||
<RefreshCw size={18} />
|
||||
</button>
|
||||
{authEnabled ? (
|
||||
<button type="button" className="ghost-button" onClick={onLogout}>
|
||||
<LogOut size={17} />
|
||||
Выйти
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
29
src/features/edge-detail/components/EquipmentView.tsx
Normal file
29
src/features/edge-detail/components/EquipmentView.tsx
Normal file
@@ -0,0 +1,29 @@
|
||||
import { useState } from 'react';
|
||||
import { ToirLightIframe } from '../../../components/ToirLightIframe';
|
||||
|
||||
const ACTIVE_EQUIPMENT_PATH =
|
||||
'/equipment?filter=%7B%22status%22%3A%5B%22Active%22%5D%7D&displayedFilters=%7B%22status%22%3Atrue%7D';
|
||||
|
||||
export function EquipmentView() {
|
||||
const [iframeLoaded, setIframeLoaded] = useState(false);
|
||||
|
||||
return (
|
||||
<section className="equipment-section" aria-label="Активное оборудование">
|
||||
<div className="equipment-frame-shell" aria-busy={!iframeLoaded}>
|
||||
{!iframeLoaded ? (
|
||||
<div className="equipment-frame-loading" role="status" aria-live="polite">
|
||||
<span className="equipment-frame-loading__ring" aria-hidden />
|
||||
<span>Загрузка интерфейса управления оборудованием...</span>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<ToirLightIframe
|
||||
className="equipment-frame"
|
||||
path={ACTIVE_EQUIPMENT_PATH}
|
||||
title="ТОиР light: управление активным оборудованием"
|
||||
onLoad={() => setIframeLoaded(true)}
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
133
src/features/edge-detail/components/IndicatorsView.tsx
Normal file
133
src/features/edge-detail/components/IndicatorsView.tsx
Normal file
@@ -0,0 +1,133 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { Search } from 'lucide-react';
|
||||
import type { CurrentItem } from '../../../entities/current/types';
|
||||
import { MetricCard } from '../../../components/MetricCard';
|
||||
import { formatNumber } from '../../../utils/format';
|
||||
import { getMetricStatus } from '../../../utils/metricStatus';
|
||||
|
||||
type IndicatorsViewProps = {
|
||||
error: unknown;
|
||||
getTagLabel: (tag: string) => string;
|
||||
isError: boolean;
|
||||
items: CurrentItem[];
|
||||
search: string;
|
||||
selectedTags: string[];
|
||||
onSearchChange: (value: string) => void;
|
||||
onToggleTag: (tag: string) => void;
|
||||
};
|
||||
|
||||
export function IndicatorsView({
|
||||
error,
|
||||
getTagLabel,
|
||||
isError,
|
||||
items,
|
||||
search,
|
||||
selectedTags,
|
||||
onSearchChange,
|
||||
onToggleTag,
|
||||
}: IndicatorsViewProps) {
|
||||
const [displayMode, setDisplayMode] = useState<'overview' | 'cards'>('overview');
|
||||
const itemStatuses = useMemo(() => {
|
||||
const now = Date.now();
|
||||
return items.map((item) => ({ item, statusInfo: getMetricStatus(item, now) }));
|
||||
}, [items]);
|
||||
const statusCounts = itemStatuses.reduce(
|
||||
(counts, { statusInfo }) => {
|
||||
counts[statusInfo.status] += 1;
|
||||
return counts;
|
||||
},
|
||||
{ normal: 0, warning: 0, critical: 0 },
|
||||
);
|
||||
|
||||
return (
|
||||
<section className="tags-section">
|
||||
<div className="section-header">
|
||||
<div>
|
||||
<span className="page-kicker">
|
||||
<Search size={14} />
|
||||
Показатели
|
||||
</span>
|
||||
<h2>Текущие значения</h2>
|
||||
</div>
|
||||
<div className="indicator-controls">
|
||||
<div className="view-switch" aria-label="Режим отображения показателей">
|
||||
<button
|
||||
type="button"
|
||||
className={displayMode === 'overview' ? 'view-switch__button--active' : ''}
|
||||
onClick={() => setDisplayMode('overview')}
|
||||
>
|
||||
Картина
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={displayMode === 'cards' ? 'view-switch__button--active' : ''}
|
||||
onClick={() => setDisplayMode('cards')}
|
||||
>
|
||||
Карточки
|
||||
</button>
|
||||
</div>
|
||||
<label className="search-box">
|
||||
<Search size={16} />
|
||||
<input value={search} onChange={(event) => onSearchChange(event.target.value)} placeholder="Поиск показателя" />
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="indicator-summary">
|
||||
<div>
|
||||
<span>Всего</span>
|
||||
<strong>{items.length}</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span>В норме</span>
|
||||
<strong>{statusCounts.normal}</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span>Предупреждение</span>
|
||||
<strong>{statusCounts.warning}</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span>Критично</span>
|
||||
<strong>{statusCounts.critical}</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span>На графике</span>
|
||||
<strong>{selectedTags.length}</strong>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isError ? (
|
||||
<div className="empty-panel">Не удалось загрузить текущие значения: {String(error)}</div>
|
||||
) : displayMode === 'overview' ? (
|
||||
<div className="metric-mosaic">
|
||||
{itemStatuses.map(({ item, statusInfo }) => (
|
||||
<button
|
||||
key={`${item.edge}:${item.tag}`}
|
||||
type="button"
|
||||
className={`metric-tile metric-tile--${statusInfo.status} ${selectedTags.includes(item.tag) ? 'metric-tile--selected' : ''}`}
|
||||
title={`${getTagLabel(item.tag)} (${item.tag}): ${formatNumber(item.value)} · ${statusInfo.label}`}
|
||||
onClick={() => onToggleTag(item.tag)}
|
||||
>
|
||||
<span className="metric-tile__status" />
|
||||
<span className="metric-tile__tag">{getTagLabel(item.tag)}</span>
|
||||
<strong>{formatNumber(item.value)}</strong>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="metric-grid">
|
||||
{itemStatuses.map(({ item, statusInfo }) => (
|
||||
<MetricCard
|
||||
key={`${item.edge}:${item.tag}`}
|
||||
item={item}
|
||||
displayName={getTagLabel(item.tag)}
|
||||
statusInfo={statusInfo}
|
||||
selected={selectedTags.includes(item.tag)}
|
||||
onToggle={onToggleTag}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
72
src/features/edge-detail/components/OverviewView.tsx
Normal file
72
src/features/edge-detail/components/OverviewView.tsx
Normal file
@@ -0,0 +1,72 @@
|
||||
import { Activity, BarChart3, CalendarClock, Wrench } from 'lucide-react';
|
||||
import { formatDateTime } from '../../../utils/format';
|
||||
|
||||
type OverviewViewProps = {
|
||||
edgeId: string;
|
||||
latestUpdatedAt?: Date;
|
||||
liveCount: number;
|
||||
selectedCount: number;
|
||||
totalTags: number;
|
||||
onOpenArchive: () => void;
|
||||
onOpenEquipment: () => void;
|
||||
onOpenIndicators: () => void;
|
||||
};
|
||||
|
||||
export function OverviewView({
|
||||
edgeId,
|
||||
latestUpdatedAt,
|
||||
liveCount,
|
||||
selectedCount,
|
||||
totalTags,
|
||||
onOpenArchive,
|
||||
onOpenEquipment,
|
||||
onOpenIndicators,
|
||||
}: OverviewViewProps) {
|
||||
return (
|
||||
<section className="detail-overview">
|
||||
<div className="summary-grid">
|
||||
<div className="summary-card">
|
||||
<span>Всего показателей</span>
|
||||
<strong>{totalTags}</strong>
|
||||
</div>
|
||||
<div className="summary-card">
|
||||
<span>Live</span>
|
||||
<strong>{liveCount}</strong>
|
||||
</div>
|
||||
<div className="summary-card">
|
||||
<span>Выбрано для графика</span>
|
||||
<strong>{selectedCount}</strong>
|
||||
</div>
|
||||
<div className="summary-card">
|
||||
<span>Последнее обновление</span>
|
||||
<strong>{latestUpdatedAt ? formatDateTime(latestUpdatedAt) : '-'}</strong>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<section className="detail-action-panel">
|
||||
<div>
|
||||
<span className="page-kicker">Разделы</span>
|
||||
<h2>{edgeId}</h2>
|
||||
</div>
|
||||
<div className="detail-action-grid">
|
||||
<button type="button" onClick={onOpenIndicators}>
|
||||
<Activity size={18} />
|
||||
Текущие показатели
|
||||
</button>
|
||||
<button type="button" onClick={onOpenArchive}>
|
||||
<BarChart3 size={18} />
|
||||
Архив и график
|
||||
</button>
|
||||
<button type="button" onClick={onOpenEquipment}>
|
||||
<Wrench size={18} />
|
||||
Состояние оборудования
|
||||
</button>
|
||||
<button type="button">
|
||||
<CalendarClock size={18} />
|
||||
Техническое обслуживание
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
1
src/features/edge-detail/types.ts
Normal file
1
src/features/edge-detail/types.ts
Normal file
@@ -0,0 +1 @@
|
||||
export type DetailView = 'overview' | 'archive' | 'indicators' | 'equipment';
|
||||
162
src/features/edges-dashboard/EdgesDashboard.tsx
Normal file
162
src/features/edges-dashboard/EdgesDashboard.tsx
Normal file
@@ -0,0 +1,162 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { ArrowRight, Clock3, Gauge, LogOut, RefreshCw, Search, ShieldAlert, Wrench } from 'lucide-react';
|
||||
import edgeImage from '../../assets/edge.png';
|
||||
import { getEdges } from '../../entities/edge/api';
|
||||
import type { EdgeItem } from '../../entities/edge/types';
|
||||
import { useAuth } from '../../auth/authContext';
|
||||
|
||||
type EdgesDashboardProps = {
|
||||
onOpenEdge: (edgeId: string) => void;
|
||||
onOpenEquipment: (edgeId: string) => void;
|
||||
};
|
||||
|
||||
function getEdgeTitle(edge: EdgeItem): string {
|
||||
return edge.name && edge.name !== edge.id ? edge.name : edge.id;
|
||||
}
|
||||
|
||||
function filterEdges(edges: EdgeItem[], search: string): EdgeItem[] {
|
||||
const query = search.trim().toLowerCase();
|
||||
return query ? edges.filter((edge) => `${edge.id} ${edge.name}`.toLowerCase().includes(query)) : edges;
|
||||
}
|
||||
|
||||
/** Отображает список буровых без расчетов по текущим значениям. */
|
||||
export function EdgesDashboard({ onOpenEdge, onOpenEquipment }: EdgesDashboardProps) {
|
||||
const [search, setSearch] = useState('');
|
||||
const auth = useAuth();
|
||||
const edges = useQuery({
|
||||
queryKey: ['edge'],
|
||||
queryFn: getEdges,
|
||||
refetchInterval: false,
|
||||
});
|
||||
|
||||
const filteredEdges = useMemo(() => filterEdges(edges.data?.items ?? [], search), [edges.data?.items, search]);
|
||||
|
||||
return (
|
||||
<main className="dashboard-shell">
|
||||
<header className="dashboard-header">
|
||||
<div>
|
||||
<span className="page-kicker">Drill Cloud v3</span>
|
||||
<h1>Буровые установки</h1>
|
||||
</div>
|
||||
<div className="dashboard-actions">
|
||||
<label className="search-box dashboard-search">
|
||||
<Search size={16} />
|
||||
<input value={search} onChange={(event) => setSearch(event.target.value)} placeholder="Поиск буровой" />
|
||||
</label>
|
||||
<button type="button" className="icon-button" onClick={() => edges.refetch()} title="Обновить список">
|
||||
<RefreshCw size={18} />
|
||||
</button>
|
||||
{auth.enabled ? (
|
||||
<button type="button" className="ghost-button" onClick={() => void auth.logout()}>
|
||||
<LogOut size={17} />
|
||||
Выйти
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section className="dashboard-stats" aria-label="Статистика буровых">
|
||||
<StatBlock label="Всего установок" value={edges.data?.items.length ?? 0} tone="neutral" />
|
||||
<StatBlock label="Найдено" value={filteredEdges.length} tone="accent" />
|
||||
</section>
|
||||
|
||||
{edges.isError ? (
|
||||
<div className="empty-panel">Не удалось загрузить список буровых: {String(edges.error)}</div>
|
||||
) : (
|
||||
<section className="edge-card-grid" aria-label="Буровые установки">
|
||||
{filteredEdges.map((edge) => (
|
||||
<EdgeCard
|
||||
key={edge.id}
|
||||
edge={edge}
|
||||
onOpenEdge={onOpenEdge}
|
||||
onOpenEquipment={onOpenEquipment}
|
||||
/>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
|
||||
{!edges.isPending && !filteredEdges.length && !edges.isError ? (
|
||||
<div className="empty-panel">В cloud-v3 пока нет буровых</div>
|
||||
) : null}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
function StatBlock({
|
||||
label,
|
||||
value,
|
||||
tone,
|
||||
}: {
|
||||
label: string;
|
||||
value: number;
|
||||
tone: 'neutral' | 'success' | 'danger' | 'warning' | 'accent';
|
||||
}) {
|
||||
return (
|
||||
<article className={`dashboard-stat dashboard-stat--${tone}`}>
|
||||
<span>{label}</span>
|
||||
<strong>{value}</strong>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
function EdgeCard({
|
||||
edge,
|
||||
onOpenEdge,
|
||||
onOpenEquipment,
|
||||
}: {
|
||||
edge: EdgeItem;
|
||||
onOpenEdge: (edgeId: string) => void;
|
||||
onOpenEquipment: (edgeId: string) => void;
|
||||
}) {
|
||||
const title = getEdgeTitle(edge);
|
||||
|
||||
return (
|
||||
<article className="edge-card">
|
||||
<header className="edge-card__header">
|
||||
<div className="edge-card__logo">
|
||||
<img src={edgeImage} alt="" />
|
||||
</div>
|
||||
<div className="edge-card__title">
|
||||
<h2>{title}</h2>
|
||||
<span>{edge.id}</span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="edge-card__actions" aria-label={`Разделы ${title}`}>
|
||||
<button type="button" onClick={() => onOpenEquipment(edge.id)}>
|
||||
<Wrench size={15} />
|
||||
Оборудование
|
||||
</button>
|
||||
<button type="button">
|
||||
<Gauge size={15} />
|
||||
Состояние байпасов
|
||||
</button>
|
||||
<button type="button">
|
||||
<ShieldAlert size={15} />
|
||||
Аварии приводов
|
||||
</button>
|
||||
<button type="button">
|
||||
<Clock3 size={15} />
|
||||
Техническое обслуживание
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<section className="edge-card__maintenance" aria-label="Техническое обслуживание">
|
||||
<span>Техническое обслуживание</span>
|
||||
<div>
|
||||
<button type="button">Ежедневное</button>
|
||||
<button type="button">Еженедельное</button>
|
||||
<button type="button">Ежемесячное</button>
|
||||
<button type="button">Полугодовое</button>
|
||||
<button type="button">Годовое</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<button type="button" className="edge-card__details" onClick={() => onOpenEdge(edge.id)}>
|
||||
<span>Подробнее</span>
|
||||
<ArrowRight size={18} />
|
||||
</button>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
78
src/features/electrical-schematics/ElectricalNode.tsx
Normal file
78
src/features/electrical-schematics/ElectricalNode.tsx
Normal file
@@ -0,0 +1,78 @@
|
||||
import { type CSSProperties } from 'react';
|
||||
import { Activity, AlertTriangle, PlugZap } from 'lucide-react';
|
||||
import type { DiagramNode } from '../../entities/diagram/types';
|
||||
import { formatNumber } from '../../utils/format';
|
||||
import { getNodeSize } from './geometry';
|
||||
import { getLiveValue } from './model';
|
||||
import type { LiveValue } from './types';
|
||||
|
||||
function getNodeTitle(node: DiagramNode, value?: LiveValue) {
|
||||
if (node.kind === 'tagWidget') {
|
||||
return node.label || value?.name || node.tagId;
|
||||
}
|
||||
|
||||
return String(node.data?.title || node.data?.text || node.decorationType);
|
||||
}
|
||||
|
||||
type ElectricalNodeProps = {
|
||||
liveValues: Map<string, LiveValue>;
|
||||
node: DiagramNode;
|
||||
ownerEdgeId: string;
|
||||
};
|
||||
|
||||
export function ElectricalNode({ liveValues, node, ownerEdgeId }: ElectricalNodeProps) {
|
||||
const size = getNodeSize(node);
|
||||
const bindings = node.kind === 'decoration' ? node.bindings : undefined;
|
||||
const bindingEdgeId = bindings?.sseEdgeId || bindings?.edgeId || ownerEdgeId;
|
||||
const mainValue =
|
||||
node.kind === 'tagWidget'
|
||||
? 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 title = getNodeTitle(node, mainValue);
|
||||
const style: CSSProperties = {
|
||||
left: node.position.x,
|
||||
top: node.position.y,
|
||||
width: size.width,
|
||||
height: size.height,
|
||||
zIndex: node.zIndex ?? 1,
|
||||
transform: node.kind === 'decoration' && node.rotation ? `rotate(${node.rotation}deg)` : undefined,
|
||||
};
|
||||
|
||||
return (
|
||||
<article
|
||||
className={[
|
||||
'electrical-node',
|
||||
`electrical-node--${node.kind}`,
|
||||
node.kind === 'decoration' ? `electrical-node--${node.decorationType}` : `electrical-node--${node.widgetType}`,
|
||||
stateActive ? 'electrical-node--active' : '',
|
||||
alarmActive ? 'electrical-node--alarm' : '',
|
||||
].join(' ')}
|
||||
style={style}
|
||||
title={title}
|
||||
>
|
||||
<div className="electrical-node__header">
|
||||
{alarmActive ? <AlertTriangle size={15} /> : node.kind === 'tagWidget' ? <Activity size={15} /> : <PlugZap size={15} />}
|
||||
<span>{title}</span>
|
||||
</div>
|
||||
|
||||
{mainValue ? (
|
||||
<strong className="electrical-node__value">
|
||||
{formatNumber(mainValue.value)}
|
||||
{mainValue.unitOfMeasurement ? <small>{mainValue.unitOfMeasurement}</small> : null}
|
||||
</strong>
|
||||
) : node.kind === 'decoration' ? (
|
||||
<span className="electrical-node__text">{String(node.data?.text || node.data?.title || node.decorationType)}</span>
|
||||
) : (
|
||||
<strong className="electrical-node__value">-</strong>
|
||||
)}
|
||||
|
||||
<div className="electrical-node__footer">
|
||||
{node.kind === 'tagWidget' ? <span>{node.tagId}</span> : bindings?.stateTagId ? <span>{bindings.stateTagId}</span> : <span>{node.decorationType}</span>}
|
||||
{alarmValue ? <span className="electrical-node__alarm">alarm {formatNumber(alarmValue.value)}</span> : null}
|
||||
</div>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
162
src/features/electrical-schematics/ElectricalSchematicsPage.tsx
Normal file
162
src/features/electrical-schematics/ElectricalSchematicsPage.tsx
Normal file
@@ -0,0 +1,162 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { CircuitBoard, DatabaseZap, RefreshCw } from 'lucide-react';
|
||||
import { getPublishedDiagramPage, listDiagramPages } from '../../entities/diagram/api';
|
||||
import { formatDateTime } from '../../utils/format';
|
||||
import { ElectricalNode } from './ElectricalNode';
|
||||
import { getCanvasBounds, getEdgePoints, pointsToPolyline } from './geometry';
|
||||
import { collectBindingTags, createLiveGroups, pickDefaultPage } from './model';
|
||||
import { useElectricalLiveValues } from './useElectricalLiveValues';
|
||||
|
||||
type ElectricalSchematicsPageProps = {
|
||||
edgeId: string;
|
||||
};
|
||||
|
||||
/** Отображает опубликованную электросхему и подставляет live-значения через SSE cloud-v3. */
|
||||
export function ElectricalSchematicsPage({ edgeId }: ElectricalSchematicsPageProps) {
|
||||
const [selectedPageKey, setSelectedPageKey] = useState('');
|
||||
|
||||
const pages = useQuery({
|
||||
queryKey: ['diagram-pages', edgeId],
|
||||
queryFn: () => listDiagramPages(edgeId),
|
||||
enabled: Boolean(edgeId),
|
||||
});
|
||||
|
||||
const publishedPages = useMemo(() => pages.data?.filter((page) => page.publishedRevision) ?? [], [pages.data]);
|
||||
const selectedPage = useMemo(
|
||||
() => publishedPages.find((page) => page.pageKey === selectedPageKey) ?? pickDefaultPage(publishedPages, edgeId),
|
||||
[edgeId, publishedPages, selectedPageKey],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedPage && selectedPage.pageKey !== selectedPageKey) {
|
||||
setSelectedPageKey(selectedPage.pageKey);
|
||||
}
|
||||
}, [selectedPage, selectedPageKey]);
|
||||
|
||||
const page = useQuery({
|
||||
queryKey: ['published-diagram-page', selectedPage?.pageKey],
|
||||
queryFn: () => getPublishedDiagramPage(selectedPage!.pageKey),
|
||||
enabled: Boolean(selectedPage?.pageKey),
|
||||
});
|
||||
|
||||
const diagramDocument = page.data?.document;
|
||||
const bindingTags = useMemo(() => (diagramDocument ? collectBindingTags(diagramDocument) : []), [diagramDocument]);
|
||||
const liveGroups = useMemo(() => createLiveGroups(bindingTags), [bindingTags]);
|
||||
const nodeMap = useMemo(() => new Map((diagramDocument?.nodes ?? []).map((node) => [node.id, node])), [diagramDocument?.nodes]);
|
||||
const canvasBounds = useMemo(() => getCanvasBounds(diagramDocument), [diagramDocument]);
|
||||
const { connectedSources, liveValues } = useElectricalLiveValues(liveGroups, selectedPage?.pageKey);
|
||||
const liveTagCount = liveValues.size ? Array.from(liveValues.keys()).filter((key) => key.startsWith('tag:')).length : 0;
|
||||
const connected = connectedSources.size > 0;
|
||||
|
||||
return (
|
||||
<section className="electrical-section">
|
||||
<div className="section-header">
|
||||
<div>
|
||||
<span className="page-kicker">
|
||||
<CircuitBoard size={14} />
|
||||
Электросхемы
|
||||
</span>
|
||||
<h2>{page.data?.title || diagramDocument?.title || selectedPage?.pageKey || edgeId}</h2>
|
||||
</div>
|
||||
<div className="electrical-toolbar">
|
||||
{publishedPages.length > 1 ? (
|
||||
<label>
|
||||
Схема
|
||||
<select value={selectedPageKey} onChange={(event) => setSelectedPageKey(event.target.value)}>
|
||||
{publishedPages.map((item) => (
|
||||
<option key={item.pageKey} value={item.pageKey}>
|
||||
{item.title || item.pageKey}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
) : null}
|
||||
<div className={`source-chip electrical-live-chip ${connected ? 'electrical-live-chip--sse' : ''}`}>
|
||||
<DatabaseZap size={16} />
|
||||
{connected ? `SSE · ${connectedSources.size}` : liveGroups.length ? 'подключение SSE' : 'нет привязок'}
|
||||
</div>
|
||||
<button type="button" className="icon-button" onClick={() => void page.refetch()} title="Обновить схему">
|
||||
<RefreshCw size={18} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{pages.isError ? (
|
||||
<div className="empty-panel">Не удалось загрузить список опубликованных схем: {String(pages.error)}</div>
|
||||
) : null}
|
||||
|
||||
{!pages.isPending && !publishedPages.length && !pages.isError ? (
|
||||
<div className="empty-panel">Для {edgeId} пока нет опубликованных схем</div>
|
||||
) : null}
|
||||
|
||||
{page.isError ? (
|
||||
<div className="empty-panel">Не удалось загрузить опубликованную схему: {String(page.error)}</div>
|
||||
) : null}
|
||||
|
||||
{diagramDocument ? (
|
||||
<div className="electrical-layout">
|
||||
<div className="electrical-canvas-shell">
|
||||
<div className="electrical-canvas" style={{ width: canvasBounds.width, height: canvasBounds.height }}>
|
||||
{diagramDocument.background?.url ? (
|
||||
<img
|
||||
className={`electrical-background electrical-background--${diagramDocument.background.fit ?? 'contain'}`}
|
||||
src={diagramDocument.background.url}
|
||||
alt=""
|
||||
style={{ opacity: diagramDocument.background.opacity ?? 0.22 }}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<svg className="electrical-wires" width={canvasBounds.width} height={canvasBounds.height}>
|
||||
{(diagramDocument.edges ?? []).map((edge) => {
|
||||
const points = getEdgePoints(edge, nodeMap);
|
||||
if (points.length < 2) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<polyline
|
||||
key={edge.id}
|
||||
className={`electrical-wire electrical-wire--${edge.kind} ${edge.animated ? 'electrical-wire--animated' : ''}`}
|
||||
points={pointsToPolyline(points)}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</svg>
|
||||
|
||||
{diagramDocument.nodes.map((node) => (
|
||||
<ElectricalNode
|
||||
key={node.id}
|
||||
node={node}
|
||||
ownerEdgeId={diagramDocument.ownerEdgeId}
|
||||
liveValues={liveValues}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<aside className="electrical-side-panel">
|
||||
<div>
|
||||
<span>Опубликовано</span>
|
||||
<strong>{page.data?.publishedAt ? formatDateTime(page.data.publishedAt) : '-'}</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span>Элементы</span>
|
||||
<strong>{diagramDocument.nodes.length}</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span>Провода</span>
|
||||
<strong>{diagramDocument.edges.length}</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span>Live-теги</span>
|
||||
<strong>{liveTagCount}</strong>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
) : page.isPending || pages.isPending ? (
|
||||
<div className="empty-panel">Загрузка опубликованной схемы...</div>
|
||||
) : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
42
src/features/electrical-schematics/geometry.ts
Normal file
42
src/features/electrical-schematics/geometry.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import type { DiagramDocument, DiagramEdge, DiagramNode, DiagramPoint } from '../../entities/diagram/types';
|
||||
|
||||
export function getCanvasBounds(document?: DiagramDocument) {
|
||||
const nodes = document?.nodes ?? [];
|
||||
const maxX = Math.max(...nodes.map((node) => node.position.x + getNodeSize(node).width), 960);
|
||||
const maxY = Math.max(...nodes.map((node) => node.position.y + getNodeSize(node).height), 560);
|
||||
|
||||
return {
|
||||
width: Math.ceil(maxX + 80),
|
||||
height: Math.ceil(maxY + 80),
|
||||
};
|
||||
}
|
||||
|
||||
export function getNodeSize(node: DiagramNode) {
|
||||
if (node.kind === 'decoration') {
|
||||
return node.size;
|
||||
}
|
||||
|
||||
return node.size ?? { width: 190, height: 82 };
|
||||
}
|
||||
|
||||
export function getNodeCenter(node: DiagramNode): DiagramPoint {
|
||||
const size = getNodeSize(node);
|
||||
return {
|
||||
x: node.position.x + size.width / 2,
|
||||
y: node.position.y + size.height / 2,
|
||||
};
|
||||
}
|
||||
|
||||
export function getEdgePoints(edge: DiagramEdge, nodeMap: Map<string, DiagramNode>): DiagramPoint[] {
|
||||
const source = nodeMap.get(edge.sourceNodeId);
|
||||
const target = nodeMap.get(edge.targetNodeId);
|
||||
if (!source || !target) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [getNodeCenter(source), ...(edge.waypoints ?? []), getNodeCenter(target)];
|
||||
}
|
||||
|
||||
export function pointsToPolyline(points: DiagramPoint[]) {
|
||||
return points.map((point) => `${point.x},${point.y}`).join(' ');
|
||||
}
|
||||
90
src/features/electrical-schematics/model.ts
Normal file
90
src/features/electrical-schematics/model.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
import type { DiagramDocument, DiagramPageSummary } from '../../entities/diagram/types';
|
||||
import type { BindingTag, LiveGroup, LiveValue } from './types';
|
||||
|
||||
const DEFAULT_PAGE_PREFIXES = ['ELECTRICAL', 'MAIN', 'DIRECT'];
|
||||
|
||||
export function pickDefaultPage(pages: DiagramPageSummary[], edgeId: string): DiagramPageSummary | undefined {
|
||||
const published = pages.filter((page) => page.publishedRevision);
|
||||
const byPriority = [...published].sort((a, b) => {
|
||||
const aRank = getPageRank(a.pageKey, edgeId);
|
||||
const bRank = getPageRank(b.pageKey, edgeId);
|
||||
return aRank - bRank || a.pageKey.localeCompare(b.pageKey);
|
||||
});
|
||||
|
||||
return byPriority[0];
|
||||
}
|
||||
|
||||
function getPageRank(pageKey: string, edgeId: string): number {
|
||||
const exactKeys = DEFAULT_PAGE_PREFIXES.map((prefix) => (prefix === 'DIRECT' ? edgeId : `${prefix}_${edgeId}`));
|
||||
const exactIndex = exactKeys.indexOf(pageKey);
|
||||
if (exactIndex >= 0) {
|
||||
return exactIndex;
|
||||
}
|
||||
|
||||
return pageKey.includes(edgeId) ? 10 : 20;
|
||||
}
|
||||
|
||||
export function collectBindingTags(document: DiagramDocument): BindingTag[] {
|
||||
const tags: BindingTag[] = [];
|
||||
|
||||
for (const node of document.nodes) {
|
||||
if (node.kind === 'tagWidget') {
|
||||
tags.push({
|
||||
tagId: node.tagId,
|
||||
edgeId: node.edgeId || document.ownerEdgeId,
|
||||
sourceKey: `edge:${node.edgeId || document.ownerEdgeId}`,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const bindings = node.bindings;
|
||||
if (!bindings) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const edgeId = bindings.sseEdgeId || bindings.edgeId || document.ownerEdgeId;
|
||||
const sourceKey = bindings.sseUrl || `edge:${edgeId}`;
|
||||
|
||||
[bindings.stateTagId, bindings.alarmTagId].filter(Boolean).forEach((tagId) => {
|
||||
tags.push({
|
||||
tagId: tagId as string,
|
||||
edgeId,
|
||||
sourceKey,
|
||||
sseUrl: bindings.sseUrl,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const unique = new Map<string, BindingTag>();
|
||||
tags.forEach((tag) => unique.set(`${tag.sourceKey}:${tag.edgeId}:${tag.tagId}`, tag));
|
||||
return Array.from(unique.values());
|
||||
}
|
||||
|
||||
export function createLiveGroups(tags: BindingTag[]): LiveGroup[] {
|
||||
const groups = new Map<string, LiveGroup>();
|
||||
|
||||
tags.forEach((tag) => {
|
||||
const group = groups.get(tag.sourceKey) ?? {
|
||||
sourceKey: tag.sourceKey,
|
||||
edgeId: tag.edgeId,
|
||||
sseUrl: tag.sseUrl,
|
||||
tags: [],
|
||||
};
|
||||
|
||||
if (!group.tags.includes(tag.tagId)) {
|
||||
group.tags.push(tag.tagId);
|
||||
}
|
||||
|
||||
groups.set(tag.sourceKey, group);
|
||||
});
|
||||
|
||||
return Array.from(groups.values());
|
||||
}
|
||||
|
||||
export function getLiveValue(values: Map<string, LiveValue>, edgeId: string, tagId?: string): LiveValue | undefined {
|
||||
if (!tagId) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return values.get(`${edgeId}:${tagId}`) ?? values.get(`tag:${tagId}`);
|
||||
}
|
||||
19
src/features/electrical-schematics/types.ts
Normal file
19
src/features/electrical-schematics/types.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import type { CurrentItem } from '../../entities/current/types';
|
||||
|
||||
export type LiveValue = CurrentItem & {
|
||||
sourceKey: string;
|
||||
};
|
||||
|
||||
export type BindingTag = {
|
||||
tagId: string;
|
||||
edgeId: string;
|
||||
sourceKey: string;
|
||||
sseUrl?: string;
|
||||
};
|
||||
|
||||
export type LiveGroup = {
|
||||
sourceKey: string;
|
||||
edgeId: string;
|
||||
sseUrl?: string;
|
||||
tags: string[];
|
||||
};
|
||||
@@ -0,0 +1,83 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { getCurrent, getCurrentEventsUrl } from '../../entities/current/api';
|
||||
import type { CurrentEvent, CurrentResponse } from '../../entities/current/types';
|
||||
import type { LiveGroup, LiveValue } from './types';
|
||||
|
||||
function buildCustomSseUrl(sseUrl: string, tags: string[]): string {
|
||||
const url = new URL(sseUrl, window.location.origin);
|
||||
if (tags.length && !url.searchParams.has('tags')) {
|
||||
tags.forEach((tag) => url.searchParams.append('tags', tag));
|
||||
}
|
||||
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
export function useElectricalLiveValues(liveGroups: LiveGroup[], resetKey?: string) {
|
||||
const [liveValues, setLiveValues] = useState(() => new Map<string, LiveValue>());
|
||||
const [connectedSources, setConnectedSources] = useState<Set<string>>(new Set());
|
||||
|
||||
useEffect(() => {
|
||||
setLiveValues(new Map());
|
||||
setConnectedSources(new Set());
|
||||
}, [resetKey]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!liveGroups.length) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
let closed = false;
|
||||
const eventSources: EventSource[] = [];
|
||||
|
||||
const mergeResponse = (response: CurrentResponse, sourceKey: string) => {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
|
||||
setLiveValues((previous) => {
|
||||
const next = new Map(previous);
|
||||
response.items.forEach((item) => {
|
||||
const value = { ...item, sourceKey };
|
||||
next.set(`${item.edge}:${item.tag}`, value);
|
||||
next.set(`tag:${item.tag}`, value);
|
||||
});
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
liveGroups.forEach((group) => {
|
||||
if (!group.sseUrl) {
|
||||
void getCurrent(group.edgeId, group.tags).then((response) => mergeResponse(response, group.sourceKey));
|
||||
}
|
||||
|
||||
const url = group.sseUrl ? buildCustomSseUrl(group.sseUrl, group.tags) : getCurrentEventsUrl(group.edgeId, group.tags);
|
||||
const eventSource = new EventSource(url);
|
||||
|
||||
eventSource.onopen = () => {
|
||||
setConnectedSources((previous) => new Set(previous).add(group.sourceKey));
|
||||
};
|
||||
|
||||
eventSource.onerror = () => {
|
||||
setConnectedSources((previous) => {
|
||||
const next = new Set(previous);
|
||||
next.delete(group.sourceKey);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
eventSource.onmessage = (message) => {
|
||||
const event = JSON.parse(message.data) as CurrentEvent;
|
||||
mergeResponse(event, group.sourceKey);
|
||||
};
|
||||
|
||||
eventSources.push(eventSource);
|
||||
});
|
||||
|
||||
return () => {
|
||||
closed = true;
|
||||
eventSources.forEach((eventSource) => eventSource.close());
|
||||
};
|
||||
}, [liveGroups]);
|
||||
|
||||
return { connectedSources, liveValues };
|
||||
}
|
||||
92
src/features/history-chart/HistoryChart.tsx
Normal file
92
src/features/history-chart/HistoryChart.tsx
Normal file
@@ -0,0 +1,92 @@
|
||||
import { LineChart, ScatterChart } from 'echarts/charts';
|
||||
import {
|
||||
DataZoomComponent,
|
||||
GridComponent,
|
||||
LegendComponent,
|
||||
TooltipComponent,
|
||||
} from 'echarts/components';
|
||||
import * as echarts from 'echarts/core';
|
||||
import { CanvasRenderer } from 'echarts/renderers';
|
||||
import ReactEChartsCore from 'echarts-for-react/esm/core.js';
|
||||
import { useMemo, useRef } from 'react';
|
||||
import type { HistoryResponse } from '../../entities/history/types';
|
||||
import type { HistoryAxisLabelFormat } from '../../utils/historyGranularity';
|
||||
import type { DataZoomEventBatch, DataZoomState } from './chartTypes';
|
||||
import { createHistoryChartOptions } from './historyChartOptions';
|
||||
|
||||
echarts.use([
|
||||
LineChart,
|
||||
ScatterChart,
|
||||
GridComponent,
|
||||
LegendComponent,
|
||||
TooltipComponent,
|
||||
DataZoomComponent,
|
||||
CanvasRenderer,
|
||||
]);
|
||||
|
||||
type HistoryChartProps = {
|
||||
data?: HistoryResponse;
|
||||
loading: boolean;
|
||||
from?: string;
|
||||
to?: string;
|
||||
tickIntervalMs?: number;
|
||||
labelFormat?: HistoryAxisLabelFormat;
|
||||
tagLabels?: Record<string, string>;
|
||||
};
|
||||
|
||||
/** Рисует avg-линию, min/max-точки и вертикальный диапазон для агрегированной истории. */
|
||||
export function HistoryChart({
|
||||
data,
|
||||
loading,
|
||||
from,
|
||||
to,
|
||||
tickIntervalMs,
|
||||
labelFormat,
|
||||
tagLabels = {},
|
||||
}: HistoryChartProps) {
|
||||
const dataZoomRef = useRef<DataZoomState | null>(null);
|
||||
const legendData = useMemo(
|
||||
() => data?.series.map((series) => tagLabels[series.tag] ?? series.tag) ?? [],
|
||||
[data?.series, tagLabels],
|
||||
);
|
||||
|
||||
const option = useMemo(
|
||||
() =>
|
||||
createHistoryChartOptions({
|
||||
data,
|
||||
dataZoomState: dataZoomRef.current ?? {},
|
||||
from,
|
||||
to,
|
||||
labelFormat,
|
||||
legendData,
|
||||
tagLabels,
|
||||
tickIntervalMs,
|
||||
}),
|
||||
[data, from, labelFormat, legendData, tagLabels, tickIntervalMs, to],
|
||||
);
|
||||
|
||||
const onChartEvents = useMemo(
|
||||
() => ({
|
||||
datazoom: (event: DataZoomEventBatch) => {
|
||||
const state = event.batch?.[0] ?? event;
|
||||
dataZoomRef.current = {
|
||||
start: state.start,
|
||||
end: state.end,
|
||||
startValue: state.startValue,
|
||||
endValue: state.endValue,
|
||||
};
|
||||
},
|
||||
}),
|
||||
[],
|
||||
);
|
||||
|
||||
if (loading) {
|
||||
return <div className="chart-placeholder">Загрузка графика...</div>;
|
||||
}
|
||||
|
||||
if (!data?.series.length) {
|
||||
return <div className="chart-placeholder">Нет данных для выбранного диапазона</div>;
|
||||
}
|
||||
|
||||
return <ReactEChartsCore echarts={echarts} option={option} className="history-chart" onEvents={onChartEvents} lazyUpdate />;
|
||||
}
|
||||
18
src/features/history-chart/chartTypes.ts
Normal file
18
src/features/history-chart/chartTypes.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
export type AvgPointValue = [time: number, avg: number, min: number, max: number, count: number];
|
||||
|
||||
export type TooltipParam = {
|
||||
marker?: string;
|
||||
seriesName?: string;
|
||||
value?: unknown;
|
||||
};
|
||||
|
||||
export type DataZoomState = {
|
||||
start?: number;
|
||||
end?: number;
|
||||
startValue?: number;
|
||||
endValue?: number;
|
||||
};
|
||||
|
||||
export type DataZoomEventBatch = DataZoomState & {
|
||||
batch?: DataZoomState[];
|
||||
};
|
||||
102
src/features/history-chart/historyChartFormat.ts
Normal file
102
src/features/history-chart/historyChartFormat.ts
Normal file
@@ -0,0 +1,102 @@
|
||||
import type { HistoryAxisLabelFormat } from '../../utils/historyGranularity';
|
||||
import type { AvgPointValue, TooltipParam } from './chartTypes';
|
||||
|
||||
export function formatAxisDate(value: number, labelFormat: HistoryAxisLabelFormat = 'time-minutes'): string {
|
||||
const date = new Date(value);
|
||||
|
||||
if (labelFormat === 'time-seconds') {
|
||||
return new Intl.DateTimeFormat('ru-RU', {
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
}).format(date);
|
||||
}
|
||||
|
||||
if (labelFormat === 'time-minutes') {
|
||||
return new Intl.DateTimeFormat('ru-RU', { hour: '2-digit', minute: '2-digit' }).format(date);
|
||||
}
|
||||
|
||||
if (labelFormat === 'hour-zero') {
|
||||
return `${new Intl.DateTimeFormat('ru-RU', { hour: '2-digit' }).format(date)}:00`;
|
||||
}
|
||||
|
||||
if (labelFormat === 'day-hour') {
|
||||
const day = new Intl.DateTimeFormat('ru-RU', { day: '2-digit' }).format(date);
|
||||
const hour = new Intl.DateTimeFormat('ru-RU', { hour: '2-digit' }).format(date);
|
||||
return `${day} ${hour}:00`;
|
||||
}
|
||||
|
||||
if (labelFormat === 'weekday-day') {
|
||||
return new Intl.DateTimeFormat('ru-RU', { weekday: 'short', day: '2-digit' }).format(date);
|
||||
}
|
||||
|
||||
if (labelFormat === 'day-month') {
|
||||
return new Intl.DateTimeFormat('ru-RU', { day: '2-digit', month: '2-digit' }).format(date);
|
||||
}
|
||||
|
||||
if (labelFormat === 'day-month-name') {
|
||||
return new Intl.DateTimeFormat('ru-RU', { day: '2-digit', month: 'short' }).format(date);
|
||||
}
|
||||
|
||||
if (labelFormat === 'month-name') {
|
||||
return new Intl.DateTimeFormat('ru-RU', { month: 'short' }).format(date);
|
||||
}
|
||||
|
||||
if (labelFormat === 'month-year') {
|
||||
return new Intl.DateTimeFormat('ru-RU', { month: 'short', year: '2-digit' }).format(date);
|
||||
}
|
||||
|
||||
if (labelFormat === 'quarter-year') {
|
||||
const quarter = Math.floor(date.getMonth() / 3) + 1;
|
||||
return `Кв${quarter} ${String(date.getFullYear()).slice(-2)}`;
|
||||
}
|
||||
|
||||
return new Intl.DateTimeFormat('ru-RU', { year: 'numeric' }).format(date);
|
||||
}
|
||||
|
||||
function formatChartValue(value: number): string {
|
||||
return new Intl.NumberFormat('ru-RU', {
|
||||
maximumFractionDigits: Math.abs(value) >= 100 ? 2 : 3,
|
||||
}).format(value);
|
||||
}
|
||||
|
||||
function isAvgPointValue(value: unknown): value is AvgPointValue {
|
||||
return Array.isArray(value) && value.length >= 5 && value.every((item) => typeof item === 'number');
|
||||
}
|
||||
|
||||
/** Собирает tooltip с min/avg/max для основной avg-серии. */
|
||||
export function formatTooltip(params: unknown): string {
|
||||
const items = (Array.isArray(params) ? params : [params]).filter(
|
||||
(item): item is TooltipParam => typeof item === 'object' && item !== null,
|
||||
);
|
||||
const avgItems = items.filter((item) => isAvgPointValue(item.value));
|
||||
const firstValue = avgItems[0]?.value as AvgPointValue | undefined;
|
||||
|
||||
if (!firstValue) {
|
||||
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 rows = avgItems.map((item) => {
|
||||
const value = item.value as AvgPointValue;
|
||||
return [
|
||||
'<div class="chart-tooltip-row">',
|
||||
`<span>${item.marker ?? ''}${item.seriesName ?? ''}</span>`,
|
||||
'<strong>',
|
||||
`min ${formatChartValue(value[2])} · avg ${formatChartValue(value[1])} · max ${formatChartValue(value[3])}`,
|
||||
value[4] > 1 ? ` · ${value[4]} точек` : '',
|
||||
'</strong>',
|
||||
'</div>',
|
||||
].join('');
|
||||
});
|
||||
|
||||
return [`<div class="chart-tooltip"><div class="chart-tooltip-title">${header}</div>`, ...rows, '</div>'].join('');
|
||||
}
|
||||
110
src/features/history-chart/historyChartOptions.ts
Normal file
110
src/features/history-chart/historyChartOptions.ts
Normal file
@@ -0,0 +1,110 @@
|
||||
import type { EChartsOption } from 'echarts';
|
||||
import type { HistoryResponse } from '../../entities/history/types';
|
||||
import type { HistoryAxisLabelFormat } from '../../utils/historyGranularity';
|
||||
import type { DataZoomState } from './chartTypes';
|
||||
import { formatAxisDate, formatTooltip } from './historyChartFormat';
|
||||
import { createSeriesOptions, SERIES_COLORS } from './historyChartSeries';
|
||||
|
||||
export type HistoryChartOptionsInput = {
|
||||
data?: HistoryResponse;
|
||||
dataZoomState: DataZoomState;
|
||||
from?: string;
|
||||
to?: string;
|
||||
labelFormat?: HistoryAxisLabelFormat;
|
||||
legendData: string[];
|
||||
tagLabels: Record<string, string>;
|
||||
tickIntervalMs?: number;
|
||||
};
|
||||
|
||||
export function createHistoryChartOptions({
|
||||
data,
|
||||
dataZoomState,
|
||||
from,
|
||||
to,
|
||||
labelFormat,
|
||||
legendData,
|
||||
tagLabels,
|
||||
tickIntervalMs,
|
||||
}: HistoryChartOptionsInput): EChartsOption {
|
||||
const xMin = from ? new Date(from).getTime() : undefined;
|
||||
const xMax = to ? new Date(to).getTime() : undefined;
|
||||
|
||||
return {
|
||||
color: SERIES_COLORS,
|
||||
animation: false,
|
||||
backgroundColor: 'transparent',
|
||||
textStyle: {
|
||||
color: '#cbd5e1',
|
||||
fontFamily: 'Inter, Segoe UI, sans-serif',
|
||||
},
|
||||
tooltip: {
|
||||
trigger: 'axis',
|
||||
backgroundColor: 'rgba(10, 13, 18, 0.96)',
|
||||
borderColor: 'rgba(212, 165, 116, 0.32)',
|
||||
textStyle: { color: '#f8fafc' },
|
||||
formatter: formatTooltip,
|
||||
},
|
||||
legend: {
|
||||
type: 'scroll',
|
||||
top: 0,
|
||||
data: legendData,
|
||||
textStyle: { color: '#cbd5e1' },
|
||||
},
|
||||
grid: {
|
||||
top: 54,
|
||||
left: 48,
|
||||
right: 24,
|
||||
bottom: 72,
|
||||
},
|
||||
xAxis: {
|
||||
type: 'time',
|
||||
min: Number.isFinite(xMin) ? xMin : undefined,
|
||||
max: Number.isFinite(xMax) ? xMax : undefined,
|
||||
minInterval: tickIntervalMs,
|
||||
maxInterval: tickIntervalMs,
|
||||
axisLine: { lineStyle: { color: 'rgba(148, 163, 184, 0.35)' } },
|
||||
axisLabel: {
|
||||
color: '#94a3b8',
|
||||
formatter: (value: number) => formatAxisDate(value, labelFormat),
|
||||
},
|
||||
splitLine: { show: false },
|
||||
},
|
||||
yAxis: {
|
||||
type: 'value',
|
||||
scale: true,
|
||||
axisLine: { lineStyle: { color: 'rgba(148, 163, 184, 0.35)' } },
|
||||
axisLabel: { color: '#94a3b8' },
|
||||
splitLine: { lineStyle: { color: 'rgba(148, 163, 184, 0.1)' } },
|
||||
},
|
||||
dataZoom: [
|
||||
{
|
||||
type: 'inside',
|
||||
throttle: 80,
|
||||
start: dataZoomState.start,
|
||||
end: dataZoomState.end,
|
||||
startValue: dataZoomState.startValue,
|
||||
endValue: dataZoomState.endValue,
|
||||
},
|
||||
{
|
||||
type: 'slider',
|
||||
bottom: 18,
|
||||
height: 28,
|
||||
borderColor: 'rgba(148, 163, 184, 0.24)',
|
||||
fillerColor: 'rgba(91, 143, 249, 0.18)',
|
||||
handleStyle: {
|
||||
color: '#d4a574',
|
||||
borderColor: '#e8c9a0',
|
||||
},
|
||||
textStyle: { color: '#94a3b8' },
|
||||
start: dataZoomState.start,
|
||||
end: dataZoomState.end,
|
||||
startValue: dataZoomState.startValue,
|
||||
endValue: dataZoomState.endValue,
|
||||
},
|
||||
],
|
||||
series:
|
||||
data?.series.flatMap((series, index) =>
|
||||
createSeriesOptions(series, index, tagLabels[series.tag] ?? series.tag),
|
||||
) ?? [],
|
||||
};
|
||||
}
|
||||
101
src/features/history-chart/historyChartSeries.ts
Normal file
101
src/features/history-chart/historyChartSeries.ts
Normal file
@@ -0,0 +1,101 @@
|
||||
import type { SeriesOption } from 'echarts';
|
||||
import type { HistorySeries } from '../../entities/history/types';
|
||||
import type { AvgPointValue } from './chartTypes';
|
||||
|
||||
export const SERIES_COLORS = [
|
||||
'#5B8FF9',
|
||||
'#5AD8A6',
|
||||
'#F6BD16',
|
||||
'#E8684A',
|
||||
'#6DC8EC',
|
||||
'#FF9D4D',
|
||||
'#73D13D',
|
||||
'#A7B3FF',
|
||||
];
|
||||
|
||||
/** Создает avg-линию, вертикальные min/max-отрезки и точки экстремумов для одной серии. */
|
||||
export function createSeriesOptions(series: HistorySeries, index: number, label: string): SeriesOption[] {
|
||||
const color = SERIES_COLORS[index % SERIES_COLORS.length];
|
||||
const avgData: AvgPointValue[] = series.points.map((point) => [
|
||||
point.t,
|
||||
point.avg,
|
||||
point.min,
|
||||
point.max,
|
||||
point.count,
|
||||
]);
|
||||
const spreadData = series.points.flatMap((point) => [
|
||||
[point.t, point.min],
|
||||
[point.t, point.max],
|
||||
[point.t, null],
|
||||
]);
|
||||
|
||||
return [
|
||||
{
|
||||
name: `${label} min/max`,
|
||||
type: 'line',
|
||||
data: spreadData,
|
||||
showSymbol: false,
|
||||
connectNulls: false,
|
||||
silent: true,
|
||||
tooltip: { show: false },
|
||||
legendHoverLink: false,
|
||||
lineStyle: {
|
||||
width: 1,
|
||||
opacity: 0.42,
|
||||
color,
|
||||
},
|
||||
emphasis: {
|
||||
disabled: true,
|
||||
},
|
||||
z: 1,
|
||||
},
|
||||
{
|
||||
name: `${label} min`,
|
||||
type: 'scatter',
|
||||
data: series.points.map((point) => [point.t, point.min]),
|
||||
symbolSize: 4,
|
||||
silent: true,
|
||||
tooltip: { show: false },
|
||||
itemStyle: {
|
||||
color,
|
||||
opacity: 0.72,
|
||||
},
|
||||
emphasis: {
|
||||
disabled: true,
|
||||
},
|
||||
z: 2,
|
||||
},
|
||||
{
|
||||
name: `${label} max`,
|
||||
type: 'scatter',
|
||||
data: series.points.map((point) => [point.t, point.max]),
|
||||
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: {
|
||||
focus: 'series',
|
||||
},
|
||||
z: 3,
|
||||
},
|
||||
];
|
||||
}
|
||||
23
src/features/history/dateRange.ts
Normal file
23
src/features/history/dateRange.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
import { toInputDateTimeValue } from '../../utils/format';
|
||||
|
||||
export type DateRangeState = {
|
||||
from: string;
|
||||
to: string;
|
||||
};
|
||||
|
||||
export const RANGE_PRESETS = [
|
||||
{ id: '1h', label: '1 час', hours: 1 },
|
||||
{ id: '6h', label: '6 часов', hours: 6 },
|
||||
{ id: '24h', label: '24 часа', hours: 24 },
|
||||
{ id: '7d', label: '7 дней', hours: 24 * 7 },
|
||||
{ id: '30d', label: '30 дней', hours: 24 * 30 },
|
||||
] as const;
|
||||
|
||||
export function createRange(hours: number): DateRangeState {
|
||||
const to = new Date();
|
||||
const from = new Date(to.getTime() - hours * 60 * 60 * 1000);
|
||||
return {
|
||||
from: toInputDateTimeValue(from),
|
||||
to: toInputDateTimeValue(to),
|
||||
};
|
||||
}
|
||||
28
src/features/history/useHistoryQuery.ts
Normal file
28
src/features/history/useHistoryQuery.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { useMemo } from 'react';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { getHistory } from '../../entities/history/api';
|
||||
import { toIsoFromInput } from '../../utils/format';
|
||||
import { getHistoryGranularity } from '../../utils/historyGranularity';
|
||||
import type { DateRangeState } from './dateRange';
|
||||
|
||||
export function useHistoryQuery(edgeId: string, selectedTag: string | undefined, range: DateRangeState) {
|
||||
const from = toIsoFromInput(range.from) as string;
|
||||
const to = toIsoFromInput(range.to) as string;
|
||||
const granularity = useMemo(() => getHistoryGranularity(from, to), [from, to]);
|
||||
|
||||
const query = useQuery({
|
||||
queryKey: ['history', edgeId, selectedTag, from, to, granularity.granulate],
|
||||
queryFn: () =>
|
||||
getHistory({
|
||||
edge: edgeId,
|
||||
tag: selectedTag as string,
|
||||
from,
|
||||
to,
|
||||
granulate: granularity.granulate,
|
||||
}),
|
||||
enabled: Boolean(edgeId && selectedTag),
|
||||
refetchInterval: false,
|
||||
});
|
||||
|
||||
return { query, from, to, granularity };
|
||||
}
|
||||
Reference in New Issue
Block a user