23 Commits

Author SHA1 Message Date
Первов Артем
d2f8671162 удаление docker-compose.dev.yml. Удаление container_name из docker-compose. Удаление branch env переменной. 2026-07-04 19:59:04 +03:00
Первов Артем
36276297a6 Merge branch 'main' into dev 2026-07-04 18:02:38 +03:00
Первов Артем
19b1eb3d8a docker-compose.dev.yml добавил. Временное решение. 2026-07-04 14:26:18 +03:00
Первов Артем
b58b5102b2 Удалил docker-compose.dev.yml. поменял наименование контейнера. 2026-07-04 14:06:32 +03:00
Первов Артем
221552104f добавлен docker-compose.dev.yml для окружения разработки 2026-07-04 13:35:42 +03:00
0f38229ad0 Merge pull request 'no-cache' (#5) from dev into main
Reviewed-on: #5
2026-07-04 08:26:20 +00:00
faccdf734a no-cache 2026-07-04 13:25:43 +05:00
8522d35d90 Merge pull request 'CORS problem solution' (#4) from cors into dev
Reviewed-on: #4
2026-07-03 07:58:08 +00:00
96ca70d9f9 CORS problem solution 2026-07-03 12:51:34 +05:00
Первов Артем
c44534bf66 Merge branch 'dev' of https://git.greact.ru/APervov/ui into dev 2026-07-02 20:55:21 +03:00
Первов Артем
594a3c2a2a Добавлена env переменная branch=dev для дев окружения 2026-07-02 20:55:05 +03:00
34ab5d4a6f Merge pull request 'main' (#3) from main into dev
Reviewed-on: #3
2026-07-02 11:02:10 +00:00
f60451ecb1 MetricWidget bigger 2026-07-02 15:58:39 +05:00
Первов Артем
3e3d2cdec3 исправлена опечатка в docker-compose 2026-06-23 14:19:52 +03:00
Первов Артем
33b9b3f4bd Добавлен networks в docker-compose 2026-06-23 14:18:10 +03:00
95690f76ec Merge pull request 'Обновление echarts графика.' (#2) from dev into main
Reviewed-on: #2
2026-06-23 10:36:56 +00:00
Первов Артем
9fc66624dc Добавил возможность выбора множества тегов для отображения. 2026-06-22 21:49:52 +03:00
Первов Артем
6ab9cd1c75 Обновил контракт по получению данных для графика. 2026-06-22 03:19:56 +03:00
8e7fc624be Merge pull request 'decompose structure' (#1) from dev into main
Reviewed-on: #1
2026-06-21 17:48:56 +00:00
Первов Артем
fe7d051d4a Улучшены datetimepicker элементы 2026-06-21 04:10:38 +03:00
Первов Артем
638eaea5fa Скорректировал getMetricStatus - метод, который влиял на отображаемый статус показателя. 2026-06-21 03:40:33 +03:00
Первов Артем
61ab9eb37a Убрал rollupOptions из vite.config. Убрал equipments. Скорректировал route. Декомпозировал EdgeDetailPage. 2026-06-21 03:08:35 +03:00
Первов Артем
31add10e56 decompose structure 2026-06-20 00:51:18 +03:00
86 changed files with 4444 additions and 4035 deletions

4
.dockerignore Normal file
View File

@@ -0,0 +1,4 @@
node_modules
dist
.env
.env.*

View File

@@ -1,3 +1,6 @@
VITE_CLOUD_API_URL=http://localhost:3101
DEV_API_URL=http://localhost:3101
VITE_DIAGRAM_API_URL=http://localhost:3002
VITE_DEFAULT_EDGE=edge5
VITE_TOIR_LIGHT_ORIGIN=https://toir-light.greact.ru
VITE_KEYCLOAK_URL=https://sso.greact.ru
VITE_KEYCLOAK_REALM=toir
VITE_KEYCLOAK_CLIENT_ID=localhost

View File

@@ -1,10 +0,0 @@
VITE_CLOUD_API_URL=http://localhost:3101
VITE_DIAGRAM_API_URL=http://localhost:3002
# Если эти переменные не заданы, greact.drill.ui работает без SSO для локальной разработки.
VITE_KEYCLOAK_URL=https://sso.greact.ru
VITE_KEYCLOAK_REALM=toir
VITE_KEYCLOAK_CLIENT_ID=drill-ui-frontend
# Origin встроенного ТОиР light. По умолчанию используется https://toir-light.greact.ru.
VITE_TOIR_LIGHT_ORIGIN=https://toir-light.greact.ru

View File

@@ -7,10 +7,16 @@ FROM node:22-alpine AS build
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
ARG VITE_CLOUD_API_URL=http://localhost:3101
ARG VITE_DEFAULT_EDGE=edge5
ENV VITE_CLOUD_API_URL=$VITE_CLOUD_API_URL
ENV VITE_DEFAULT_EDGE=$VITE_DEFAULT_EDGE
ARG VITE_DIAGRAM_API_URL
ARG VITE_TOIR_LIGHT_ORIGIN
ARG VITE_KEYCLOAK_URL
ARG VITE_KEYCLOAK_REALM
ARG VITE_KEYCLOAK_CLIENT_ID
ENV VITE_DIAGRAM_API_URL=$VITE_DIAGRAM_API_URL
ENV VITE_TOIR_LIGHT_ORIGIN=$VITE_TOIR_LIGHT_ORIGIN
ENV VITE_KEYCLOAK_URL=$VITE_KEYCLOAK_URL
ENV VITE_KEYCLOAK_REALM=$VITE_KEYCLOAK_REALM
ENV VITE_KEYCLOAK_CLIENT_ID=$VITE_KEYCLOAK_CLIENT_ID
RUN npm run build
FROM nginx:1.27-alpine

View File

@@ -3,11 +3,16 @@ services:
build:
context: .
args:
VITE_CLOUD_API_URL: ${VITE_CLOUD_API_URL:-http://localhost:3101}
VITE_DEFAULT_EDGE: ${VITE_DEFAULT_EDGE:-edge5}
VITE_DIAGRAM_API_URL: ${VITE_DIAGRAM_API_URL}
VITE_TOIR_LIGHT_ORIGIN: ${VITE_TOIR_LIGHT_ORIGIN}
VITE_KEYCLOAK_URL: ${VITE_KEYCLOAK_URL}
VITE_KEYCLOAK_REALM: ${VITE_KEYCLOAK_REALM}
VITE_KEYCLOAK_CLIENT_ID: ${VITE_KEYCLOAK_CLIENT_ID}
expose:
- "80"
networks:
- proxy
networks:
external:
true
proxy:
external: true

View File

@@ -7,5 +7,10 @@ server {
location / {
try_files $uri $uri/ /index.html;
# отключаем кеширование вообще пока активная разработка
add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0";
add_header Pragma "no-cache";
add_header Expires "0";
}
}
}

View File

@@ -1,34 +1 @@
import { BrowserRouter, Navigate, Route, Routes, useNavigate } from 'react-router-dom';
import { EdgeDetailPage } from './pages/EdgeDetailPage';
import { EdgesDashboard } from './pages/EdgesDashboard';
/** Связывает dashboard со SPA-навигацией без передачи navigate в саму страницу. */
function DashboardRoute() {
const navigate = useNavigate();
return (
<EdgesDashboard
onOpenEdge={(edgeId) => navigate(`/edges/${encodeURIComponent(edgeId)}`)}
onOpenEquipment={(edgeId) => navigate(`/edges/${encodeURIComponent(edgeId)}/equipment`)}
/>
);
}
/** Описывает публичную карту маршрутов приложения вокруг edge-объектов. */
export default function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Navigate to="/edges" replace />} />
<Route path="/edges" element={<DashboardRoute />} />
<Route path="/edges/:edgeId" element={<EdgeDetailPage view="overview" />} />
<Route path="/edges/:edgeId/archive" element={<EdgeDetailPage view="archive" />} />
<Route path="/edges/:edgeId/indicators" element={<EdgeDetailPage view="indicators" />} />
<Route path="/edges/:edgeId/equipment" element={<EdgeDetailPage view="equipment" />} />
{/* Электросхемы временно скрыты до готовности опубликованных схем и diagram-service. */}
{/* <Route path="/edges/:edgeId/electrical" element={<EdgeDetailPage view="electrical" />} /> */}
<Route path="*" element={<Navigate to="/edges" replace />} />
</Routes>
</BrowserRouter>
);
}
export { default } from './app/App';

View File

@@ -1,159 +1,10 @@
const API_URL = import.meta.env.VITE_CLOUD_API_URL ?? 'http://localhost:3101';
export type HealthResponse = {
status: 'ok';
database: {
now: string;
timescaledb_installed: boolean;
timescaledb_version: string | null;
};
};
export type CurrentItem = {
edge: string;
tag: string;
value: number;
createdAt: string;
updatedAt: string;
time: string;
name: string | null;
tagGroup: string | null;
min: number | null;
max: number | null;
comment: string | null;
unitOfMeasurement: string | null;
precision: number | null;
};
export type CurrentResponse = {
edge: string;
items: CurrentItem[];
};
export type CurrentEvent = CurrentResponse;
export type EdgeItem = {
id: string;
name: string;
parentId: string | null;
tagIds: string[];
tagCount: number;
currentTagCount: number;
liveTagCount: number;
lastDataAt: string | null;
};
export type EdgeResponse = {
items: EdgeItem[];
};
export type TagItem = {
id: string;
name: string;
tagGroup: string | null;
min: number;
max: number;
comment: string;
unitOfMeasurement: string;
edgeIds: string[];
precision: number | null;
};
export type TagResponse = {
items: TagItem[];
};
export type HistoryPoint = {
t: number;
v: number;
min: number;
avg: number;
max: number;
count: number;
};
export type HistorySeries = {
edge: string;
tag: string;
points: HistoryPoint[];
};
export type HistoryResponse = {
edge: string;
source: 'empty' | 'latest' | 'raw' | '1m' | '5m' | '1h' | '1d';
targetPoints: number;
series: HistorySeries[];
from?: string;
to?: string;
resolutionSeconds?: number | null;
};
/** Выполняет типизированный GET-запрос к cloud-v3 и централизованно обрабатывает HTTP-ошибки. */
async function request<T>(path: string, params?: Record<string, string | number | undefined>): Promise<T> {
const url = new URL(path, API_URL);
Object.entries(params ?? {}).forEach(([key, value]) => {
if (value !== undefined && value !== '') {
url.searchParams.set(key, String(value));
}
});
const response = await fetch(url);
if (!response.ok) {
const message = await response.text();
throw new Error(message || `${response.status} ${response.statusText}`);
}
return response.json() as Promise<T>;
}
/** Запрашивает состояние cloud-v3 и подключенной базы данных. */
export function getHealth(): Promise<HealthResponse> {
return request<HealthResponse>('/health');
}
/** Возвращает список edge-установок, доступных в cloud-v3. */
export function getEdges(): Promise<EdgeResponse> {
return request<EdgeResponse>('/edge');
}
/** Загружает справочник тегов, используя tag.name как отображаемое имя. */
export function getTags(params: { edge?: string; search?: string } = {}): Promise<TagResponse> {
return request<TagResponse>('/tag', params);
}
/** Загружает текущие значения показателей для выбранного edge вместе с метаданными тегов. */
export function getCurrent(edge: string, tags?: string[]): Promise<CurrentResponse> {
return request<CurrentResponse>('/current', {
edge,
tags: tags?.join(','),
});
}
/** Формирует URL SSE-потока текущих значений для выбранного edge. */
export function getCurrentEventsUrl(edge: string, tags?: string[]): string {
const url = new URL('/current/events', API_URL);
url.searchParams.set('edge', edge);
if (tags?.length) {
url.searchParams.set('tags', tags.join(','));
}
return url.toString();
}
/** Запрашивает исторические ряды с avg-линией и min/max-диапазоном для графика. */
export function getHistory(params: {
edge: string;
tags?: string[];
from?: string;
to?: string;
targetPoints?: number;
}): Promise<HistoryResponse> {
return request<HistoryResponse>('/history', {
edge: params.edge,
tags: params.tags?.join(','),
from: params.from,
to: params.to,
targetPoints: params.targetPoints,
});
}
export { getCurrent, getCurrentEventsUrl } from '../entities/current/api';
export type { CurrentEvent, CurrentItem, CurrentResponse } from '../entities/current/types';
export { getEdges } from '../entities/edge/api';
export type { EdgeItem, EdgeResponse } from '../entities/edge/types';
export { getHealth } from '../entities/health/api';
export type { HealthResponse } from '../entities/health/types';
export { getHistory } from '../entities/history/api';
export type { HistoryPoint, HistoryRequest, HistoryResponse } from '../entities/history/types';
export { getTags } from '../entities/tag/api';
export type { TagItem, TagResponse } from '../entities/tag/types';

View File

@@ -1,124 +1,11 @@
import { getAccessToken } from '../auth/keycloak';
const DIAGRAM_API_URL = import.meta.env.VITE_DIAGRAM_API_URL ?? 'http://localhost:3002';
export type DiagramPoint = {
x: number;
y: number;
};
export type DiagramSize = {
width: number;
height: number;
};
export type DiagramBindingConfig = {
stateTagId?: string;
alarmTagId?: string;
edgeId?: string;
sseEdgeId?: string;
sseUrl?: string;
};
export type DiagramNode =
| {
id: string;
kind: 'tagWidget';
tagId: string;
edgeId: string;
widgetType: string;
position: DiagramPoint;
size?: DiagramSize;
zIndex?: number;
label?: string;
displayType?: 'widget' | 'compact' | 'card';
style?: Record<string, unknown>;
}
| {
id: string;
kind: 'decoration';
decorationType: string;
position: DiagramPoint;
size: DiagramSize;
rotation?: number;
zIndex?: number;
data?: Record<string, unknown>;
style?: Record<string, unknown>;
bindings?: DiagramBindingConfig;
};
export type DiagramEdge = {
id: string;
sourceNodeId: string;
targetNodeId: string;
sourceSide?: 'left' | 'right' | 'top' | 'bottom';
targetSide?: 'left' | 'right' | 'top' | 'bottom';
kind: 'wire' | 'power' | 'signal' | 'alert';
label?: string;
animated?: boolean;
waypoints?: DiagramPoint[];
};
export type DiagramDocument = {
schemaVersion: number;
pageKey: string;
ownerEdgeId: string;
title?: string;
viewport?: { x: number; y: number; zoom: number } | null;
background?: {
url?: string;
opacity?: number;
fit?: 'contain' | 'cover' | 'stretch';
};
nodes: DiagramNode[];
edges: DiagramEdge[];
};
export type DiagramPageSummary = {
pageKey: string;
ownerEdgeId: string;
title?: string | null;
schemaVersion: number;
revision: number;
status: 'draft' | 'published' | 'archived';
publishedRevision?: number;
publishedAt?: string;
createdAt: string;
updatedAt: string;
};
export type DiagramPageResponse = DiagramPageSummary & {
document: DiagramDocument;
};
/** Выполняет запрос к diagram-service и пробрасывает Bearer-токен, если UI работает с SSO. */
async function request<T>(path: string, params?: Record<string, string | undefined>): Promise<T> {
const url = new URL(path, DIAGRAM_API_URL);
Object.entries(params ?? {}).forEach(([key, value]) => {
if (value) {
url.searchParams.set(key, value);
}
});
const token = await getAccessToken();
const response = await fetch(url, {
headers: token ? { Authorization: `Bearer ${token}` } : undefined,
});
if (!response.ok) {
const message = await response.text();
throw new Error(message || `${response.status} ${response.statusText}`);
}
return response.json() as Promise<T>;
}
/** Возвращает список страниц схем, опубликованность определяется по publishedRevision. */
export function listDiagramPages(ownerEdgeId?: string): Promise<DiagramPageSummary[]> {
return request<DiagramPageSummary[]>('/diagram/pages', { ownerEdgeId });
}
/** Загружает опубликованную версию страницы схемы. */
export function getPublishedDiagramPage(pageKey: string): Promise<DiagramPageResponse> {
return request<DiagramPageResponse>(`/diagram/pages/${encodeURIComponent(pageKey)}/published`);
}
export { getPublishedDiagramPage, listDiagramPages } from '../entities/diagram/api';
export type {
DiagramBindingConfig,
DiagramDocument,
DiagramEdge,
DiagramNode,
DiagramPageResponse,
DiagramPageSummary,
DiagramPoint,
DiagramSize,
} from '../entities/diagram/types';

5
src/app/App.tsx Normal file
View File

@@ -0,0 +1,5 @@
import { AppRouter } from './router';
export default function App() {
return <AppRouter />;
}

21
src/app/providers.tsx Normal file
View File

@@ -0,0 +1,21 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type { PropsWithChildren } from 'react';
import { AuthProvider } from '../auth/AuthProvider';
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 1_000,
retry: 1,
refetchOnWindowFocus: false,
},
},
});
export function AppProviders({ children }: PropsWithChildren) {
return (
<QueryClientProvider client={queryClient}>
<AuthProvider>{children}</AuthProvider>
</QueryClientProvider>
);
}

26
src/app/router.tsx Normal file
View File

@@ -0,0 +1,26 @@
import { BrowserRouter, Navigate, Route, Routes, useNavigate } from 'react-router-dom';
import { EdgeCurrentPage } from '../features/edge-detail/EdgeCurrentPage';
import { EdgeDetailPage } from '../features/edge-detail/EdgeDetailPage';
import { EdgeHistoryPage } from '../features/edge-detail/EdgeHistoryPage';
import { EdgesDashboard } from '../features/edges-dashboard/EdgesDashboard';
function DashboardRoute() {
const navigate = useNavigate();
return <EdgesDashboard onOpenEdge={(edgeId) => navigate(`/edges/${encodeURIComponent(edgeId)}`)} />;
}
export function AppRouter() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Navigate to="/edges" replace />} />
<Route path="/edges" element={<DashboardRoute />} />
<Route path="/edges/:edgeId" element={<EdgeDetailPage />} />
<Route path="/edges/:edgeId/archive" element={<EdgeHistoryPage />} />
<Route path="/edges/:edgeId/indicators" element={<EdgeCurrentPage />} />
<Route path="*" element={<Navigate to="/edges" replace />} />
</Routes>
</BrowserRouter>
);
}

116
src/auth/authActions.ts Normal file
View File

@@ -0,0 +1,116 @@
import type { KeycloakInitOptions } from 'keycloak-js';
import { keycloak } from './keycloakClient';
import { getAuthState, getIdentityState, setAuthState, type AuthState } from './authStore';
let initPromise: Promise<boolean> | null = null;
let refreshPromise: Promise<string | null> | null = null;
/** Инициализирует Keycloak один раз и запускает login-required flow при включенном SSO. */
export async function initAuth(): Promise<AuthState> {
if (!keycloak) {
return getAuthState();
}
if (!initPromise) {
const initOptions: KeycloakInitOptions = {
onLoad: 'login-required',
pkceMethod: 'S256',
checkLoginIframe: false,
};
initPromise = keycloak.init(initOptions).then((authenticated) => {
setAuthState({
initialized: true,
authenticated,
...getIdentityState(),
});
return authenticated;
});
}
await initPromise;
return getAuthState();
}
/** Обновляет access token перед API-запросами и повторно использует текущий refresh-promise. */
export async function refreshToken(minValidity = 30): Promise<string | null> {
if (!keycloak) {
return null;
}
const client = keycloak;
if (!refreshPromise) {
refreshPromise = client
.updateToken(minValidity)
.then(() => {
setAuthState({
authenticated: Boolean(client.authenticated),
...getIdentityState(),
});
return client.token ?? null;
})
.catch(async () => {
setAuthState({
authenticated: false,
username: null,
fullName: null,
email: null,
});
await login();
return null;
})
.finally(() => {
refreshPromise = null;
});
}
return refreshPromise;
}
/** Возвращает действующий access token или null, если SSO отключен/пользователь не вошел. */
export async function getAccessToken(): Promise<string | null> {
if (!keycloak?.authenticated) {
return null;
}
await refreshToken(30);
return keycloak.token ?? null;
}
/** Запускает ручной вход через Keycloak с возвратом на текущий адрес. */
export async function login(redirectUri = window.location.href): Promise<void> {
await keycloak?.login({ redirectUri });
}
/** Завершает Keycloak-сессию и возвращает пользователя на origin приложения. */
export async function logout(redirectUri = window.location.origin): Promise<void> {
await keycloak?.logout({ redirectUri });
}
if (keycloak) {
keycloak.onAuthSuccess = () => {
setAuthState({
initialized: true,
authenticated: true,
...getIdentityState(),
});
};
keycloak.onAuthLogout = () => {
setAuthState({
initialized: true,
authenticated: false,
username: null,
fullName: null,
email: null,
});
};
keycloak.onTokenExpired = () => {
void refreshToken(30);
};
}

58
src/auth/authStore.ts Normal file
View File

@@ -0,0 +1,58 @@
import { authEnabled, keycloak } from './keycloakClient';
export type AuthState = {
initialized: boolean;
authenticated: boolean;
enabled: boolean;
username: string | null;
fullName: string | null;
email: string | null;
};
type AuthListener = (state: AuthState) => void;
const defaultState: AuthState = {
initialized: !authEnabled,
authenticated: !authEnabled,
enabled: authEnabled,
username: null,
fullName: null,
email: null,
};
let authState = defaultState;
const listeners = new Set<AuthListener>();
/** Извлекает пользовательскую идентичность из распарсенного Keycloak-токена. */
export function getIdentityState(): Pick<AuthState, 'username' | 'fullName' | 'email'> {
const tokenParsed = keycloak?.tokenParsed as
| { preferred_username?: string; name?: string; email?: string }
| undefined;
return {
username: tokenParsed?.preferred_username ?? null,
fullName: tokenParsed?.name ?? null,
email: tokenParsed?.email ?? null,
};
}
/** Обновляет auth-состояние и уведомляет все React-подписки. */
export function setAuthState(partial: Partial<AuthState>) {
authState = { ...authState, ...partial };
listeners.forEach((listener) => listener(authState));
}
/** Возвращает актуальный снимок auth-состояния без подписки. */
export function getAuthState(): AuthState {
return authState;
}
/** Подписывает UI на изменения Keycloak-сессии и возвращает функцию отписки. */
export function subscribeAuth(listener: AuthListener): () => void {
listeners.add(listener);
listener(authState);
return () => {
listeners.delete(listener);
};
}

View File

@@ -1,183 +1,3 @@
import Keycloak, { type KeycloakInitOptions } from 'keycloak-js';
const keycloakUrl = import.meta.env.VITE_KEYCLOAK_URL;
const keycloakRealm = import.meta.env.VITE_KEYCLOAK_REALM;
const keycloakClientId = import.meta.env.VITE_KEYCLOAK_CLIENT_ID;
const authEnabled = Boolean(keycloakUrl && keycloakRealm && keycloakClientId);
const keycloak = authEnabled
? new Keycloak({
url: keycloakUrl!,
realm: keycloakRealm!,
clientId: keycloakClientId!,
})
: null;
let initPromise: Promise<boolean> | null = null;
let refreshPromise: Promise<string | null> | null = null;
export type AuthState = {
initialized: boolean;
authenticated: boolean;
enabled: boolean;
username: string | null;
fullName: string | null;
email: string | null;
};
type AuthListener = (state: AuthState) => void;
const defaultState: AuthState = {
initialized: !authEnabled,
authenticated: !authEnabled,
enabled: authEnabled,
username: null,
fullName: null,
email: null,
};
let authState = defaultState;
const listeners = new Set<AuthListener>();
/** Извлекает пользовательскую идентичность из распарсенного Keycloak-токена. */
function getIdentityState(): Pick<AuthState, 'username' | 'fullName' | 'email'> {
const tokenParsed = keycloak?.tokenParsed as
| { preferred_username?: string; name?: string; email?: string }
| undefined;
return {
username: tokenParsed?.preferred_username ?? null,
fullName: tokenParsed?.name ?? null,
email: tokenParsed?.email ?? null,
};
}
/** Обновляет auth-состояние и уведомляет все React-подписки. */
function setAuthState(partial: Partial<AuthState>) {
authState = { ...authState, ...partial };
listeners.forEach((listener) => listener(authState));
}
if (keycloak) {
keycloak.onAuthSuccess = () => {
setAuthState({
initialized: true,
authenticated: true,
...getIdentityState(),
});
};
keycloak.onAuthLogout = () => {
setAuthState({
initialized: true,
authenticated: false,
username: null,
fullName: null,
email: null,
});
};
keycloak.onTokenExpired = () => {
void refreshToken(30);
};
}
/** Возвращает актуальный снимок auth-состояния без подписки. */
export function getAuthState(): AuthState {
return authState;
}
/** Подписывает UI на изменения Keycloak-сессии и возвращает функцию отписки. */
export function subscribeAuth(listener: AuthListener): () => void {
listeners.add(listener);
listener(authState);
return () => {
listeners.delete(listener);
};
}
/** Инициализирует Keycloak один раз и запускает login-required flow при включенном SSO. */
export async function initAuth(): Promise<AuthState> {
if (!keycloak) {
return authState;
}
if (!initPromise) {
const initOptions: KeycloakInitOptions = {
onLoad: 'login-required',
pkceMethod: 'S256',
checkLoginIframe: false,
};
initPromise = keycloak.init(initOptions).then((authenticated) => {
setAuthState({
initialized: true,
authenticated,
...getIdentityState(),
});
return authenticated;
});
}
await initPromise;
return authState;
}
/** Обновляет access token перед API-запросами и повторно использует текущий refresh-promise. */
export async function refreshToken(minValidity = 30): Promise<string | null> {
if (!keycloak) {
return null;
}
if (!refreshPromise) {
refreshPromise = keycloak
.updateToken(minValidity)
.then(() => {
setAuthState({
authenticated: Boolean(keycloak.authenticated),
...getIdentityState(),
});
return keycloak.token ?? null;
})
.catch(async () => {
setAuthState({
authenticated: false,
username: null,
fullName: null,
email: null,
});
await login();
return null;
})
.finally(() => {
refreshPromise = null;
});
}
return refreshPromise;
}
/** Возвращает действующий access token или null, если SSO отключен/пользователь не вошел. */
export async function getAccessToken(): Promise<string | null> {
if (!keycloak?.authenticated) {
return null;
}
await refreshToken(30);
return keycloak.token ?? null;
}
/** Запускает ручной вход через Keycloak с возвратом на текущий адрес. */
export async function login(redirectUri = window.location.href): Promise<void> {
await keycloak?.login({ redirectUri });
}
/** Завершает Keycloak-сессию и возвращает пользователя на origin приложения. */
export async function logout(redirectUri = window.location.origin): Promise<void> {
await keycloak?.logout({ redirectUri });
}
export { getAuthState, subscribeAuth } from './authStore';
export type { AuthState } from './authStore';
export { getAccessToken, initAuth, login, logout, refreshToken } from './authActions';

View File

@@ -0,0 +1,12 @@
import Keycloak from 'keycloak-js';
import { keycloakClientId, keycloakRealm, keycloakUrl } from '../shared/config/env';
export const authEnabled = Boolean(keycloakUrl && keycloakRealm && keycloakClientId);
export const keycloak = authEnabled
? new Keycloak({
url: keycloakUrl as string,
realm: keycloakRealm as string,
clientId: keycloakClientId as string,
})
: null;

View File

@@ -1,332 +1 @@
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 type { EChartsOption, SeriesOption } from 'echarts';
import { useMemo, useRef } from 'react';
import type { HistoryResponse } from '../api/cloud';
echarts.use([
LineChart,
ScatterChart,
GridComponent,
LegendComponent,
TooltipComponent,
DataZoomComponent,
CanvasRenderer,
]);
const SERIES_COLORS = [
'#5B8FF9',
'#5AD8A6',
'#F6BD16',
'#E8684A',
'#6DC8EC',
'#FF9D4D',
'#73D13D',
'#A7B3FF',
];
type HistoryChartProps = {
data?: HistoryResponse;
loading: boolean;
from?: string;
to?: string;
tagLabels?: Record<string, string>;
};
type AvgPointValue = [time: number, value: number, min: number, avg: number, max: number, count: number];
type TooltipParam = {
marker?: string;
seriesName?: string;
value?: unknown;
};
type DataZoomState = {
start?: number;
end?: number;
startValue?: number;
endValue?: number;
};
type DataZoomEventBatch = DataZoomState & {
batch?: DataZoomState[];
};
/** Подбирает подпись оси времени под текущий масштаб графика. */
function formatAxisDate(value: number, spanMs?: number): string {
const date = new Date(value);
if (!spanMs || spanMs <= 24 * 60 * 60 * 1000) {
return new Intl.DateTimeFormat('ru-RU', { hour: '2-digit', minute: '2-digit' }).format(date);
}
if (spanMs <= 7 * 24 * 60 * 60 * 1000) {
return new Intl.DateTimeFormat('ru-RU', { day: '2-digit', month: '2-digit', hour: '2-digit' }).format(date);
}
return new Intl.DateTimeFormat('ru-RU', { day: '2-digit', month: '2-digit' }).format(date);
}
/** Форматирует числовое значение для tooltip без лишнего шума в дробной части. */
function formatChartValue(value: number): string {
return new Intl.NumberFormat('ru-RU', {
maximumFractionDigits: Math.abs(value) >= 100 ? 2 : 3,
}).format(value);
}
/** Проверяет, что tooltip получил основную точку avg-линии, а не вспомогательную серию. */
function isAvgPointValue(value: unknown): value is AvgPointValue {
return Array.isArray(value) && value.length >= 6 && value.every((item) => typeof item === 'number');
}
/** Собирает tooltip с min/avg/max для всех серий на выбранной отметке времени. */
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[3])} · max ${formatChartValue(value[4])}`,
value[5] > 1 ? ` · ${value[5]} точек` : '',
'</strong>',
'</div>',
].join('');
});
return [`<div class="chart-tooltip"><div class="chart-tooltip-title">${header}</div>`, ...rows, '</div>'].join('');
}
/** Создает avg-линию, вертикальные min/max отрезки и точки экстремумов для одной серии. */
function createSeriesOptions(
series: NonNullable<HistoryResponse['series']>[number],
index: number,
label: string,
): SeriesOption[] {
const color = SERIES_COLORS[index % SERIES_COLORS.length];
const avgData: AvgPointValue[] = series.points.map((point) => [
point.t,
point.v,
point.min,
point.avg,
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,
},
];
}
/** Рисует исторические ряды: avg соединяется линией, min/max показываются точками и вертикальным диапазоном. */
export function HistoryChart({ data, loading, from, to, tagLabels = {} }: HistoryChartProps) {
const dataZoomRef = useRef<DataZoomState | null>(null);
const xMin = from ? new Date(from).getTime() : undefined;
const xMax = to ? new Date(to).getTime() : undefined;
const xSpan = Number.isFinite(xMin) && Number.isFinite(xMax) ? Number(xMax) - Number(xMin) : undefined;
const legendData = useMemo(
() => data?.series.map((series) => tagLabels[series.tag] ?? series.tag) ?? [],
[data?.series, tagLabels],
);
const dataZoomState = dataZoomRef.current ?? {};
const option: EChartsOption = useMemo(() => ({
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,
axisLine: { lineStyle: { color: 'rgba(148, 163, 184, 0.35)' } },
axisLabel: {
color: '#94a3b8',
formatter: (value: number) => formatAxisDate(value, xSpan),
},
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),
) ?? [],
}), [data?.series, dataZoomState.end, dataZoomState.endValue, dataZoomState.start, dataZoomState.startValue, legendData, tagLabels, xMax, xMin, xSpan]);
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 />;
}
export { HistoryChart } from '../features/history-chart/HistoryChart';

View File

@@ -1,5 +1,5 @@
import { Activity, Check, Clock3, Plus } from 'lucide-react';
import type { CurrentItem } from '../api/cloud';
import type { CurrentItem } from '../entities/current/types';
import { formatNumber } from '../utils/format';
import { getMetricStatus, type MetricStatusInfo } from '../utils/metricStatus';

View File

@@ -0,0 +1,17 @@
import type { CurrentItem } from '../entities/current/types';
import { formatNumber } from '../utils/format';
type MetricWidgetProps = {
item: CurrentItem;
};
export function MetricWidget({ item }: MetricWidgetProps) {
const title = item.name?.trim() || item.tag;
return (
<article className="metric-widget" title={`${title} (${item.tag})`}>
<span className="metric-widget__tag">{title}</span>
<strong className="metric-widget__value">{formatNumber(item.value)}</strong>
</article>
);
}

View File

@@ -0,0 +1,7 @@
import type { PropsWithChildren } from 'react';
type MetricWidgetsContainerProps = PropsWithChildren;
export function MetricWidgetsContainer({ children }: MetricWidgetsContainerProps) {
return <div className="metric-widgets-grid">{children}</div>;
}

View File

@@ -0,0 +1,13 @@
import { buildApiUrl, getJson } from '../../shared/api/http';
import { cloudApiUrl } from '../../shared/config/env';
import type { CurrentResponse } from './types';
/** Загружает текущие значения показателей для выбранной буровой. */
export function getCurrent(edge: string, tags?: string[]): Promise<CurrentResponse> {
return getJson<CurrentResponse>(cloudApiUrl, '/current', { edge, tags });
}
/** Формирует URL SSE-потока текущих значений. */
export function getCurrentEventsUrl(edge: string, tags?: string[]): string {
return buildApiUrl(cloudApiUrl, '/current/events', { edge, tags });
}

View File

@@ -0,0 +1,22 @@
export type CurrentItem = {
edge: string;
tag: string;
value: number;
createdAt: string;
updatedAt: string;
time: string;
name: string | null;
tagGroup: string | null;
min: number | null;
max: number | null;
comment: string | null;
unitOfMeasurement: string | null;
precision: number | null;
};
export type CurrentResponse = {
edge: string;
items: CurrentItem[];
};
export type CurrentEvent = CurrentResponse;

View File

@@ -0,0 +1,22 @@
import { getAccessToken } from '../../auth/keycloak';
import { getJson } from '../../shared/api/http';
import { diagramApiUrl } from '../../shared/config/env';
import type { DiagramPageResponse, DiagramPageSummary } from './types';
/** Выполняет запрос к diagram-service и пробрасывает Bearer-токен, если UI работает с SSO. */
async function request<T>(path: string, params?: Record<string, string | undefined>): Promise<T> {
const token = await getAccessToken();
return getJson<T>(diagramApiUrl, path, params, {
headers: token ? { Authorization: `Bearer ${token}` } : undefined,
});
}
/** Возвращает список страниц схем; опубликованность определяется по publishedRevision. */
export function listDiagramPages(ownerEdgeId?: string): Promise<DiagramPageSummary[]> {
return request<DiagramPageSummary[]>('/diagram/pages', { ownerEdgeId });
}
/** Загружает опубликованную версию страницы схемы. */
export function getPublishedDiagramPage(pageKey: string): Promise<DiagramPageResponse> {
return request<DiagramPageResponse>(`/diagram/pages/${encodeURIComponent(pageKey)}/published`);
}

View File

@@ -0,0 +1,88 @@
export type DiagramPoint = {
x: number;
y: number;
};
export type DiagramSize = {
width: number;
height: number;
};
export type DiagramBindingConfig = {
stateTagId?: string;
alarmTagId?: string;
edgeId?: string;
sseEdgeId?: string;
sseUrl?: string;
};
export type DiagramNode =
| {
id: string;
kind: 'tagWidget';
tagId: string;
edgeId: string;
widgetType: string;
position: DiagramPoint;
size?: DiagramSize;
zIndex?: number;
label?: string;
displayType?: 'widget' | 'compact' | 'card';
style?: Record<string, unknown>;
}
| {
id: string;
kind: 'decoration';
decorationType: string;
position: DiagramPoint;
size: DiagramSize;
rotation?: number;
zIndex?: number;
data?: Record<string, unknown>;
style?: Record<string, unknown>;
bindings?: DiagramBindingConfig;
};
export type DiagramEdge = {
id: string;
sourceNodeId: string;
targetNodeId: string;
sourceSide?: 'left' | 'right' | 'top' | 'bottom';
targetSide?: 'left' | 'right' | 'top' | 'bottom';
kind: 'wire' | 'power' | 'signal' | 'alert';
label?: string;
animated?: boolean;
waypoints?: DiagramPoint[];
};
export type DiagramDocument = {
schemaVersion: number;
pageKey: string;
ownerEdgeId: string;
title?: string;
viewport?: { x: number; y: number; zoom: number } | null;
background?: {
url?: string;
opacity?: number;
fit?: 'contain' | 'cover' | 'stretch';
};
nodes: DiagramNode[];
edges: DiagramEdge[];
};
export type DiagramPageSummary = {
pageKey: string;
ownerEdgeId: string;
title?: string | null;
schemaVersion: number;
revision: number;
status: 'draft' | 'published' | 'archived';
publishedRevision?: number;
publishedAt?: string;
createdAt: string;
updatedAt: string;
};
export type DiagramPageResponse = DiagramPageSummary & {
document: DiagramDocument;
};

8
src/entities/edge/api.ts Normal file
View File

@@ -0,0 +1,8 @@
import { getJson } from '../../shared/api/http';
import { cloudApiUrl } from '../../shared/config/env';
import type { EdgeResponse } from './types';
/** Возвращает список буровых, доступных в cloud-v3. */
export function getEdges(): Promise<EdgeResponse> {
return getJson<EdgeResponse>(cloudApiUrl, '/edge');
}

View File

@@ -0,0 +1,11 @@
export type EdgeItem = {
id: string;
name: string;
parentId: string | null;
tagIds: string[];
tagCount: number;
};
export type EdgeResponse = {
items: EdgeItem[];
};

View File

@@ -0,0 +1,8 @@
import { getJson } from '../../shared/api/http';
import { cloudApiUrl } from '../../shared/config/env';
import type { HealthResponse } from './types';
/** Запрашивает состояние cloud-v3 и подключенной базы данных. */
export function getHealth(): Promise<HealthResponse> {
return getJson<HealthResponse>(cloudApiUrl, '/health');
}

View File

@@ -0,0 +1,8 @@
export type HealthResponse = {
status: 'ok';
database: {
now: string;
timescaledb_installed: boolean;
timescaledb_version: string | null;
};
};

View File

@@ -0,0 +1,8 @@
import { getJson } from '../../shared/api/http';
import { cloudApiUrl } from '../../shared/config/env';
import type { HistoryRequest, HistoryResponse } from './types';
/** Запрашивает исторический ряд с avg-линией и min/max-диапазоном для графика. */
export function getHistory(params: HistoryRequest): Promise<HistoryResponse> {
return getJson<HistoryResponse>(cloudApiUrl, '/history', params);
}

View File

@@ -0,0 +1,19 @@
export type HistoryPoint = {
time: string;
min_value: number;
avg_value: number;
max_value: number;
point_count: number;
};
export type HistoryResponse = {
rows: HistoryPoint[];
};
export type HistoryRequest = {
edge: string;
tag: string;
from: string;
to: string;
granulate: string;
};

8
src/entities/tag/api.ts Normal file
View File

@@ -0,0 +1,8 @@
import { getJson } from '../../shared/api/http';
import { cloudApiUrl } from '../../shared/config/env';
import type { TagResponse } from './types';
/** Загружает справочник тегов; tag.name используется как отображаемое имя. */
export function getTags(params: { edge?: string; search?: string } = {}): Promise<TagResponse> {
return getJson<TagResponse>(cloudApiUrl, '/tag', params);
}

15
src/entities/tag/types.ts Normal file
View File

@@ -0,0 +1,15 @@
export type TagItem = {
id: string;
name: string;
tagGroup: string | null;
min: number | null;
max: number | null;
comment: string;
unitOfMeasurement: string;
edgeIds: string[];
precision: number | null;
};
export type TagResponse = {
items: TagItem[];
};

View 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;
}

View 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;
}

View File

@@ -0,0 +1,49 @@
import { useMemo, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useParams } from 'react-router-dom';
import { getCurrent } from '../../entities/current/api';
import { createCurrentTagLabels, filterCurrentItems } from '../current/model';
import { useCurrentEvents } from '../current/useCurrentEvents';
import { EdgePageLayout } from './components/EdgePageLayout';
import { IndicatorsView } from './components/IndicatorsView';
export function EdgeCurrentPage() {
const { edgeId = '' } = useParams();
const [search, setSearch] = useState('');
const [selectedTags, setSelectedTags] = useState<string[]>([]);
const currentEventsConnected = useCurrentEvents(edgeId);
const current = useQuery({
queryKey: ['current', edgeId],
queryFn: () => getCurrent(edgeId),
enabled: Boolean(edgeId),
refetchInterval: currentEventsConnected ? false : 1_000,
});
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 toggleTag = (tag: string) => {
setSelectedTags((prev) => (prev.includes(tag) ? prev.filter((selected) => selected !== tag) : [...prev, tag]));
};
return (
<EdgePageLayout
currentEventsConnected={currentEventsConnected}
edgeId={edgeId}
view="indicators"
onRefresh={() => void current.refetch()}
>
<IndicatorsView
items={visibleItems}
search={search}
isError={current.isError}
error={current.error}
selectedTags={selectedTags}
getTagLabel={getTagLabel}
onSearchChange={setSearch}
onToggleTag={toggleTag}
/>
</EdgePageLayout>
);
}

View File

@@ -0,0 +1,45 @@
import { useMemo } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useNavigate, useParams } from 'react-router-dom';
import { getCurrent } from '../../entities/current/api';
import {
countLiveCurrentItems,
getLatestCurrentUpdatedAt,
} from '../current/model';
import { useCurrentEvents } from '../current/useCurrentEvents';
import { EdgePageLayout } from './components/EdgePageLayout';
import { OverviewView } from './components/OverviewView';
export function EdgeDetailPage() {
const navigate = useNavigate();
const { edgeId = '' } = useParams();
const edgePath = `/edges/${encodeURIComponent(edgeId)}`;
const currentEventsConnected = useCurrentEvents(edgeId);
const current = useQuery({
queryKey: ['current', edgeId],
queryFn: () => getCurrent(edgeId),
enabled: Boolean(edgeId),
refetchInterval: currentEventsConnected ? false : 1_000,
});
const currentItems = useMemo(() => current.data?.items ?? [], [current.data?.items]);
const latestUpdatedAt = useMemo(() => getLatestCurrentUpdatedAt(currentItems), [currentItems]);
const liveCount = countLiveCurrentItems(currentItems);
return (
<EdgePageLayout
currentEventsConnected={currentEventsConnected}
edgeId={edgeId}
view="overview"
onRefresh={() => void current.refetch()}
>
<OverviewView
edgeId={edgeId}
totalTags={currentItems.length}
liveCount={liveCount}
latestUpdatedAt={latestUpdatedAt}
onOpenArchive={() => navigate(`${edgePath}/archive`)}
onOpenIndicators={() => navigate(`${edgePath}/indicators`)}
/>
</EdgePageLayout>
);
}

View File

@@ -0,0 +1,80 @@
import { useMemo, useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useParams } from 'react-router-dom';
import { getCurrent } from '../../entities/current/api';
import { toIsoFromInput } from '../../utils/format';
import { getHistoryGranularity } from '../../utils/historyGranularity';
import { createCurrentTagLabels, filterCurrentItems } from '../current/model';
import { useCurrentEvents } from '../current/useCurrentEvents';
import { createRange } from '../history/dateRange';
import { ArchiveView } from './components/ArchiveView';
import { EdgePageLayout } from './components/EdgePageLayout';
export function EdgeHistoryPage() {
const { edgeId = '' } = useParams();
const queryClient = useQueryClient();
const [search, setSearch] = useState('');
const [range, setRange] = useState(() => createRange(24));
const [selectedTags, setSelectedTags] = useState<string[]>([]);
const currentEventsConnected = useCurrentEvents(edgeId);
const current = useQuery({
queryKey: ['current', edgeId],
queryFn: () => getCurrent(edgeId),
enabled: Boolean(edgeId),
refetchInterval: currentEventsConnected ? false : 1_000,
});
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 from = toIsoFromInput(range.from) as string;
const to = toIsoFromInput(range.to) as string;
const historyGranularity = useMemo(() => getHistoryGranularity(from, to), [from, to]);
const toggleTag = (tag: string) => {
setSelectedTags((prev) => (prev.includes(tag) ? prev.filter((selected) => selected !== tag) : [...prev, tag]));
};
const selectFirstTags = () => {
setSelectedTags(visibleItems[0] ? [visibleItems[0].tag] : []);
};
const selectVisibleTags = () => {
setSelectedTags((prev) => Array.from(new Set([...prev, ...visibleItems.map((item) => item.tag)])));
};
const clearVisibleTags = () => {
const visibleTags = new Set(visibleItems.map((item) => item.tag));
setSelectedTags((prev) => prev.filter((tag) => !visibleTags.has(tag)));
};
return (
<EdgePageLayout
currentEventsConnected={currentEventsConnected}
edgeId={edgeId}
view="archive"
onRefresh={() => {
void current.refetch();
void queryClient.invalidateQueries({ queryKey: ['history', edgeId] });
}}
>
<ArchiveView
edgeId={edgeId}
items={visibleItems}
search={search}
selectedTags={selectedTags}
historyGranulate={historyGranularity.granulate}
historyAxis={historyGranularity}
range={range}
onSearchChange={setSearch}
onRangeChange={setRange}
onToggleTag={toggleTag}
onSelectFirstTags={selectFirstTags}
onSelectVisibleTags={selectVisibleTags}
onClearVisibleTags={clearVisibleTags}
onClearTags={() => setSelectedTags([])}
getTagLabel={getTagLabel}
tagLabels={tagLabels}
/>
</EdgePageLayout>
);
}

View File

@@ -0,0 +1,268 @@
import { useState } from 'react';
import type { RefObject } from 'react';
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 { RANGE_PRESETS, createRange, type DateRangeState } from '../../../features/history/dateRange';
import { toIsoFromInput } from '../../../utils/format';
import type { HistoryGranularity } from '../../../utils/historyGranularity';
type ArchiveViewProps = {
edgeId: string;
getTagLabel: (tag: string) => string;
historyAxis: HistoryGranularity;
historyGranulate?: string;
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;
};
type RangePart = 'from' | 'to';
type RangeInputPart = 'date' | 'time';
function getRangeInputPart(value: string, part: RangeInputPart): string {
const [date = '', time = ''] = value.split('T');
return part === 'date' ? date : time;
}
function updateRangeInputPart(value: string, part: RangeInputPart, nextValue: string): string {
const date = getRangeInputPart(value, 'date');
const time = getRangeInputPart(value, 'time');
return part === 'date' ? `${nextValue}T${time}` : `${date}T${nextValue}`;
}
function openInputPicker(input: HTMLInputElement | null): void {
input?.focus();
input?.showPicker?.();
}
type DateRangeFieldProps = {
icon: 'date' | 'time';
inputRef: RefObject<HTMLInputElement | null>;
type: 'date' | 'time';
value: string;
onChange: (value: string) => void;
};
function DateRangeField({ icon, inputRef, type, value, onChange }: DateRangeFieldProps) {
const Icon = icon === 'date' ? CalendarDays : Clock3;
const label = icon === 'date' ? 'Открыть календарь' : 'Открыть выбор времени';
return (
<div className="archive-date-field" onClick={() => openInputPicker(inputRef.current)}>
<button type="button" className="archive-date-picker-button" aria-label={label}>
<Icon size={16} />
</button>
<input
ref={inputRef}
aria-label={label}
className={`archive-date-input archive-date-input--${type}`}
type={type}
value={value}
onChange={(event) => onChange(event.target.value)}
/>
</div>
);
}
export function ArchiveView({
edgeId,
getTagLabel,
historyAxis,
historyGranulate,
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);
const fromDateRef = useRef<HTMLInputElement>(null);
const fromTimeRef = useRef<HTMLInputElement>(null);
const toDateRef = useRef<HTMLInputElement>(null);
const toTimeRef = useRef<HTMLInputElement>(null);
const fromIso = toIsoFromInput(range.from) as string;
const toIso = toIsoFromInput(range.to) as string;
const updateRangePart = (rangePart: RangePart, inputPart: RangeInputPart, value: string) => {
onRangeChange({
...range,
[rangePart]: updateRangeInputPart(range[rangePart], inputPart, value),
});
};
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)}
aria-pressed={selected}
>
<span className="tag-select-item__name">
<span>{label}</span>
{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>
{selected ? <Check size={15} /> : null}
</span>
</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>
<div className="archive-date-range">
<span>С</span>
<DateRangeField
icon="date"
inputRef={fromDateRef}
type="date"
value={getRangeInputPart(range.from, 'date')}
onChange={(value) => updateRangePart('from', 'date', value)}
/>
<DateRangeField
icon="time"
inputRef={fromTimeRef}
type="time"
value={getRangeInputPart(range.from, 'time')}
onChange={(value) => updateRangePart('from', 'time', value)}
/>
</div>
<div className="archive-date-range">
<span>По</span>
<DateRangeField
icon="date"
inputRef={toDateRef}
type="date"
value={getRangeInputPart(range.to, 'date')}
onChange={(value) => updateRangePart('to', 'date', value)}
/>
<DateRangeField
icon="time"
inputRef={toTimeRef}
type="time"
value={getRangeInputPart(range.to, 'time')}
onChange={(value) => updateRangePart('to', 'time', value)}
/>
</div>
</div>
{selectedTags.length ? (
<HistoryChart
key={`${range.from}:${range.to}:${selectedTags.join(',')}`}
edge={edgeId}
from={fromIso}
to={toIso}
granulate={historyAxis.granulate}
tickIntervalMs={historyAxis.tickIntervalMs}
labelFormat={historyAxis.labelFormat}
tags={selectedTags}
tagLabels={tagLabels}
/>
) : (
<div className="chart-placeholder">Разверните список показателей и выберите серию для графика</div>
)}
</div>
</section>
);
}

View File

@@ -0,0 +1,53 @@
import type { ReactNode } from 'react';
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../../../auth/authContext';
import { EdgeSidebar } from './EdgeSidebar';
import { EdgeTopbar } from './EdgeTopbar';
import type { DetailView } from '../types';
type EdgePageLayoutProps = {
children: ReactNode;
currentEventsConnected: boolean;
edgeId: string;
onRefresh: () => void;
view: DetailView;
};
export function EdgePageLayout({
children,
currentEventsConnected,
edgeId,
onRefresh,
view,
}: EdgePageLayoutProps) {
const navigate = useNavigate();
const auth = useAuth();
const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
const edgePath = `/edges/${encodeURIComponent(edgeId)}`;
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={onRefresh}
/>
{children}
</section>
</main>
);
}

View File

@@ -0,0 +1,62 @@
import { Activity, BarChart3, Gauge, Menu, PanelLeftClose, PanelLeftOpen } 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>
</nav>
</aside>
);
}

View 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>
);
}

View File

@@ -0,0 +1,99 @@
import { Search } from 'lucide-react';
import type { CurrentItem } from '../../../entities/current/types';
import { MetricWidget } from '../../../components/MetricWidget';
import { MetricWidgetsContainer } from '../../../components/MetricWidgetsContainer';
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) {
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">
<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>{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>
) */}
<MetricWidgetsContainer>
{items.map((item) => (
<MetricWidget key={item.tag} item={item} />
))}
</MetricWidgetsContainer>
</>
)}
</section>
);
}

View File

@@ -0,0 +1,64 @@
import { Activity, BarChart3, CalendarClock } from 'lucide-react';
import { formatDateTime } from '../../../utils/format';
type OverviewViewProps = {
edgeId: string;
latestUpdatedAt?: Date;
liveCount: number;
totalTags: number;
onOpenArchive: () => void;
onOpenIndicators: () => void;
};
export function OverviewView({
edgeId,
latestUpdatedAt,
liveCount,
totalTags,
onOpenArchive,
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>1</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">
<CalendarClock size={18} />
Техническое обслуживание
</button>
</div>
</section>
</section>
);
}

View File

@@ -0,0 +1 @@
export type DetailView = 'overview' | 'archive' | 'indicators';

View File

@@ -0,0 +1,154 @@
import { useMemo, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { ArrowRight, Clock3, Gauge, LogOut, RefreshCw, Search, ShieldAlert } 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;
};
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 }: 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}
/>
))}
</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,
}: {
edge: EdgeItem;
onOpenEdge: (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">
<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>
);
}

View 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>
);
}

View 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>
);
}

View 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(' ');
}

View 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}`);
}

View 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[];
};

View File

@@ -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 };
}

View File

@@ -0,0 +1,70 @@
import { useCallback, useMemo, useRef } from 'react';
import type { HistoryAxisLabelFormat } from '../../utils/historyGranularity';
import type { DataZoomEventBatch, DataZoomState } from './chartTypes';
import { HistoryChartArea } from './HistoryChartArea';
import { createHistoryChartOptions } from './historyChartOptions';
import { useHistoryChartQueries } from './useHistoryChartQueries';
import { useHistoryChartSeries } from './useHistoryChartSeries';
type HistoryChartProps = {
edge: string;
from: string;
granulate: string;
labelFormat?: HistoryAxisLabelFormat;
tags: string[];
tickIntervalMs?: number;
to: string;
tagLabels?: Record<string, string>;
};
/** Контейнер истории: загружает выбранные теги и передает готовые серии в область ECharts. */
export function HistoryChart({
edge,
from,
granulate,
labelFormat,
tags,
tickIntervalMs,
to,
tagLabels = {},
}: HistoryChartProps) {
const dataZoomRef = useRef<DataZoomState | null>(null);
const lines = useHistoryChartQueries({ edge, from, granulate, tags, to, tagLabels });
const series = useHistoryChartSeries(lines);
const legendData = useMemo(() => lines.map((line) => line.label), [lines]);
const loading = lines.some((line) => line.loading);
const option = useMemo(
() =>
createHistoryChartOptions({
dataZoomState: dataZoomRef.current ?? {},
from,
to,
labelFormat,
legendData,
series,
tickIntervalMs,
}),
[from, labelFormat, legendData, series, tickIntervalMs, to],
);
const handleDataZoom = useCallback((event: DataZoomEventBatch) => {
const state = event.batch?.[0] ?? event;
dataZoomRef.current = {
start: state.start,
end: state.end,
startValue: state.startValue,
endValue: state.endValue,
};
}, []);
return (
<HistoryChartArea
hasData={series.length > 0}
hasSelection={tags.length > 0}
loading={loading}
option={option}
onDataZoom={handleDataZoom}
/>
);
}

View File

@@ -0,0 +1,43 @@
import type { EChartsOption } from 'echarts';
import ReactEChartsCore from 'echarts-for-react/esm/core.js';
import { useMemo } from 'react';
import type { DataZoomEventBatch } from './chartTypes';
import { echarts } from './historyChartEcharts';
type HistoryChartAreaProps = {
hasData: boolean;
hasSelection: boolean;
loading: boolean;
option: EChartsOption;
onDataZoom: (event: DataZoomEventBatch) => void;
};
/** Отвечает только за визуальную область графика: placeholder или ECharts canvas. */
export function HistoryChartArea({
hasData,
hasSelection,
loading,
option,
onDataZoom,
}: HistoryChartAreaProps) {
const onChartEvents = useMemo(
() => ({
datazoom: onDataZoom,
}),
[onDataZoom],
);
if (!hasSelection) {
return <div className="chart-placeholder">Разверните список показателей и выберите серию для графика</div>;
}
if (loading) {
return <div className="chart-placeholder">Загрузка графика...</div>;
}
if (!hasData) {
return <div className="chart-placeholder">Нет данных для выбранного диапазона</div>;
}
return <ReactEChartsCore echarts={echarts} option={option} className="history-chart" onEvents={onChartEvents} lazyUpdate />;
}

View 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[];
};

View File

@@ -0,0 +1,21 @@
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';
echarts.use([
LineChart,
ScatterChart,
GridComponent,
LegendComponent,
TooltipComponent,
DataZoomComponent,
CanvasRenderer,
]);
export { echarts };

View 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('');
}

View File

@@ -0,0 +1,105 @@
import type { EChartsOption } from 'echarts';
import type { SeriesOption } from 'echarts';
import type { HistoryAxisLabelFormat } from '../../utils/historyGranularity';
import type { DataZoomState } from './chartTypes';
import { formatAxisDate, formatTooltip } from './historyChartFormat';
import { SERIES_COLORS } from './historyChartSeries';
export type HistoryChartOptionsInput = {
dataZoomState: DataZoomState;
from?: string;
to?: string;
labelFormat?: HistoryAxisLabelFormat;
legendData: string[];
series: SeriesOption[];
tickIntervalMs?: number;
};
export function createHistoryChartOptions({
dataZoomState,
from,
to,
labelFormat,
legendData,
series,
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,
};
}

View File

@@ -0,0 +1,101 @@
import type { SeriesOption } from 'echarts';
import type { HistoryPoint } 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(points: HistoryPoint[], index: number, label: string): SeriesOption[] {
const color = SERIES_COLORS[index % SERIES_COLORS.length];
const avgData: AvgPointValue[] = points.map((point) => {
const time = new Date(point.time).getTime();
return [time, point.avg_value, point.min_value, point.max_value, point.point_count];
});
const spreadData = points.flatMap((point) => {
const time = new Date(point.time).getTime();
return [
[time, point.min_value],
[time, point.max_value],
[time, null],
];
});
return [
{
name: label,
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,
type: 'scatter',
data: points.map((point) => [new Date(point.time).getTime(), point.min_value]),
symbolSize: 4,
silent: true,
tooltip: { show: false },
itemStyle: {
color,
opacity: 0.72,
},
emphasis: {
disabled: true,
},
z: 2,
},
{
name: label,
type: 'scatter',
data: points.map((point) => [new Date(point.time).getTime(), point.max_value]),
symbolSize: 4,
silent: true,
tooltip: { show: false },
itemStyle: {
color,
opacity: 0.72,
},
emphasis: {
disabled: true,
},
z: 2,
},
{
name: label,
type: 'line',
showSymbol: false,
smooth: false,
sampling: 'lttb',
data: avgData,
lineStyle: {
width: 1.8,
color,
},
emphasis: {
focus: 'series',
},
z: 3,
},
];
}

View File

@@ -0,0 +1,52 @@
import { useMemo } from 'react';
import { useQueries } from '@tanstack/react-query';
import { getHistory } from '../../entities/history/api';
import type { HistoryPoint } from '../../entities/history/types';
type UseHistoryChartQueriesParams = {
edge: string;
from: string;
granulate: string;
tags: string[];
to: string;
tagLabels: Record<string, string>;
};
export type HistoryChartLineData = {
index: number;
label: string;
loading: boolean;
rows: HistoryPoint[];
tag: string;
};
export function useHistoryChartQueries({
edge,
from,
granulate,
tags,
to,
tagLabels,
}: UseHistoryChartQueriesParams): HistoryChartLineData[] {
const enabled = Boolean(edge && from && granulate && to);
const queries = useQueries({
queries: tags.map((tag) => ({
queryKey: ['history', edge, tag, from, to, granulate],
queryFn: () => getHistory({ edge, tag, from, to, granulate }),
enabled,
})),
});
return useMemo(
() =>
tags.map((tag, index) => ({
index,
label: tagLabels[tag] ?? tag,
loading: enabled && queries[index].isPending,
rows: queries[index].data?.rows ?? [],
tag,
})),
[enabled, queries, tagLabels, tags],
);
}

View File

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

View 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),
};
}

View File

@@ -1,16 +1,16 @@
const DEFAULT_TOIR_ORIGIN = 'https://toir-light.greact.ru';
import { toirLightOrigin } from '../shared/config/env';
/** Возвращает origin встроенного TOиР-приложения с безопасной нормализацией слеша. */
/** Возвращает origin встроенного ТОиР-приложения из Vite env. */
export function getToirLightOrigin(): string {
return (import.meta.env.VITE_TOIR_LIGHT_ORIGIN ?? DEFAULT_TOIR_ORIGIN).replace(/\/$/, '');
return toirLightOrigin;
}
/** Определяет targetOrigin для postMessage в iframe TOиР. */
/** Определяет targetOrigin для postMessage в iframe ТОиР. */
export function getToirLightPostMessageTarget(): string {
return getToirLightOrigin();
}
/** Собирает полный URL iframe TOиР и передает тему через query-параметр. */
/** Собирает полный URL iframe ТОиР и передает тему через query-параметр. */
export function buildToirLightUrl(path: string, theme = 'dark'): string {
const origin = getToirLightOrigin();
const normalizedPath = path.startsWith('/') ? path : `/${path}`;

View File

@@ -1,26 +1,13 @@
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import App from './App';
import { AuthProvider } from './auth/AuthProvider';
import { AppProviders } from './app/providers';
import './styles/index.css';
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 1_000,
retry: 1,
refetchOnWindowFocus: false,
},
},
});
createRoot(document.getElementById('root')!).render(
<StrictMode>
<QueryClientProvider client={queryClient}>
<AuthProvider>
<App />
</AuthProvider>
</QueryClientProvider>
<AppProviders>
<App />
</AppProviders>
</StrictMode>,
);

View File

@@ -1,723 +1,3 @@
import { useEffect, useMemo, useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import {
Activity,
BarChart3,
CalendarClock,
ChevronDown,
DatabaseZap,
Gauge,
LogOut,
Menu,
PanelLeftClose,
PanelLeftOpen,
RefreshCw,
Search,
Wrench,
} from 'lucide-react';
import { useNavigate, useParams } from 'react-router-dom';
import type { CurrentEvent, CurrentItem, CurrentResponse, HistoryResponse } from '../api/cloud';
import { getCurrent, getCurrentEventsUrl, getHistory } from '../api/cloud';
import { useAuth } from '../auth/authContext';
import { HistoryChart } from '../components/HistoryChart';
import { MetricCard } from '../components/MetricCard';
import { ToirLightIframe } from '../components/ToirLightIframe';
import { formatDateTime, formatNumber, toInputDateTimeValue, toIsoFromInput } from '../utils/format';
import { getMetricStatus } from '../utils/metricStatus';
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;
const ACTIVE_EQUIPMENT_PATH =
'/equipment?filter=%7B%22status%22%3A%5B%22Active%22%5D%7D&displayedFilters=%7B%22status%22%3Atrue%7D';
type DetailView = 'overview' | 'archive' | 'indicators' | 'equipment';
type EdgeDetailPageProps = {
view: DetailView;
};
type DateRangeState = {
from: string;
to: string;
};
/** Создает диапазон истории от текущего времени на заданное количество часов назад. */
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),
};
}
/** Возвращает русское имя тега из tag.name, если оно пришло из cloud-v3. */
function getItemLabel(item: CurrentItem): string {
return item.name?.trim() || item.tag;
}
/** Собирает общий layout edge-раздела: меню, текущие данные, архив, показатели и iframe оборудования. */
export function EdgeDetailPage({ view }: EdgeDetailPageProps) {
const navigate = useNavigate();
const queryClient = useQueryClient();
const auth = useAuth();
const { edgeId = '' } = useParams();
const [sidebarCollapsed, setSidebarCollapsed] = useState(false);
const [currentEventsConnected, setCurrentEventsConnected] = useState(false);
const [search, setSearch] = useState('');
const [range, setRange] = useState(() => createRange(24));
const [selectedTags, setSelectedTags] = useState<string[]>([]);
const edgePath = `/edges/${encodeURIComponent(edgeId)}`;
const current = useQuery({
queryKey: ['current', edgeId],
queryFn: () => getCurrent(edgeId),
enabled: Boolean(edgeId),
refetchInterval: currentEventsConnected ? false : 1_000,
});
useEffect(() => {
if (!edgeId || typeof EventSource === 'undefined') {
setCurrentEventsConnected(false);
return undefined;
}
const eventSource = new EventSource(getCurrentEventsUrl(edgeId));
eventSource.onopen = () => setCurrentEventsConnected(true);
eventSource.onerror = () => setCurrentEventsConnected(false);
eventSource.onmessage = (message) => {
const event = JSON.parse(message.data) as CurrentEvent;
queryClient.setQueryData<CurrentResponse>(['current', edgeId], event);
};
return () => {
eventSource.close();
setCurrentEventsConnected(false);
};
}, [edgeId, queryClient]);
const tagLabels = useMemo(() => {
return Object.fromEntries((current.data?.items ?? []).map((item) => [item.tag, getItemLabel(item)]));
}, [current.data?.items]);
const getTagLabel = (tag: string) => tagLabels[tag] ?? tag;
const visibleItems = useMemo(() => {
const query = search.trim().toLowerCase();
const items = current.data?.items ?? [];
return query
? items.filter((item) =>
[
item.tag,
item.name,
item.comment,
item.tagGroup,
item.unitOfMeasurement,
]
.filter(Boolean)
.join(' ')
.toLowerCase()
.includes(query),
)
: items;
}, [current.data?.items, search]);
const latestUpdatedAt = useMemo(() => {
const latest = (current.data?.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);
}, [current.data?.items]);
const liveCount =
current.data?.items.filter((item) => {
const ageSeconds = (Date.now() - new Date(item.time).getTime()) / 1000;
return ageSeconds <= 30;
}).length ?? 0;
const history = useQuery({
queryKey: ['history', edgeId, selectedTags, range.from, range.to],
queryFn: () =>
getHistory({
edge: edgeId,
tags: selectedTags,
from: toIsoFromInput(range.from),
to: toIsoFromInput(range.to),
targetPoints: 1600,
}),
enabled: Boolean(edgeId && selectedTags.length),
refetchInterval: false,
});
/** Переключает выбранный тег для отображения на историческом графике. */
const toggleTag = (tag: string) => {
setSelectedTags((prev) => (prev.includes(tag) ? prev.filter((item) => item !== tag) : [...prev, tag]));
};
/** Быстро выбирает первые найденные показатели для первичного анализа графика. */
const selectFirstTags = () => {
setSelectedTags(visibleItems.slice(0, 6).map((item) => item.tag));
};
/** Добавляет все отфильтрованные показатели к текущему набору выбранных тегов. */
const selectVisibleTags = () => {
setSelectedTags((prev) => Array.from(new Set([...prev, ...visibleItems.map((item) => item.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' : ''}`}>
<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={() => setSidebarCollapsed((collapsed) => !collapsed)}
title={sidebarCollapsed ? 'Развернуть меню' : 'Свернуть меню'}
>
{sidebarCollapsed ? <PanelLeftOpen size={18} /> : <PanelLeftClose size={18} />}
</button>
</div>
<nav className="nav-list" aria-label="Основная навигация">
<button className="nav-item nav-item--button" type="button" onClick={() => navigate('/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={() => navigate(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={() => navigate(`${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={() => navigate(`${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={() => navigate(`${edgePath}/equipment`)}
>
<Wrench size={18} />
<span className="nav-label">Оборудование</span>
</button>
{/* Электросхемы временно скрыты до готовности опубликованных схем и diagram-service. */}
{/* <button
className={`nav-item nav-item--button ${view === 'electrical' ? 'nav-item--active' : ''}`}
type="button"
onClick={() => navigate(`${edgePath}/electrical`)}
>
<CircuitBoard size={18} />
<span className="nav-label">Электросхемы</span>
</button> */}
</nav>
</aside>
<section className={`workspace workspace--${view}`}>
<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={() => navigate('/edges')}>
<Menu size={17} />
К списку
</button>
<button type="button" className="icon-button" onClick={() => current.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>
{view === 'overview' ? (
<OverviewView
edgeId={edgeId}
totalTags={current.data?.items.length ?? 0}
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}
historySource={history.data?.source}
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}
{/* Электросхемы временно скрыты до готовности опубликованных схем и diagram-service. */}
{/* {view === 'electrical' ? <ElectricalSchematicsPage edgeId={edgeId} /> : null} */}
</section>
</main>
);
}
/** Показывает обзор выбранного edge и быстрые переходы в основные разделы. */
function OverviewView({
edgeId,
totalTags,
liveCount,
latestUpdatedAt,
selectedCount,
onOpenArchive,
onOpenIndicators,
onOpenEquipment,
}: {
edgeId: string;
totalTags: number;
liveCount: number;
latestUpdatedAt?: Date;
selectedCount: number;
onOpenArchive: () => void;
onOpenIndicators: () => void;
onOpenEquipment: () => void;
}) {
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>
{/* Электросхемы временно скрыты до готовности опубликованных схем и diagram-service. */}
{/* <button type="button" onClick={onOpenElectrical}>
<CircuitBoard size={18} />
Электросхемы
</button> */}
<button type="button">
<CalendarClock size={18} />
Техническое обслуживание
</button>
</div>
</section>
</section>
);
}
/** Управляет выбором тегов и диапазона для исторического графика cloud-v3. */
function ArchiveView({
items,
search,
selectedTags,
history,
historyLoading,
historySource,
range,
onSearchChange,
onRangeChange,
onToggleTag,
onSelectFirstTags,
onSelectVisibleTags,
onClearVisibleTags,
onClearTags,
getTagLabel,
tagLabels,
}: {
items: CurrentItem[];
search: string;
selectedTags: string[];
history?: HistoryResponse;
historyLoading: boolean;
historySource?: string;
range: DateRangeState;
onSearchChange: (value: string) => void;
onRangeChange: (value: DateRangeState) => void;
onToggleTag: (tag: string) => void;
onSelectFirstTags: () => void;
onSelectVisibleTags: () => void;
onClearVisibleTags: () => void;
onClearTags: () => void;
getTagLabel: (tag: string) => string;
tagLabels: Record<string, string>;
}) {
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 · {historySource ?? 'ожидание'}
</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}>
Первые 6
</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)}
tagLabels={tagLabels}
/>
) : (
<div className="chart-placeholder">Разверните список показателей и выберите серии для графика</div>
)}
</div>
</section>
);
}
/** Встраивает страницу активного оборудования из ТОиР light почти на всю рабочую область. */
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>
);
}
/** Показывает текущие показатели edge в режимах общей картины и детальных карточек. */
function IndicatorsView({
items,
search,
isError,
error,
selectedTags,
getTagLabel,
onSearchChange,
onToggleTag,
}: {
items: CurrentItem[];
search: string;
isError: boolean;
error: unknown;
selectedTags: string[];
getTagLabel: (tag: string) => string;
onSearchChange: (value: string) => void;
onToggleTag: (tag: string) => void;
}) {
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>
);
}
export { EdgeDetailPage } from '../features/edge-detail/EdgeDetailPage';
export { EdgeCurrentPage } from '../features/edge-detail/EdgeCurrentPage';
export { EdgeHistoryPage } from '../features/edge-detail/EdgeHistoryPage';

View File

@@ -1,235 +1 @@
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 { EdgeItem, getEdges } from '../api/cloud';
import { useAuth } from '../auth/authContext';
import { formatDateTime } from '../utils/format';
type EdgesDashboardProps = {
onOpenEdge: (edgeId: string) => void;
onOpenEquipment: (edgeId: string) => void;
};
/** Определяет базовый статус edge по наличию последних и live-данных. */
function getEdgeState(edge: EdgeItem): 'ok' | 'warn' | 'empty' {
if (!edge.lastDataAt) {
return 'empty';
}
if (edge.liveTagCount > 0) {
return 'ok';
}
return 'warn';
}
/** Возвращает пользовательское имя edge, если оно отличается от технического id. */
function getEdgeTitle(edge: EdgeItem): string {
if (edge.name && edge.name !== edge.id) {
return edge.name;
}
return edge.id;
}
/** Отображает стартовый dashboard со списком edge-установок и общей статистикой cloud-v3. */
export function EdgesDashboard({ onOpenEdge, onOpenEquipment }: EdgesDashboardProps) {
const [search, setSearch] = useState('');
const auth = useAuth();
const edges = useQuery({
queryKey: ['edge'],
queryFn: getEdges,
refetchInterval: 5_000,
});
const filteredEdges = useMemo(() => {
const query = search.trim().toLowerCase();
const items = edges.data?.items ?? [];
if (!query) {
return items;
}
return items.filter((edge) => `${edge.id} ${edge.name}`.toLowerCase().includes(query));
}, [edges.data?.items, search]);
const stats = useMemo(() => {
const items = edges.data?.items ?? [];
const normal = items.filter((edge) => getEdgeState(edge) === 'ok').length;
const stale = items.filter((edge) => getEdgeState(edge) === 'warn').length;
const empty = items.filter((edge) => getEdgeState(edge) === 'empty').length;
return {
total: items.length,
normal,
stale,
empty,
liveTags: items.reduce((sum, edge) => sum + edge.liveTagCount, 0),
};
}, [edges.data?.items]);
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={stats.total} tone="neutral" />
<StatBlock label="В норме" value={stats.normal} tone="success" />
<StatBlock label="Нет live" value={stats.stale} tone="warning" />
<StatBlock label="Нет данных" value={stats.empty} tone="danger" />
<StatBlock label="Live тегов" value={stats.liveTags} tone="accent" />
</section>
{edges.isError ? (
<div className="empty-panel">Не удалось загрузить список буровых: {String(edges.error)}</div>
) : (
<section className="edge-card-grid" aria-label="Буровые установки">
{filteredEdges.map((edge, index) => (
<EdgeCard
key={edge.id}
edge={edge}
index={index}
onOpenEdge={onOpenEdge}
onOpenEquipment={onOpenEquipment}
/>
))}
</section>
)}
{!edges.isPending && !filteredEdges.length && !edges.isError ? (
<div className="empty-panel">В cloud-v3 пока нет буровых</div>
) : null}
</main>
);
}
/** Показывает один числовой показатель общей статистики dashboard. */
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>
);
}
/** Рендерит карточку edge с быстрыми переходами в рабочие разделы. */
function EdgeCard({
edge,
onOpenEdge,
onOpenEquipment,
}: {
edge: EdgeItem;
index: number;
onOpenEdge: (edgeId: string) => void;
onOpenEquipment: (edgeId: string) => void;
}) {
const state = getEdgeState(edge);
const title = getEdgeTitle(edge);
const stateLabel = state === 'ok' ? 'В норме' : state === 'warn' ? 'Нет live' : 'Нет данных';
return (
<article className={`edge-card edge-card--${state}`}>
<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>
<span className={`edge-state edge-state--${state}`}>
<Gauge size={14} />
{stateLabel}
</span>
</header>
<dl className="edge-card__meta">
<div>
<dt>Показатели</dt>
<dd>{edge.currentTagCount}/{edge.tagCount}</dd>
</div>
<div>
<dt>Live</dt>
<dd>{edge.liveTagCount}</dd>
</div>
<div>
<dt>
<Clock3 size={14} />
Последние данные
</dt>
<dd>{edge.lastDataAt ? formatDateTime(edge.lastDataAt) : '-'}</dd>
</div>
</dl>
<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>
{/* Электросхемы временно скрыты до готовности опубликованных схем и diagram-service. */}
{/* <button type="button" onClick={() => onOpenElectrical(edge.id)}>
<CircuitBoard 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>
);
}
export { EdgesDashboard } from '../features/edges-dashboard/EdgesDashboard';

View File

@@ -1,476 +1 @@
import { useEffect, useMemo, useState, type CSSProperties } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Activity, AlertTriangle, CircuitBoard, DatabaseZap, PlugZap, RefreshCw } from 'lucide-react';
import type {
CurrentEvent,
CurrentItem,
CurrentResponse,
} from '../api/cloud';
import { getCurrent, getCurrentEventsUrl } from '../api/cloud';
import {
getPublishedDiagramPage,
listDiagramPages,
type DiagramDocument,
type DiagramEdge,
type DiagramNode,
type DiagramPageSummary,
type DiagramPoint,
} from '../api/diagram';
import { formatDateTime, formatNumber } from '../utils/format';
type ElectricalSchematicsPageProps = {
edgeId: string;
};
type LiveValue = CurrentItem & {
sourceKey: string;
};
type BindingTag = {
tagId: string;
edgeId: string;
sourceKey: string;
sseUrl?: string;
};
type LiveGroup = {
sourceKey: string;
edgeId: string;
sseUrl?: string;
tags: string[];
};
const DEFAULT_PAGE_PREFIXES = ['ELECTRICAL', 'MAIN', 'DIRECT'];
/** Выбирает опубликованную страницу, отдавая приоритет электросхеме текущей установки. */
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;
}
/** Собирает теги, которые надо читать по SSE, из виджетов и bindings у элементов схемы. */
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!,
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());
}
/** Группирует подписки так, чтобы один EventSource читал сразу несколько тегов одного edge/source. */
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());
}
/** Добавляет tags-параметр к пользовательскому SSE URL, если он еще не задан в настройке. */
function buildCustomSseUrl(sseUrl: string, tags: string[]): string {
const url = new URL(sseUrl, window.location.origin);
if (tags.length && !url.searchParams.has('tags')) {
url.searchParams.set('tags', tags.join(','));
}
return url.toString();
}
/** Возвращает live-значение с учетом edge, но оставляет fallback по tag для старых схем. */
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}`);
}
/** Рассчитывает размеры полотна по опубликованным координатам элементов. */
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),
};
}
function getNodeSize(node: DiagramNode) {
if (node.kind === 'decoration') {
return node.size;
}
return node.size ?? { width: 190, height: 82 };
}
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);
}
function getNodeCenter(node: DiagramNode): DiagramPoint {
const size = getNodeSize(node);
return {
x: node.position.x + size.width / 2,
y: node.position.y + size.height / 2,
};
}
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)];
}
function pointsToPolyline(points: DiagramPoint[]) {
return points.map((point) => `${point.x},${point.y}`).join(' ');
}
/** Отображает опубликованную электросхему и подставляет live-значения через SSE cloud-v3. */
export function ElectricalSchematicsPage({ edgeId }: ElectricalSchematicsPageProps) {
const [selectedPageKey, setSelectedPageKey] = useState('');
const [liveValues, setLiveValues] = useState(() => new Map<string, LiveValue>());
const [connectedSources, setConnectedSources] = useState<Set<string>>(new Set());
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 document = page.data?.document;
const bindingTags = useMemo(() => (document ? collectBindingTags(document) : []), [document]);
const liveGroups = useMemo(() => createLiveGroups(bindingTags), [bindingTags]);
const nodeMap = useMemo(() => new Map((document?.nodes ?? []).map((node) => [node.id, node])), [document?.nodes]);
const canvasBounds = useMemo(() => getCanvasBounds(document), [document]);
useEffect(() => {
setLiveValues(new Map());
setConnectedSources(new Set());
}, [selectedPage?.pageKey]);
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]);
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 || document?.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}
{document ? (
<div className="electrical-layout">
<div className="electrical-canvas-shell">
<div
className="electrical-canvas"
style={{ width: canvasBounds.width, height: canvasBounds.height }}
>
{document.background?.url ? (
<img
className={`electrical-background electrical-background--${document.background.fit ?? 'contain'}`}
src={document.background.url}
alt=""
style={{ opacity: document.background.opacity ?? 0.22 }}
/>
) : null}
<svg className="electrical-wires" width={canvasBounds.width} height={canvasBounds.height}>
{(document.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>
{document.nodes.map((node) => (
<ElectricalNode
key={node.id}
node={node}
ownerEdgeId={document.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>{document.nodes.length}</strong>
</div>
<div>
<span>Провода</span>
<strong>{document.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>
);
}
function ElectricalNode({
node,
ownerEdgeId,
liveValues,
}: {
node: DiagramNode;
ownerEdgeId: string;
liveValues: Map<string, LiveValue>;
}) {
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>
);
}
export { ElectricalSchematicsPage } from '../features/electrical-schematics/ElectricalSchematicsPage';

52
src/shared/api/http.ts Normal file
View File

@@ -0,0 +1,52 @@
export type QueryParamValue = string | number | string[] | undefined;
function joinUrl(baseUrl: string, path: string): string {
const base = baseUrl.replace(/\/$/, '');
const endpoint = path.startsWith('/') ? path : `/${path}`;
return `${base}${endpoint}`;
}
function appendQueryParams(url: string, params?: Record<string, QueryParamValue>): string {
const searchParams = new URLSearchParams();
Object.entries(params ?? {}).forEach(([key, value]) => {
if (Array.isArray(value)) {
value.forEach((item) => searchParams.append(key, item));
return;
}
if (value !== undefined && value !== '') {
searchParams.set(key, String(value));
}
});
const query = searchParams.toString();
return query ? `${url}?${query}` : url;
}
/** Собирает URL API из base, пути и query-параметров. */
export function buildApiUrl(
baseUrl: string,
path: string,
params?: Record<string, QueryParamValue>,
): string {
return appendQueryParams(joinUrl(baseUrl, path), params);
}
/** Выполняет GET-запрос и добавляет query-параметры в едином формате для всех API. */
export async function getJson<T>(
baseUrl: string,
path: string,
params?: Record<string, QueryParamValue>,
init?: RequestInit,
): Promise<T> {
const url = buildApiUrl(baseUrl, path, params);
const response = await fetch(url, init);
if (!response.ok) {
const message = await response.text();
throw new Error(message || `${response.status} ${response.statusText}`);
}
return response.json() as Promise<T>;
}

7
src/shared/config/env.ts Normal file
View File

@@ -0,0 +1,7 @@
/** Базовый путь cloud API; маршрутизация на бэкенд — на уровне реверс-прокси. */
export const cloudApiUrl = '/api';
export const diagramApiUrl = import.meta.env.VITE_DIAGRAM_API_URL as string;
export const toirLightOrigin = import.meta.env.VITE_TOIR_LIGHT_ORIGIN as string;
export const keycloakUrl = import.meta.env.VITE_KEYCLOAK_URL;
export const keycloakRealm = import.meta.env.VITE_KEYCLOAK_REALM;
export const keycloakClientId = import.meta.env.VITE_KEYCLOAK_CLIENT_ID;

View File

@@ -1,543 +1,3 @@
.panel-eyebrow,
.page-kicker {
display: inline-flex;
align-items: center;
gap: 6px;
color: var(--accent-soft);
font-size: 0.72rem;
font-weight: 700;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.icon-button,
.segmented button,
.ghost-button {
min-height: 38px;
border: 1px solid var(--line);
border-radius: var(--radius);
background: rgba(201, 122, 61, 0.08);
cursor: pointer;
}
.icon-button {
width: 38px;
display: inline-flex;
align-items: center;
justify-content: center;
}
.ghost-button {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 0 12px;
color: #cbd5e1;
}
.segmented {
display: inline-flex;
padding: 3px;
border: 1px solid rgba(148, 163, 184, 0.16);
border-radius: var(--radius);
background: rgba(2, 6, 23, 0.35);
}
.view-switch {
display: inline-flex;
flex: 0 0 auto;
padding: 3px;
border: 1px solid rgba(148, 163, 184, 0.16);
border-radius: var(--radius);
background: rgba(2, 6, 23, 0.35);
}
.segmented button {
border-color: transparent;
padding: 0 10px;
}
.view-switch button {
min-height: 36px;
padding: 0 12px;
border: 1px solid transparent;
border-radius: calc(var(--radius) - 3px);
background: transparent;
color: var(--muted);
cursor: pointer;
}
.view-switch button:hover,
.view-switch__button--active {
border-color: rgba(212, 165, 116, 0.34);
background: rgba(201, 122, 61, 0.14);
color: #f8fafc;
}
.segmented button:hover,
.icon-button:hover {
border-color: var(--line-strong);
background: rgba(201, 122, 61, 0.18);
}
.source-chip,
.status-pill,
.metric-card__state {
display: inline-flex;
align-items: center;
gap: 6px;
min-height: 28px;
padding: 0 10px;
border-radius: 999px;
font-size: 0.78rem;
}
.source-chip {
border: 1px solid var(--line);
color: #cbd5e1;
}
.status-pill--ok {
border: 1px solid rgba(34, 197, 94, 0.36);
background: rgba(34, 197, 94, 0.12);
color: #86efac;
}
.status-pill--warn {
border: 1px solid rgba(245, 158, 11, 0.36);
background: rgba(245, 158, 11, 0.12);
color: #facc15;
}
.status-pill--error {
border: 1px solid rgba(239, 68, 68, 0.36);
background: rgba(239, 68, 68, 0.12);
color: #fca5a5;
}
.status-pill--muted {
border: 1px solid rgba(148, 163, 184, 0.22);
background: rgba(148, 163, 184, 0.08);
color: #cbd5e1;
}
.search-box {
min-width: min(320px, 100%);
padding-left: 10px;
border: 1px solid rgba(148, 163, 184, 0.18);
border-radius: var(--radius);
background: rgba(15, 23, 42, 0.72);
}
.search-box input {
flex: 1;
border: 0;
background: transparent;
padding-left: 0;
}
.empty-panel {
min-height: 260px;
display: grid;
place-items: center;
color: var(--muted);
border: 1px dashed rgba(148, 163, 184, 0.2);
border-radius: var(--radius);
}
.auth-screen {
min-height: 100dvh;
display: grid;
place-items: center;
padding: 24px;
background:
radial-gradient(circle at 50% 18%, rgba(201, 122, 61, 0.16), transparent 36%),
var(--bg);
}
.auth-screen-card {
width: min(420px, 100%);
padding: 24px;
border: 1px solid var(--line);
border-radius: var(--radius);
background:
linear-gradient(180deg, rgba(255, 255, 255, 0.055), transparent 34%),
rgba(10, 13, 18, 0.88);
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.07),
0 22px 44px rgba(0, 0, 0, 0.34);
}
.auth-screen-card h1 {
margin: 0 0 10px;
font-size: 1.4rem;
}
.auth-screen-card p {
margin: 0;
color: var(--muted);
}
.auth-screen-button {
min-height: 38px;
margin-top: 18px;
padding: 0 14px;
border: 1px solid var(--line);
border-radius: var(--radius);
background: rgba(201, 122, 61, 0.12);
color: var(--text);
cursor: pointer;
}
.metric-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
gap: 12px;
}
.metric-mosaic {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(82px, 1fr));
gap: 7px;
}
.metric-tile {
position: relative;
isolation: isolate;
aspect-ratio: 1 / 0.86;
min-height: 76px;
min-width: 0;
display: grid;
align-content: space-between;
gap: 7px;
padding: 10px 9px 9px;
border: 1px solid rgba(88, 103, 121, 0.5);
border-radius: 6px;
background:
linear-gradient(180deg, rgba(255, 255, 255, 0.055), transparent 32%),
repeating-linear-gradient(135deg, rgba(255, 255, 255, 0.035) 0 1px, transparent 1px 9px),
linear-gradient(145deg, rgba(20, 27, 36, 0.96), rgba(5, 8, 13, 0.92));
cursor: pointer;
text-align: left;
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.08),
inset 0 -1px 0 rgba(0, 0, 0, 0.55),
0 8px 18px rgba(0, 0, 0, 0.18);
transition:
border-color 160ms ease,
background 160ms ease,
box-shadow 160ms ease,
transform 160ms ease;
}
.metric-tile::before {
content: "";
position: absolute;
inset: 0 auto 0 0;
z-index: -1;
width: 4px;
border-radius: 6px 0 0 6px;
background: currentColor;
box-shadow: 0 0 16px currentColor;
opacity: 0.94;
}
.metric-tile::after {
content: "";
position: absolute;
inset: 5px;
z-index: -1;
border: 1px solid rgba(255, 255, 255, 0.045);
border-radius: 4px;
pointer-events: none;
}
.metric-tile:hover,
.metric-tile--selected {
border-color: rgba(232, 201, 160, 0.58);
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.1),
inset 0 -1px 0 rgba(0, 0, 0, 0.6),
0 10px 22px rgba(0, 0, 0, 0.26);
transform: translateY(-1px);
}
.metric-tile--normal {
color: #22c55e;
}
.metric-tile--warning {
color: #f59e0b;
}
.metric-tile--critical {
color: #ef4444;
}
.metric-tile__status {
width: 10px;
height: 10px;
border: 1px solid rgba(255, 255, 255, 0.28);
border-radius: 999px;
background: currentColor;
box-shadow:
0 0 0 3px color-mix(in srgb, currentColor 13%, transparent),
0 0 16px currentColor;
}
.metric-tile__tag,
.metric-tile strong {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.metric-tile__tag {
color: #cbd5e1;
font-family: "Segoe UI", Inter, system-ui, sans-serif;
font-size: 0.68rem;
font-weight: 700;
letter-spacing: 0.02em;
}
.metric-tile strong {
color: #f8fafc;
font-size: 0.88rem;
font-variant-numeric: tabular-nums;
line-height: 1;
}
.metric-card {
position: relative;
overflow: hidden;
min-height: 184px;
text-align: left;
padding: 16px 15px 15px 17px;
border: 1px solid rgba(88, 103, 121, 0.52);
border-radius: 8px;
background:
linear-gradient(180deg, rgba(255, 255, 255, 0.06), transparent 30%),
repeating-linear-gradient(135deg, rgba(255, 255, 255, 0.025) 0 1px, transparent 1px 11px),
linear-gradient(145deg, rgba(18, 25, 34, 0.95), rgba(5, 8, 13, 0.92));
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.08),
inset 0 -1px 0 rgba(0, 0, 0, 0.52),
0 14px 28px rgba(0, 0, 0, 0.2);
cursor: pointer;
transition:
border-color 160ms ease,
background 160ms ease,
box-shadow 160ms ease,
transform 160ms ease;
}
.metric-card::before {
content: "";
position: absolute;
inset: 0 auto 0 0;
width: 5px;
background: currentColor;
box-shadow: 0 0 18px currentColor;
}
.metric-card::after {
content: "";
position: absolute;
inset: 7px;
border: 1px solid rgba(255, 255, 255, 0.045);
border-radius: 5px;
pointer-events: none;
}
.metric-card:hover,
.metric-card--selected {
border-color: rgba(232, 201, 160, 0.58);
background:
linear-gradient(180deg, rgba(255, 255, 255, 0.07), transparent 30%),
repeating-linear-gradient(135deg, rgba(255, 255, 255, 0.032) 0 1px, transparent 1px 11px),
linear-gradient(145deg, rgba(27, 35, 46, 0.98), rgba(11, 14, 20, 0.94));
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.1),
inset 0 -1px 0 rgba(0, 0, 0, 0.58),
0 18px 32px rgba(0, 0, 0, 0.28);
transform: translateY(-1px);
}
.metric-card--normal {
color: #22c55e;
}
.metric-card--normal .metric-card__signal {
color: #86efac;
border-color: rgba(34, 197, 94, 0.24);
background: rgba(34, 197, 94, 0.08);
}
.metric-card--warning {
color: #f59e0b;
}
.metric-card--warning .metric-card__signal {
color: #facc15;
border-color: rgba(245, 158, 11, 0.28);
background: rgba(245, 158, 11, 0.08);
}
.metric-card--critical {
color: #ef4444;
}
.metric-card--critical .metric-card__signal {
color: #fca5a5;
border-color: rgba(239, 68, 68, 0.3);
background: rgba(239, 68, 68, 0.1);
}
.metric-card__header {
display: grid;
grid-template-columns: auto minmax(0, 1fr) auto;
align-items: start;
gap: 9px;
}
.metric-card__footer {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 10px;
}
.metric-card__signal {
width: 30px;
height: 30px;
display: inline-flex;
align-items: center;
justify-content: center;
border: 1px solid rgba(212, 165, 116, 0.24);
border-radius: 6px;
color: var(--accent-soft);
background:
repeating-linear-gradient(135deg, rgba(255, 255, 255, 0.04) 0 1px, transparent 1px 7px),
rgba(2, 6, 23, 0.42);
}
.metric-card__tag {
min-width: 0;
color: #e5e7eb;
font-size: 0.86rem;
font-weight: 750;
letter-spacing: 0.025em;
}
.metric-card__tag span,
.metric-card__tag small {
display: block;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.metric-card__tag small {
margin-top: 3px;
color: var(--muted);
font-size: 0.68rem;
font-weight: 600;
letter-spacing: 0;
}
.metric-card__state {
flex: 0 0 auto;
padding: 0 8px;
}
.metric-card__corner {
display: inline-flex;
align-items: flex-end;
flex-direction: column;
gap: 6px;
}
.metric-card__age {
display: inline-flex;
align-items: center;
gap: 5px;
color: #9aa8ba;
font-size: 0.73rem;
font-variant-numeric: tabular-nums;
}
.metric-card__state.is-normal {
border-color: rgba(34, 197, 94, 0.24);
background: rgba(34, 197, 94, 0.1);
color: #86efac;
}
.metric-card__state.is-warning {
border-color: rgba(245, 158, 11, 0.28);
background: rgba(245, 158, 11, 0.1);
color: #facc15;
}
.metric-card__state.is-critical {
border-color: rgba(239, 68, 68, 0.3);
background: rgba(239, 68, 68, 0.12);
color: #fca5a5;
}
.metric-card__value {
margin: 22px 0 16px;
overflow: hidden;
font-size: clamp(1.85rem, 4vw, 2.7rem);
font-variant-numeric: tabular-nums;
font-weight: 760;
line-height: 1;
color: #f8fafc;
text-overflow: ellipsis;
white-space: nowrap;
text-shadow: 0 0 18px color-mix(in srgb, currentColor 18%, transparent);
}
.metric-card__footer {
margin-top: 18px;
padding-top: 12px;
border-top: 1px solid rgba(148, 163, 184, 0.12);
color: var(--muted);
font-size: 0.78rem;
}
.metric-card__footer span {
display: inline-flex;
align-items: center;
gap: 6px;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.metric-card__action {
flex: 0 0 auto;
color: var(--accent-soft);
font-weight: 700;
}
@media (max-width: 680px) {
.search-box {
width: 100%;
}
.segmented {
width: 100%;
overflow-x: auto;
}
.view-switch {
width: 100%;
}
.view-switch button {
flex: 1;
}
}
@import './components/controls.css';
@import './components/auth.css';
@import './components/metrics.css';

View File

@@ -0,0 +1,43 @@
.auth-screen {
min-height: 100dvh;
display: grid;
place-items: center;
padding: 24px;
background:
radial-gradient(circle at 50% 18%, rgba(201, 122, 61, 0.16), transparent 36%),
var(--bg);
}
.auth-screen-card {
width: min(420px, 100%);
padding: 24px;
border: 1px solid var(--line);
border-radius: var(--radius);
background:
linear-gradient(180deg, rgba(255, 255, 255, 0.055), transparent 34%),
rgba(10, 13, 18, 0.88);
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.07),
0 22px 44px rgba(0, 0, 0, 0.34);
}
.auth-screen-card h1 {
margin: 0 0 10px;
font-size: 1.4rem;
}
.auth-screen-card p {
margin: 0;
color: var(--muted);
}
.auth-screen-button {
min-height: 38px;
margin-top: 18px;
padding: 0 14px;
border: 1px solid var(--line);
border-radius: var(--radius);
background: rgba(201, 122, 61, 0.12);
color: var(--text);
cursor: pointer;
}

View File

@@ -0,0 +1,158 @@
.panel-eyebrow,
.page-kicker {
display: inline-flex;
align-items: center;
gap: 6px;
color: var(--accent-soft);
font-size: 0.72rem;
font-weight: 700;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.icon-button,
.segmented button,
.ghost-button {
min-height: 38px;
border: 1px solid var(--line);
border-radius: var(--radius);
background: rgba(201, 122, 61, 0.08);
cursor: pointer;
}
.icon-button {
width: 38px;
display: inline-flex;
align-items: center;
justify-content: center;
}
.ghost-button {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 0 12px;
color: #cbd5e1;
}
.segmented,
.view-switch {
display: inline-flex;
flex: 0 0 auto;
padding: 3px;
border: 1px solid rgba(148, 163, 184, 0.16);
border-radius: var(--radius);
background: rgba(2, 6, 23, 0.35);
}
.segmented button {
border-color: transparent;
padding: 0 10px;
}
.view-switch button {
min-height: 36px;
padding: 0 12px;
border: 1px solid transparent;
border-radius: calc(var(--radius) - 3px);
background: transparent;
color: var(--muted);
cursor: pointer;
}
.view-switch button:hover,
.view-switch__button--active {
border-color: rgba(212, 165, 116, 0.34);
background: rgba(201, 122, 61, 0.14);
color: #f8fafc;
}
.segmented button:hover,
.icon-button:hover {
border-color: var(--line-strong);
background: rgba(201, 122, 61, 0.18);
}
.source-chip,
.status-pill,
.metric-card__state {
display: inline-flex;
align-items: center;
gap: 6px;
min-height: 28px;
padding: 0 10px;
border-radius: 999px;
font-size: 0.78rem;
}
.source-chip {
border: 1px solid var(--line);
color: #cbd5e1;
}
.status-pill--ok {
border: 1px solid rgba(34, 197, 94, 0.36);
background: rgba(34, 197, 94, 0.12);
color: #86efac;
}
.status-pill--warn {
border: 1px solid rgba(245, 158, 11, 0.36);
background: rgba(245, 158, 11, 0.12);
color: #facc15;
}
.status-pill--error {
border: 1px solid rgba(239, 68, 68, 0.36);
background: rgba(239, 68, 68, 0.12);
color: #fca5a5;
}
.status-pill--muted {
border: 1px solid rgba(148, 163, 184, 0.22);
background: rgba(148, 163, 184, 0.08);
color: #cbd5e1;
}
.search-box {
min-width: min(320px, 100%);
padding-left: 10px;
border: 1px solid rgba(148, 163, 184, 0.18);
border-radius: var(--radius);
background: rgba(15, 23, 42, 0.72);
}
.search-box input {
flex: 1;
border: 0;
background: transparent;
padding-left: 0;
}
.empty-panel {
min-height: 260px;
display: grid;
place-items: center;
color: var(--muted);
border: 1px dashed rgba(148, 163, 184, 0.2);
border-radius: var(--radius);
}
@media (max-width: 680px) {
.search-box {
width: 100%;
}
.segmented {
width: 100%;
overflow-x: auto;
}
.view-switch {
width: 100%;
}
.view-switch button {
flex: 1;
}
}

View File

@@ -0,0 +1,371 @@
.metric-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
gap: 12px;
}
.metric-widgets-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
gap: 10px;
}
.metric-widget {
min-width: 0;
height: 100%;
display: flex;
flex-direction: column;
gap: 10px;
padding: 12px;
border: 1px solid rgba(88, 103, 121, 0.42);
border-radius: 8px;
background:
linear-gradient(180deg, rgba(255, 255, 255, 0.03), transparent 28%),
linear-gradient(145deg, rgba(6, 9, 14, 0.98), rgba(2, 4, 8, 0.96));
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.05),
0 6px 14px rgba(0, 0, 0, 0.28);
}
.metric-widget__tag {
flex: 0 0 auto;
min-width: 0;
color: #cbd5e1;
font-size: 0.74rem;
font-weight: 600;
line-height: 1.35;
white-space: normal;
overflow-wrap: anywhere;
word-break: break-word;
}
.metric-widget__value {
margin-top: auto;
align-self: flex-end;
min-width: 0;
color: #f8fafc;
font-size: 1.1rem;
font-weight: 700;
font-variant-numeric: tabular-nums;
line-height: 1.2;
text-align: right;
}
.metric-mosaic {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(82px, 1fr));
gap: 7px;
}
.metric-tile {
position: relative;
isolation: isolate;
aspect-ratio: 1 / 0.86;
min-height: 76px;
min-width: 0;
display: grid;
align-content: space-between;
gap: 7px;
padding: 10px 9px 9px;
border: 1px solid rgba(88, 103, 121, 0.5);
border-radius: 6px;
background:
linear-gradient(180deg, rgba(255, 255, 255, 0.055), transparent 32%),
repeating-linear-gradient(135deg, rgba(255, 255, 255, 0.035) 0 1px, transparent 1px 9px),
linear-gradient(145deg, rgba(20, 27, 36, 0.96), rgba(5, 8, 13, 0.92));
cursor: pointer;
text-align: left;
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.08),
inset 0 -1px 0 rgba(0, 0, 0, 0.55),
0 8px 18px rgba(0, 0, 0, 0.18);
transition:
border-color 160ms ease,
background 160ms ease,
box-shadow 160ms ease,
transform 160ms ease;
}
.metric-tile::before {
content: "";
position: absolute;
inset: 0 auto 0 0;
z-index: -1;
width: 4px;
border-radius: 6px 0 0 6px;
background: currentColor;
box-shadow: 0 0 16px currentColor;
opacity: 0.94;
}
.metric-tile::after {
content: "";
position: absolute;
inset: 5px;
z-index: -1;
border: 1px solid rgba(255, 255, 255, 0.045);
border-radius: 4px;
pointer-events: none;
}
.metric-tile:hover,
.metric-tile--selected {
border-color: rgba(232, 201, 160, 0.58);
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.1),
inset 0 -1px 0 rgba(0, 0, 0, 0.6),
0 10px 22px rgba(0, 0, 0, 0.26);
transform: translateY(-1px);
}
.metric-tile--normal,
.metric-card--normal {
color: #22c55e;
}
.metric-tile--warning,
.metric-card--warning {
color: #f59e0b;
}
.metric-tile--critical,
.metric-card--critical {
color: #ef4444;
}
.metric-tile__status {
width: 10px;
height: 10px;
border: 1px solid rgba(255, 255, 255, 0.28);
border-radius: 999px;
background: currentColor;
box-shadow:
0 0 0 3px color-mix(in srgb, currentColor 13%, transparent),
0 0 16px currentColor;
}
.metric-tile__tag,
.metric-tile strong {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.metric-tile__tag {
color: #cbd5e1;
font-family: "Segoe UI", Inter, system-ui, sans-serif;
font-size: 0.68rem;
font-weight: 700;
letter-spacing: 0.02em;
}
.metric-tile strong {
color: #f8fafc;
font-size: 0.88rem;
font-variant-numeric: tabular-nums;
line-height: 1;
}
.metric-card {
position: relative;
overflow: hidden;
min-height: 184px;
text-align: left;
padding: 16px 15px 15px 17px;
border: 1px solid rgba(88, 103, 121, 0.52);
border-radius: 8px;
background:
linear-gradient(180deg, rgba(255, 255, 255, 0.06), transparent 30%),
repeating-linear-gradient(135deg, rgba(255, 255, 255, 0.025) 0 1px, transparent 1px 11px),
linear-gradient(145deg, rgba(18, 25, 34, 0.95), rgba(5, 8, 13, 0.92));
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.08),
inset 0 -1px 0 rgba(0, 0, 0, 0.52),
0 14px 28px rgba(0, 0, 0, 0.2);
cursor: pointer;
transition:
border-color 160ms ease,
background 160ms ease,
box-shadow 160ms ease,
transform 160ms ease;
}
.metric-card::before {
content: "";
position: absolute;
inset: 0 auto 0 0;
width: 5px;
background: currentColor;
box-shadow: 0 0 18px currentColor;
}
.metric-card::after {
content: "";
position: absolute;
inset: 7px;
border: 1px solid rgba(255, 255, 255, 0.045);
border-radius: 5px;
pointer-events: none;
}
.metric-card:hover,
.metric-card--selected {
border-color: rgba(232, 201, 160, 0.58);
background:
linear-gradient(180deg, rgba(255, 255, 255, 0.07), transparent 30%),
repeating-linear-gradient(135deg, rgba(255, 255, 255, 0.032) 0 1px, transparent 1px 11px),
linear-gradient(145deg, rgba(27, 35, 46, 0.98), rgba(11, 14, 20, 0.94));
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.1),
inset 0 -1px 0 rgba(0, 0, 0, 0.58),
0 18px 32px rgba(0, 0, 0, 0.28);
transform: translateY(-1px);
}
.metric-card--normal .metric-card__signal {
color: #86efac;
border-color: rgba(34, 197, 94, 0.24);
background: rgba(34, 197, 94, 0.08);
}
.metric-card--warning .metric-card__signal {
color: #facc15;
border-color: rgba(245, 158, 11, 0.28);
background: rgba(245, 158, 11, 0.08);
}
.metric-card--critical .metric-card__signal {
color: #fca5a5;
border-color: rgba(239, 68, 68, 0.3);
background: rgba(239, 68, 68, 0.1);
}
.metric-card__header {
display: grid;
grid-template-columns: auto minmax(0, 1fr) auto;
align-items: start;
gap: 9px;
}
.metric-card__footer {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 10px;
}
.metric-card__signal {
width: 30px;
height: 30px;
display: inline-flex;
align-items: center;
justify-content: center;
border: 1px solid rgba(212, 165, 116, 0.24);
border-radius: 6px;
color: var(--accent-soft);
background:
repeating-linear-gradient(135deg, rgba(255, 255, 255, 0.04) 0 1px, transparent 1px 7px),
rgba(2, 6, 23, 0.42);
}
.metric-card__tag {
min-width: 0;
color: #e5e7eb;
font-size: 0.86rem;
font-weight: 750;
letter-spacing: 0.025em;
}
.metric-card__tag span,
.metric-card__tag small {
display: block;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.metric-card__tag small {
margin-top: 3px;
color: var(--muted);
font-size: 0.68rem;
font-weight: 600;
letter-spacing: 0;
}
.metric-card__state {
flex: 0 0 auto;
padding: 0 8px;
}
.metric-card__corner {
display: inline-flex;
align-items: flex-end;
flex-direction: column;
gap: 6px;
}
.metric-card__age {
display: inline-flex;
align-items: center;
gap: 5px;
color: #9aa8ba;
font-size: 0.73rem;
font-variant-numeric: tabular-nums;
}
.metric-card__state.is-normal {
border-color: rgba(34, 197, 94, 0.24);
background: rgba(34, 197, 94, 0.1);
color: #86efac;
}
.metric-card__state.is-warning {
border-color: rgba(245, 158, 11, 0.28);
background: rgba(245, 158, 11, 0.1);
color: #facc15;
}
.metric-card__state.is-critical {
border-color: rgba(239, 68, 68, 0.3);
background: rgba(239, 68, 68, 0.12);
color: #fca5a5;
}
.metric-card__value {
margin: 22px 0 16px;
overflow: hidden;
font-size: clamp(1.85rem, 4vw, 2.7rem);
font-variant-numeric: tabular-nums;
font-weight: 760;
line-height: 1;
color: #f8fafc;
text-overflow: ellipsis;
white-space: nowrap;
text-shadow: 0 0 18px color-mix(in srgb, currentColor 18%, transparent);
}
.metric-card__footer {
margin-top: 18px;
padding-top: 12px;
border-top: 1px solid rgba(148, 163, 184, 0.12);
color: var(--muted);
font-size: 0.78rem;
}
.metric-card__footer span {
display: inline-flex;
align-items: center;
gap: 6px;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.metric-card__action {
flex: 0 0 auto;
color: var(--accent-soft);
font-weight: 700;
}

View File

@@ -1,411 +1,2 @@
.dashboard-shell {
width: min(1440px, 100%);
min-height: 100vh;
margin: 0 auto;
padding: 26px 24px 36px;
}
.dashboard-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
margin-bottom: 22px;
}
.dashboard-actions {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 12px;
flex-wrap: wrap;
}
.dashboard-search {
width: min(360px, 100%);
}
.dashboard-stats {
display: grid;
grid-template-columns: repeat(5, minmax(0, 1fr));
gap: 12px;
margin-bottom: 22px;
}
.dashboard-stat {
min-height: 112px;
padding: 16px;
border: 1px solid rgba(148, 163, 184, 0.16);
border-radius: var(--radius);
background:
linear-gradient(145deg, rgba(17, 24, 39, 0.78), rgba(2, 6, 23, 0.62)),
rgba(2, 6, 23, 0.38);
}
.dashboard-stat span {
display: block;
min-height: 34px;
color: var(--muted);
font-size: 0.78rem;
line-height: 1.35;
}
.dashboard-stat strong {
display: block;
margin-top: 12px;
font-size: 2rem;
line-height: 1;
}
.dashboard-stat--success {
border-color: rgba(34, 197, 94, 0.28);
}
.dashboard-stat--success strong {
color: #86efac;
}
.dashboard-stat--danger {
border-color: rgba(239, 68, 68, 0.28);
}
.dashboard-stat--danger strong {
color: #fca5a5;
}
.dashboard-stat--warning {
border-color: rgba(245, 158, 11, 0.3);
}
.dashboard-stat--warning strong {
color: #facc15;
}
.dashboard-stat--accent {
border-color: rgba(212, 165, 116, 0.32);
}
.dashboard-stat--accent strong {
color: var(--accent-soft);
}
.edge-card-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(360px, 1fr));
gap: 16px;
}
.edge-card {
min-height: 520px;
display: flex;
flex-direction: column;
padding: 18px;
border: 1px solid rgba(148, 163, 184, 0.18);
border-radius: 10px;
background:
radial-gradient(circle at 12% 0%, rgba(255, 255, 255, 0.09), transparent 26%),
linear-gradient(145deg, rgba(23, 30, 42, 0.92), rgba(4, 9, 16, 0.84)),
var(--panel-strong);
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.07),
0 18px 34px rgba(0, 0, 0, 0.22);
transition:
border-color 160ms ease,
transform 160ms ease,
box-shadow 160ms ease;
}
.edge-card:hover {
border-color: rgba(212, 165, 116, 0.42);
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.08),
0 24px 44px rgba(0, 0, 0, 0.28);
transform: translateY(-1px);
}
.edge-card--ok {
border-color: rgba(34, 197, 94, 0.26);
}
.edge-card--warn {
border-color: rgba(245, 158, 11, 0.3);
}
.edge-card--empty {
border-color: rgba(148, 163, 184, 0.18);
}
.edge-card__header {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
}
.edge-card__logo {
flex: 0 0 auto;
width: 64px;
height: 64px;
display: grid;
place-items: center;
border: 1px solid rgba(212, 165, 116, 0.22);
border-radius: var(--radius);
background: rgba(2, 6, 23, 0.38);
}
.edge-card__logo img {
width: 46px;
height: 52px;
object-fit: contain;
filter:
sepia(1)
saturate(1.25)
hue-rotate(342deg)
brightness(0.86)
contrast(1.1);
}
.edge-card__title {
min-width: 0;
flex: 1;
}
.edge-card__title h2 {
margin: 0;
overflow: hidden;
font-size: 1.08rem;
font-weight: 650;
line-height: 1.2;
text-overflow: ellipsis;
white-space: nowrap;
}
.edge-card__title span {
display: block;
margin-top: 5px;
overflow: hidden;
color: var(--muted);
font-size: 0.77rem;
text-overflow: ellipsis;
white-space: nowrap;
}
.edge-state {
flex: 0 0 auto;
display: inline-flex;
align-items: center;
gap: 6px;
min-height: 28px;
padding: 0 9px;
border: 1px solid rgba(148, 163, 184, 0.22);
border-radius: 999px;
font-size: 0.68rem;
font-weight: 800;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.edge-state--ok {
color: #22e27f;
}
.edge-state--warn,
.edge-state--empty {
color: #f2a23a;
}
.edge-card__meta {
margin: 18px 0 12px;
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 10px;
}
.edge-card__meta div {
min-height: 64px;
padding: 10px;
border: 1px solid rgba(148, 163, 184, 0.13);
border-radius: var(--radius);
background: rgba(2, 6, 23, 0.26);
}
.edge-card__meta div:last-child {
grid-column: 1 / -1;
min-height: 52px;
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
align-items: center;
column-gap: 12px;
}
.edge-card__meta dt {
display: flex;
align-items: center;
gap: 6px;
margin: 0;
color: var(--muted);
font-size: 0.74rem;
}
.edge-card__meta dd {
margin: 8px 0 0;
overflow: hidden;
color: #e5e7eb;
font-size: 1.02rem;
font-weight: 700;
text-overflow: ellipsis;
white-space: nowrap;
}
.edge-card__meta div:last-child dd {
margin: 0;
font-size: 0.92rem;
}
.edge-card__actions {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 8px;
margin-bottom: 14px;
}
.edge-card__actions button,
.edge-card__maintenance button {
min-width: 0;
border: 1px solid rgba(148, 163, 184, 0.16);
border-radius: var(--radius);
background: rgba(2, 6, 23, 0.24);
color: #cbd5e1;
cursor: pointer;
transition:
border-color 160ms ease,
background 160ms ease,
color 160ms ease;
}
.edge-card__actions button {
min-height: 40px;
display: flex;
align-items: center;
gap: 8px;
padding: 0 10px;
color: #b8c3d3;
font-size: 0.76rem;
text-align: left;
}
.edge-card__actions button:hover,
.edge-card__maintenance button:hover {
border-color: rgba(212, 165, 116, 0.42);
background: rgba(201, 122, 61, 0.1);
color: #f8fafc;
}
.edge-card__maintenance {
padding: 12px;
border: 1px solid rgba(148, 163, 184, 0.12);
border-radius: var(--radius);
background: rgba(2, 6, 23, 0.2);
}
.edge-card__maintenance > span {
display: block;
margin-bottom: 9px;
color: var(--muted);
font-size: 0.72rem;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.edge-card__maintenance div {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 7px;
}
.edge-card__maintenance button {
min-height: 34px;
padding: 0 8px;
font-size: 0.72rem;
}
.edge-card__details {
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
min-height: 44px;
margin-top: auto;
padding: 0 12px;
border: 1px solid rgba(212, 165, 116, 0.28);
border-radius: var(--radius);
background:
linear-gradient(135deg, rgba(201, 122, 61, 0.14), rgba(212, 165, 116, 0.06)),
rgba(201, 122, 61, 0.08);
color: #f8fafc;
cursor: pointer;
font-size: 0.76rem;
font-weight: 900;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.edge-card__details:hover {
border-color: var(--line-strong);
background: rgba(201, 122, 61, 0.16);
}
@media (max-width: 1100px) {
.dashboard-stats {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
.edge-card-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (max-width: 680px) {
.dashboard-shell {
padding: 16px;
}
.dashboard-header {
align-items: stretch;
flex-direction: column;
}
.dashboard-actions,
.dashboard-search {
width: 100%;
}
.edge-card-grid {
gap: 16px;
grid-template-columns: 1fr;
}
.edge-card {
min-height: 0;
padding: 18px;
}
.edge-card__actions,
.edge-card__maintenance div {
grid-template-columns: 1fr;
}
.dashboard-stats {
grid-template-columns: 1fr;
}
.edge-card__header {
align-items: flex-start;
}
.edge-state {
margin-left: auto;
}
}
@import './dashboard/layout.css';
@import './dashboard/edge-card.css';

View File

@@ -0,0 +1,210 @@
.edge-card-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(360px, 1fr));
gap: 16px;
}
.edge-card {
min-height: 520px;
display: flex;
flex-direction: column;
padding: 18px;
border: 1px solid rgba(148, 163, 184, 0.18);
border-radius: 10px;
background:
radial-gradient(circle at 12% 0%, rgba(255, 255, 255, 0.09), transparent 26%),
linear-gradient(145deg, rgba(23, 30, 42, 0.92), rgba(4, 9, 16, 0.84)),
var(--panel-strong);
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.07),
0 18px 34px rgba(0, 0, 0, 0.22);
transition:
border-color 160ms ease,
transform 160ms ease,
box-shadow 160ms ease;
}
.edge-card:hover {
border-color: rgba(212, 165, 116, 0.42);
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.08),
0 24px 44px rgba(0, 0, 0, 0.28);
transform: translateY(-1px);
}
.edge-card__header {
display: flex;
align-items: center;
gap: 12px;
min-width: 0;
}
.edge-card__logo {
flex: 0 0 auto;
width: 64px;
height: 64px;
display: grid;
place-items: center;
border: 1px solid rgba(212, 165, 116, 0.22);
border-radius: var(--radius);
background: rgba(2, 6, 23, 0.38);
}
.edge-card__logo img {
width: 46px;
height: 52px;
object-fit: contain;
filter:
sepia(1)
saturate(1.25)
hue-rotate(342deg)
brightness(0.86)
contrast(1.1);
}
.edge-card__title {
min-width: 0;
flex: 1;
}
.edge-card__title h2 {
margin: 0;
overflow: hidden;
font-size: 1.08rem;
font-weight: 650;
line-height: 1.2;
text-overflow: ellipsis;
white-space: nowrap;
}
.edge-card__title span {
display: block;
margin-top: 5px;
overflow: hidden;
color: var(--muted);
font-size: 0.77rem;
text-overflow: ellipsis;
white-space: nowrap;
}
.edge-card__actions {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 8px;
margin-bottom: 14px;
}
.edge-card__actions button,
.edge-card__maintenance button {
min-width: 0;
border: 1px solid rgba(148, 163, 184, 0.16);
border-radius: var(--radius);
background: rgba(2, 6, 23, 0.24);
color: #cbd5e1;
cursor: pointer;
transition:
border-color 160ms ease,
background 160ms ease,
color 160ms ease;
}
.edge-card__actions button {
min-height: 40px;
display: flex;
align-items: center;
gap: 8px;
padding: 0 10px;
color: #b8c3d3;
font-size: 0.76rem;
text-align: left;
}
.edge-card__actions button:hover,
.edge-card__maintenance button:hover {
border-color: rgba(212, 165, 116, 0.42);
background: rgba(201, 122, 61, 0.1);
color: #f8fafc;
}
.edge-card__maintenance {
padding: 12px;
border: 1px solid rgba(148, 163, 184, 0.12);
border-radius: var(--radius);
background: rgba(2, 6, 23, 0.2);
}
.edge-card__maintenance > span {
display: block;
margin-bottom: 9px;
color: var(--muted);
font-size: 0.72rem;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.edge-card__maintenance div {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 7px;
}
.edge-card__maintenance button {
min-height: 34px;
padding: 0 8px;
font-size: 0.72rem;
}
.edge-card__details {
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
min-height: 44px;
margin-top: auto;
padding: 0 12px;
border: 1px solid rgba(212, 165, 116, 0.28);
border-radius: var(--radius);
background:
linear-gradient(135deg, rgba(201, 122, 61, 0.14), rgba(212, 165, 116, 0.06)),
rgba(201, 122, 61, 0.08);
color: #f8fafc;
cursor: pointer;
font-size: 0.76rem;
font-weight: 900;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.edge-card__details:hover {
border-color: var(--line-strong);
background: rgba(201, 122, 61, 0.16);
}
@media (max-width: 1100px) {
.edge-card-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (max-width: 680px) {
.edge-card-grid {
gap: 16px;
grid-template-columns: 1fr;
}
.edge-card {
min-height: 0;
padding: 18px;
}
.edge-card__actions,
.edge-card__maintenance div {
grid-template-columns: 1fr;
}
.edge-card__header {
align-items: flex-start;
}
}

View File

@@ -0,0 +1,116 @@
.dashboard-shell {
width: min(1440px, 100%);
min-height: 100vh;
margin: 0 auto;
padding: 26px 24px 36px;
}
.dashboard-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
margin-bottom: 22px;
}
.dashboard-actions {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 12px;
flex-wrap: wrap;
}
.dashboard-search {
width: min(360px, 100%);
}
.dashboard-stats {
display: grid;
grid-template-columns: repeat(5, minmax(0, 1fr));
gap: 12px;
margin-bottom: 22px;
}
.dashboard-stat {
min-height: 112px;
padding: 16px;
border: 1px solid rgba(148, 163, 184, 0.16);
border-radius: var(--radius);
background:
linear-gradient(145deg, rgba(17, 24, 39, 0.78), rgba(2, 6, 23, 0.62)),
rgba(2, 6, 23, 0.38);
}
.dashboard-stat span {
display: block;
min-height: 34px;
color: var(--muted);
font-size: 0.78rem;
line-height: 1.35;
}
.dashboard-stat strong {
display: block;
margin-top: 12px;
font-size: 2rem;
line-height: 1;
}
.dashboard-stat--success {
border-color: rgba(34, 197, 94, 0.28);
}
.dashboard-stat--success strong {
color: #86efac;
}
.dashboard-stat--danger {
border-color: rgba(239, 68, 68, 0.28);
}
.dashboard-stat--danger strong {
color: #fca5a5;
}
.dashboard-stat--warning {
border-color: rgba(245, 158, 11, 0.3);
}
.dashboard-stat--warning strong {
color: #facc15;
}
.dashboard-stat--accent {
border-color: rgba(212, 165, 116, 0.32);
}
.dashboard-stat--accent strong {
color: var(--accent-soft);
}
@media (max-width: 1100px) {
.dashboard-stats {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
}
@media (max-width: 680px) {
.dashboard-shell {
padding: 16px;
}
.dashboard-header {
align-items: stretch;
flex-direction: column;
}
.dashboard-actions,
.dashboard-search {
width: 100%;
}
.dashboard-stats {
grid-template-columns: 1fr;
}
}

View File

@@ -1,724 +1,5 @@
.detail-overview {
display: grid;
gap: 18px;
}
.current-transport {
display: inline-flex;
align-items: center;
min-height: 24px;
margin-top: 8px;
padding: 0 9px;
border: 1px solid rgba(148, 163, 184, 0.18);
border-radius: 999px;
color: var(--muted);
font-size: 0.72rem;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.current-transport--sse {
border-color: rgba(34, 197, 94, 0.34);
background: rgba(34, 197, 94, 0.1);
color: #86efac;
}
.current-transport--polling {
border-color: rgba(245, 158, 11, 0.32);
background: rgba(245, 158, 11, 0.08);
color: #facc15;
}
.chart-section,
.tags-section {
border: 1px solid var(--line);
border-radius: var(--radius);
background:
radial-gradient(circle at 12% 8%, rgba(255, 255, 255, 0.08), transparent 38%),
linear-gradient(145deg, rgba(17, 24, 39, 0.9), rgba(2, 6, 23, 0.78));
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.06),
0 18px 36px rgba(0, 0, 0, 0.28);
}
.summary-grid {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 12px;
}
.summary-card {
min-height: 149px;
padding: 18px;
border: 1px solid var(--line);
border-radius: var(--radius);
background: rgba(10, 13, 18, 0.62);
}
.summary-card span {
display: block;
color: var(--muted);
font-size: 0.78rem;
text-transform: uppercase;
letter-spacing: 0.12em;
}
.summary-card strong {
display: block;
margin-top: 18px;
font-size: clamp(1.5rem, 3vw, 2.3rem);
line-height: 1.1;
}
.detail-action-panel {
padding: 18px;
border: 1px solid var(--line);
border-radius: var(--radius);
background: rgba(10, 13, 18, 0.58);
}
.detail-action-grid {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 10px;
margin-top: 16px;
}
.detail-action-grid button {
min-height: 92px;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
gap: 10px;
border: 1px solid rgba(148, 163, 184, 0.16);
border-radius: var(--radius);
background: rgba(2, 6, 23, 0.28);
color: #cbd5e1;
cursor: pointer;
}
.detail-action-grid button:hover {
border-color: var(--line-strong);
background: rgba(201, 122, 61, 0.12);
color: var(--text);
}
.chart-section,
.tags-section {
padding: 18px;
margin-bottom: 18px;
}
.indicator-summary {
display: grid;
grid-template-columns: repeat(5, minmax(0, 1fr));
gap: 10px;
margin-bottom: 14px;
}
.indicator-summary div {
position: relative;
overflow: hidden;
min-height: 76px;
padding: 13px;
border: 1px solid rgba(88, 103, 121, 0.46);
border-radius: 8px;
background:
linear-gradient(180deg, rgba(255, 255, 255, 0.052), transparent 34%),
repeating-linear-gradient(135deg, rgba(255, 255, 255, 0.024) 0 1px, transparent 1px 10px),
rgba(2, 6, 23, 0.34);
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.07),
inset 0 -1px 0 rgba(0, 0, 0, 0.48);
}
.indicator-summary div::before {
content: "";
position: absolute;
inset: 0 auto 0 0;
width: 3px;
background: rgba(212, 165, 116, 0.58);
}
.indicator-summary span {
display: block;
color: #9aa8ba;
font-size: 0.74rem;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.indicator-summary strong {
display: block;
margin-top: 9px;
color: #f8fafc;
font-size: 1.65rem;
font-variant-numeric: tabular-nums;
line-height: 1;
}
.chart-section--archive {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
margin-bottom: 0;
}
.equipment-section {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
margin: 0;
}
.equipment-frame-shell {
position: relative;
flex: 1;
min-height: 0;
overflow: hidden;
border: 1px solid rgba(88, 103, 121, 0.5);
border-radius: 8px;
background:
linear-gradient(180deg, rgba(255, 255, 255, 0.055), transparent 32%),
repeating-linear-gradient(135deg, rgba(255, 255, 255, 0.025) 0 1px, transparent 1px 11px),
rgba(2, 6, 23, 0.58);
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.08),
inset 0 -1px 0 rgba(0, 0, 0, 0.52);
}
.equipment-frame-loading {
position: absolute;
inset: 0;
z-index: 2;
display: grid;
place-items: center;
gap: 12px;
align-content: center;
color: #cbd5e1;
background: rgba(2, 6, 23, 0.74);
}
.equipment-frame-loading__ring {
width: 34px;
height: 34px;
border: 3px solid rgba(212, 165, 116, 0.22);
border-top-color: var(--accent-soft);
border-radius: 999px;
animation: equipmentFrameSpin 900ms linear infinite;
}
.equipment-frame {
width: 100%;
height: 100%;
border: 0;
background: #05080d;
}
.electrical-section {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
padding: 18px;
border: 1px solid var(--line);
border-radius: var(--radius);
background:
linear-gradient(180deg, rgba(255, 255, 255, 0.055), transparent 30%),
repeating-linear-gradient(135deg, rgba(255, 255, 255, 0.022) 0 1px, transparent 1px 12px),
rgba(10, 13, 18, 0.72);
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.07),
0 18px 36px rgba(0, 0, 0, 0.24);
}
.electrical-toolbar {
display: flex;
align-items: end;
justify-content: flex-end;
gap: 10px;
flex-wrap: wrap;
}
.electrical-toolbar label {
min-width: 260px;
}
.electrical-live-chip--sse {
border-color: rgba(34, 197, 94, 0.34);
background: rgba(34, 197, 94, 0.1);
color: #86efac;
}
.electrical-layout {
min-height: 0;
display: grid;
grid-template-columns: minmax(0, 1fr) 220px;
gap: 14px;
flex: 1;
}
.electrical-canvas-shell {
min-width: 0;
min-height: 0;
overflow: auto;
border: 1px solid rgba(88, 103, 121, 0.5);
border-radius: 8px;
background:
linear-gradient(rgba(255, 255, 255, 0.035) 1px, transparent 1px),
linear-gradient(90deg, rgba(255, 255, 255, 0.035) 1px, transparent 1px),
#070b12;
background-size: 28px 28px;
}
.electrical-canvas {
position: relative;
min-width: 100%;
min-height: 100%;
}
.electrical-background {
position: absolute;
inset: 0;
z-index: 0;
width: 100%;
height: 100%;
pointer-events: none;
}
.electrical-background--contain {
object-fit: contain;
}
.electrical-background--cover {
object-fit: cover;
}
.electrical-background--stretch {
object-fit: fill;
}
.electrical-wires {
position: absolute;
inset: 0;
z-index: 1;
pointer-events: none;
}
.electrical-wire {
fill: none;
stroke: #94a3b8;
stroke-width: 2;
stroke-linecap: round;
stroke-linejoin: round;
opacity: 0.9;
}
.electrical-wire--power {
stroke: #f97316;
stroke-width: 3;
}
.electrical-wire--signal {
stroke: #38bdf8;
stroke-dasharray: 8 6;
}
.electrical-wire--alert {
stroke: #ef4444;
stroke-dasharray: 5 5;
}
.electrical-wire--animated {
animation: electricalWireFlow 900ms linear infinite;
}
.electrical-node {
position: absolute;
z-index: 2;
display: grid;
grid-template-rows: auto minmax(0, 1fr) auto;
gap: 6px;
overflow: hidden;
padding: 10px;
border: 1px solid rgba(148, 163, 184, 0.34);
border-radius: 7px;
background:
linear-gradient(180deg, rgba(255, 255, 255, 0.07), transparent 32%),
rgba(15, 23, 42, 0.9);
color: #e5e7eb;
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.08),
0 12px 24px rgba(0, 0, 0, 0.28);
}
.electrical-node--decoration {
border-style: dashed;
background:
repeating-linear-gradient(135deg, rgba(255, 255, 255, 0.026) 0 1px, transparent 1px 10px),
rgba(15, 23, 42, 0.74);
}
.electrical-node--active {
border-color: rgba(34, 197, 94, 0.58);
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.08),
0 0 0 1px rgba(34, 197, 94, 0.2),
0 0 22px rgba(34, 197, 94, 0.16);
}
.electrical-node--alarm {
border-color: rgba(239, 68, 68, 0.76);
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.08),
0 0 0 1px rgba(239, 68, 68, 0.24),
0 0 26px rgba(239, 68, 68, 0.22);
}
.electrical-node__header,
.electrical-node__footer {
display: flex;
align-items: center;
gap: 6px;
min-width: 0;
}
.electrical-node__header span,
.electrical-node__footer span,
.electrical-node__text {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.electrical-node__header {
color: #f8fafc;
font-size: 0.78rem;
font-weight: 750;
}
.electrical-node__value {
align-self: center;
min-width: 0;
overflow: hidden;
color: #f8fafc;
font-size: clamp(1.2rem, 2vw, 1.9rem);
font-variant-numeric: tabular-nums;
line-height: 1;
text-overflow: ellipsis;
white-space: nowrap;
}
.electrical-node__value small {
margin-left: 6px;
color: var(--muted);
font-size: 0.72rem;
font-weight: 650;
}
.electrical-node__text {
align-self: center;
color: #cbd5e1;
font-size: 0.9rem;
}
.electrical-node__footer {
color: var(--muted);
font-size: 0.68rem;
}
.electrical-node__alarm {
margin-left: auto;
color: #fca5a5;
}
.electrical-side-panel {
display: grid;
align-content: start;
gap: 10px;
}
.electrical-side-panel div {
min-height: 82px;
padding: 12px;
border: 1px solid rgba(88, 103, 121, 0.46);
border-radius: 8px;
background: rgba(2, 6, 23, 0.32);
}
.electrical-side-panel span {
display: block;
color: var(--muted);
font-size: 0.72rem;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.electrical-side-panel strong {
display: block;
margin-top: 10px;
color: #f8fafc;
font-size: 1.18rem;
line-height: 1.2;
}
@keyframes equipmentFrameSpin {
to {
transform: rotate(360deg);
}
}
@keyframes electricalWireFlow {
to {
stroke-dashoffset: -28;
}
}
.section-header {
justify-content: space-between;
margin-bottom: 16px;
}
.indicator-controls {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 10px;
min-width: min(560px, 100%);
}
.toolbar {
margin-bottom: 14px;
}
.archive-tag-panel {
margin-bottom: 14px;
}
.archive-tag-panel__toggle {
width: 100%;
min-height: 48px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 0 14px;
border: 1px solid rgba(148, 163, 184, 0.16);
border-radius: var(--radius);
background: rgba(2, 6, 23, 0.28);
color: #cbd5e1;
cursor: pointer;
text-align: left;
}
.archive-tag-panel__toggle span {
display: flex;
align-items: center;
gap: 10px;
min-width: 0;
}
.archive-tag-panel__toggle strong {
color: var(--accent-soft);
font-size: 0.78rem;
font-weight: 700;
}
.archive-tag-panel__toggle[aria-expanded="true"] svg {
transform: rotate(180deg);
}
.tag-selector {
display: flex;
flex-direction: column;
gap: 12px;
margin-top: 10px;
padding: 14px;
border: 1px solid rgba(148, 163, 184, 0.14);
border-radius: var(--radius);
background: rgba(2, 6, 23, 0.24);
}
.tag-selector__header {
display: grid;
grid-template-columns: minmax(280px, 1fr) minmax(420px, 0.9fr);
gap: 10px;
}
.tag-selector__header span,
.tag-selector__tools button,
.selected-tags span {
color: var(--muted);
font-size: 0.76rem;
}
.tag-selector__header strong {
color: var(--accent-soft);
font-size: 0.86rem;
}
.tag-selector__tools {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 8px;
}
.tag-selector__tools button {
min-height: 34px;
border: 1px solid rgba(148, 163, 184, 0.16);
border-radius: var(--radius);
background: rgba(15, 23, 42, 0.54);
cursor: pointer;
}
.tag-selector__tools button:hover,
.tag-select-item:hover,
.tag-select-item--selected {
border-color: var(--line-strong);
background: rgba(201, 122, 61, 0.12);
}
.selected-tags {
min-height: 38px;
display: flex;
align-items: center;
gap: 6px;
flex-wrap: wrap;
}
.selected-tags span {
max-width: 100%;
overflow: hidden;
padding: 5px 8px;
border: 1px solid rgba(148, 163, 184, 0.14);
border-radius: 999px;
text-overflow: ellipsis;
white-space: nowrap;
}
.tag-select-list {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
gap: 7px;
padding-right: 2px;
}
.tag-select-item {
min-height: 42px;
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
align-items: center;
gap: 10px;
padding: 0 10px;
border: 1px solid rgba(148, 163, 184, 0.12);
border-radius: var(--radius);
background: rgba(2, 6, 23, 0.22);
color: #cbd5e1;
cursor: pointer;
text-align: left;
}
.tag-select-item__name {
min-width: 0;
}
.tag-select-item__name span,
.tag-select-item__name small {
display: block;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.tag-select-item__name span {
font-size: 0.78rem;
}
.tag-select-item__name small {
margin-top: 3px;
color: var(--muted);
font-size: 0.68rem;
}
.tag-select-item strong {
color: #e5e7eb;
font-size: 0.76rem;
}
.tag-select-item--selected span {
color: #f8fafc;
}
.archive-chart {
min-width: 0;
min-height: 0;
display: flex;
flex: 1;
flex-direction: column;
}
.chart-section--archive .toolbar {
flex: 0 0 auto;
}
@media (max-width: 1200px) {
.summary-grid,
.detail-action-grid,
.indicator-summary {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.electrical-layout {
grid-template-columns: 1fr;
}
.electrical-side-panel {
grid-template-columns: repeat(4, minmax(0, 1fr));
}
.tag-selector__header {
grid-template-columns: 1fr;
}
.indicator-controls {
min-width: 100%;
justify-content: flex-start;
}
}
@media (max-width: 680px) {
.summary-grid,
.detail-action-grid,
.indicator-summary {
grid-template-columns: 1fr;
}
.tag-selector__tools {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.indicator-controls {
flex-direction: column;
align-items: stretch;
}
.electrical-side-panel {
grid-template-columns: 1fr 1fr;
}
.electrical-toolbar {
align-items: stretch;
flex-direction: column;
}
.electrical-toolbar label {
min-width: 0;
}
}
@import './detail/base.css';
@import './detail/overview.css';
@import './detail/indicators.css';
@import './detail/archive.css';
@import './detail/electrical.css';

View File

@@ -0,0 +1,326 @@
.chart-section--archive {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
margin-bottom: 0;
}
.toolbar {
margin-bottom: 14px;
}
.archive-tag-panel {
margin-bottom: 14px;
}
.archive-tag-panel__toggle {
width: 100%;
min-height: 48px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 0 14px;
border: 1px solid rgba(148, 163, 184, 0.16);
border-radius: var(--radius);
background: rgba(2, 6, 23, 0.28);
color: #cbd5e1;
cursor: pointer;
text-align: left;
}
.archive-tag-panel__toggle span {
display: flex;
align-items: center;
gap: 10px;
min-width: 0;
}
.archive-tag-panel__toggle strong {
color: var(--accent-soft);
font-size: 0.78rem;
font-weight: 700;
}
.archive-tag-panel__toggle[aria-expanded="true"] svg {
transform: rotate(180deg);
}
.tag-selector {
display: flex;
flex-direction: column;
gap: 12px;
margin-top: 10px;
padding: 14px;
border: 1px solid rgba(148, 163, 184, 0.14);
border-radius: var(--radius);
background: rgba(2, 6, 23, 0.24);
}
.tag-selector__header {
display: grid;
grid-template-columns: minmax(280px, 1fr) minmax(420px, 0.9fr);
gap: 10px;
}
.tag-selector__header span,
.tag-selector__tools button,
.selected-tags span {
color: var(--muted);
font-size: 0.76rem;
}
.tag-selector__header strong {
color: var(--accent-soft);
font-size: 0.86rem;
}
.tag-selector__tools {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 8px;
}
.tag-selector__tools button {
min-height: 34px;
border: 1px solid rgba(148, 163, 184, 0.16);
border-radius: var(--radius);
background: rgba(15, 23, 42, 0.54);
cursor: pointer;
}
.tag-selector__tools button:hover,
.tag-select-item:hover {
border-color: var(--line-strong);
background: rgba(201, 122, 61, 0.12);
}
.tag-select-item--selected {
border-color: rgba(232, 201, 160, 0.72);
background:
linear-gradient(135deg, rgba(201, 122, 61, 0.22), rgba(212, 165, 116, 0.08)),
rgba(15, 23, 42, 0.62);
box-shadow:
inset 3px 0 0 var(--accent-soft),
0 0 0 1px rgba(201, 122, 61, 0.12);
}
.selected-tags {
min-height: 38px;
display: flex;
align-items: center;
gap: 6px;
flex-wrap: wrap;
}
.selected-tags span {
max-width: 100%;
overflow: hidden;
padding: 5px 8px;
border: 1px solid rgba(148, 163, 184, 0.14);
border-radius: 999px;
text-overflow: ellipsis;
white-space: nowrap;
}
.tag-select-list {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
gap: 7px;
padding-right: 2px;
}
.tag-select-item {
min-height: 42px;
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
align-items: center;
gap: 10px;
padding: 0 10px;
border: 1px solid rgba(148, 163, 184, 0.12);
border-radius: var(--radius);
background: rgba(2, 6, 23, 0.22);
color: #cbd5e1;
cursor: pointer;
text-align: left;
}
.tag-select-item__name {
min-width: 0;
}
.tag-select-item__name span,
.tag-select-item__name small {
display: block;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.tag-select-item__name span {
font-size: 0.78rem;
}
.tag-select-item__name small {
margin-top: 3px;
color: var(--muted);
font-size: 0.68rem;
}
.tag-select-item strong {
color: #e5e7eb;
font-size: 0.76rem;
}
.tag-select-item__side {
display: inline-flex;
align-items: center;
justify-content: flex-end;
gap: 7px;
min-width: 0;
}
.tag-select-item__side svg {
flex: 0 0 auto;
color: var(--accent-soft);
}
.tag-select-item--selected .tag-select-item__name span,
.tag-select-item--selected .tag-select-item__side strong {
color: #f8fafc;
}
.tag-select-item--selected .tag-select-item__name small {
color: #e8c9a0;
}
.archive-chart {
min-width: 0;
min-height: 0;
display: flex;
flex: 1;
flex-direction: column;
}
.chart-section--archive .toolbar {
flex: 0 0 auto;
}
.archive-date-range {
display: inline-flex;
align-items: center;
gap: 8px;
color: var(--muted);
font-size: 0.84rem;
}
.archive-date-input {
color-scheme: dark;
min-height: 36px;
border: 0;
background: transparent;
color: var(--text);
font: inherit;
padding: 0;
cursor: text;
outline: none;
}
.archive-date-input--date {
width: 118px;
}
.archive-date-input--time {
width: 55px;
}
.archive-date-field {
min-height: 38px;
display: inline-flex;
align-items: center;
gap: 8px;
padding: 0 10px;
border: 1px solid rgba(148, 163, 184, 0.2);
border-radius: var(--radius);
background: rgba(15, 23, 42, 0.72);
cursor: pointer;
}
.archive-date-picker-button {
width: 28px;
height: 28px;
display: inline-flex;
flex: 0 0 auto;
align-items: center;
justify-content: center;
border: 1px solid rgba(201, 122, 61, 0.34);
border-radius: calc(var(--radius) - 4px);
background: rgba(201, 122, 61, 0.14);
color: var(--accent-soft);
cursor: pointer;
}
.archive-date-picker-button:hover,
.archive-date-picker-button:focus-visible {
border-color: rgba(201, 122, 61, 0.62);
background: rgba(201, 122, 61, 0.24);
color: #fed7aa;
outline: none;
}
.archive-date-field:hover,
.archive-date-field:focus-within {
border-color: var(--line-strong);
background: rgba(201, 122, 61, 0.14);
}
.archive-date-picker-button svg {
flex: 0 0 auto;
color: currentColor;
}
.archive-date-input::-webkit-calendar-picker-indicator {
opacity: 0;
width: 0;
margin: 0;
padding: 0;
}
.archive-date-input::-webkit-datetime-edit,
.archive-date-input::-webkit-datetime-edit-fields-wrapper,
.archive-date-input::-webkit-datetime-edit-text,
.archive-date-input::-webkit-datetime-edit-day-field,
.archive-date-input::-webkit-datetime-edit-month-field,
.archive-date-input::-webkit-datetime-edit-year-field,
.archive-date-input::-webkit-datetime-edit-hour-field,
.archive-date-input::-webkit-datetime-edit-minute-field {
color: var(--text);
}
@media (max-width: 1200px) {
.tag-selector__header {
grid-template-columns: 1fr;
}
}
@media (max-width: 680px) {
.tag-selector__tools {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.archive-date-range {
width: 100%;
}
.archive-date-field {
flex: 1;
}
.archive-date-input--date,
.archive-date-input--time {
width: 100%;
min-width: 0;
}
}

View File

@@ -0,0 +1,45 @@
.current-transport {
display: inline-flex;
align-items: center;
min-height: 24px;
margin-top: 8px;
padding: 0 9px;
border: 1px solid rgba(148, 163, 184, 0.18);
border-radius: 999px;
color: var(--muted);
font-size: 0.72rem;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.current-transport--sse {
border-color: rgba(34, 197, 94, 0.34);
background: rgba(34, 197, 94, 0.1);
color: #86efac;
}
.current-transport--polling {
border-color: rgba(245, 158, 11, 0.32);
background: rgba(245, 158, 11, 0.08);
color: #facc15;
}
.chart-section,
.tags-section {
padding: 18px;
margin-bottom: 18px;
border: 1px solid var(--line);
border-radius: var(--radius);
background:
radial-gradient(circle at 12% 8%, rgba(255, 255, 255, 0.08), transparent 38%),
linear-gradient(145deg, rgba(17, 24, 39, 0.9), rgba(2, 6, 23, 0.78));
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.06),
0 18px 36px rgba(0, 0, 0, 0.28);
}
.section-header {
justify-content: space-between;
margin-bottom: 16px;
}

View File

@@ -0,0 +1,278 @@
.electrical-section {
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
padding: 18px;
border: 1px solid var(--line);
border-radius: var(--radius);
background:
linear-gradient(180deg, rgba(255, 255, 255, 0.055), transparent 30%),
repeating-linear-gradient(135deg, rgba(255, 255, 255, 0.022) 0 1px, transparent 1px 12px),
rgba(10, 13, 18, 0.72);
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.07),
0 18px 36px rgba(0, 0, 0, 0.24);
}
.electrical-toolbar {
display: flex;
align-items: end;
justify-content: flex-end;
gap: 10px;
flex-wrap: wrap;
}
.electrical-toolbar label {
min-width: 260px;
}
.electrical-live-chip--sse {
border-color: rgba(34, 197, 94, 0.34);
background: rgba(34, 197, 94, 0.1);
color: #86efac;
}
.electrical-layout {
min-height: 0;
display: grid;
grid-template-columns: minmax(0, 1fr) 220px;
gap: 14px;
flex: 1;
}
.electrical-canvas-shell {
min-width: 0;
min-height: 0;
overflow: auto;
border: 1px solid rgba(88, 103, 121, 0.5);
border-radius: 8px;
background:
linear-gradient(rgba(255, 255, 255, 0.035) 1px, transparent 1px),
linear-gradient(90deg, rgba(255, 255, 255, 0.035) 1px, transparent 1px),
#070b12;
background-size: 28px 28px;
}
.electrical-canvas {
position: relative;
min-width: 100%;
min-height: 100%;
}
.electrical-background {
position: absolute;
inset: 0;
z-index: 0;
width: 100%;
height: 100%;
pointer-events: none;
}
.electrical-background--contain {
object-fit: contain;
}
.electrical-background--cover {
object-fit: cover;
}
.electrical-background--stretch {
object-fit: fill;
}
.electrical-wires {
position: absolute;
inset: 0;
z-index: 1;
pointer-events: none;
}
.electrical-wire {
fill: none;
stroke: #94a3b8;
stroke-width: 2;
stroke-linecap: round;
stroke-linejoin: round;
opacity: 0.9;
}
.electrical-wire--power {
stroke: #f97316;
stroke-width: 3;
}
.electrical-wire--signal {
stroke: #38bdf8;
stroke-dasharray: 8 6;
}
.electrical-wire--alert {
stroke: #ef4444;
stroke-dasharray: 5 5;
}
.electrical-wire--animated {
animation: electricalWireFlow 900ms linear infinite;
}
.electrical-node {
position: absolute;
z-index: 2;
display: grid;
grid-template-rows: auto minmax(0, 1fr) auto;
gap: 6px;
overflow: hidden;
padding: 10px;
border: 1px solid rgba(148, 163, 184, 0.34);
border-radius: 7px;
background:
linear-gradient(180deg, rgba(255, 255, 255, 0.07), transparent 32%),
rgba(15, 23, 42, 0.9);
color: #e5e7eb;
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.08),
0 12px 24px rgba(0, 0, 0, 0.28);
}
.electrical-node--decoration {
border-style: dashed;
background:
repeating-linear-gradient(135deg, rgba(255, 255, 255, 0.026) 0 1px, transparent 1px 10px),
rgba(15, 23, 42, 0.74);
}
.electrical-node--active {
border-color: rgba(34, 197, 94, 0.58);
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.08),
0 0 0 1px rgba(34, 197, 94, 0.2),
0 0 22px rgba(34, 197, 94, 0.16);
}
.electrical-node--alarm {
border-color: rgba(239, 68, 68, 0.76);
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.08),
0 0 0 1px rgba(239, 68, 68, 0.24),
0 0 26px rgba(239, 68, 68, 0.22);
}
.electrical-node__header,
.electrical-node__footer {
display: flex;
align-items: center;
gap: 6px;
min-width: 0;
}
.electrical-node__header span,
.electrical-node__footer span,
.electrical-node__text {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.electrical-node__header {
color: #f8fafc;
font-size: 0.78rem;
font-weight: 750;
}
.electrical-node__value {
align-self: center;
min-width: 0;
overflow: hidden;
color: #f8fafc;
font-size: clamp(1.2rem, 2vw, 1.9rem);
font-variant-numeric: tabular-nums;
line-height: 1;
text-overflow: ellipsis;
white-space: nowrap;
}
.electrical-node__value small {
margin-left: 6px;
color: var(--muted);
font-size: 0.72rem;
font-weight: 650;
}
.electrical-node__text {
align-self: center;
color: #cbd5e1;
font-size: 0.9rem;
}
.electrical-node__footer {
color: var(--muted);
font-size: 0.68rem;
}
.electrical-node__alarm {
margin-left: auto;
color: #fca5a5;
}
.electrical-side-panel {
display: grid;
align-content: start;
gap: 10px;
}
.electrical-side-panel div {
min-height: 82px;
padding: 12px;
border: 1px solid rgba(88, 103, 121, 0.46);
border-radius: 8px;
background: rgba(2, 6, 23, 0.32);
}
.electrical-side-panel span {
display: block;
color: var(--muted);
font-size: 0.72rem;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.electrical-side-panel strong {
display: block;
margin-top: 10px;
color: #f8fafc;
font-size: 1.18rem;
line-height: 1.2;
}
@keyframes electricalWireFlow {
to {
stroke-dashoffset: -28;
}
}
@media (max-width: 1200px) {
.electrical-layout {
grid-template-columns: 1fr;
}
.electrical-side-panel {
grid-template-columns: repeat(4, minmax(0, 1fr));
}
}
@media (max-width: 680px) {
.electrical-side-panel {
grid-template-columns: 1fr 1fr;
}
.electrical-toolbar {
align-items: stretch;
flex-direction: column;
}
.electrical-toolbar label {
min-width: 0;
}
}

View File

@@ -0,0 +1,78 @@
.indicator-controls {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 10px;
min-width: min(560px, 100%);
}
.indicator-summary {
display: grid;
grid-template-columns: repeat(5, minmax(0, 1fr));
gap: 10px;
margin-bottom: 14px;
}
.indicator-summary div {
position: relative;
overflow: hidden;
min-height: 76px;
padding: 13px;
border: 1px solid rgba(88, 103, 121, 0.46);
border-radius: 8px;
background:
linear-gradient(180deg, rgba(255, 255, 255, 0.052), transparent 34%),
repeating-linear-gradient(135deg, rgba(255, 255, 255, 0.024) 0 1px, transparent 1px 10px),
rgba(2, 6, 23, 0.34);
box-shadow:
inset 0 1px 0 rgba(255, 255, 255, 0.07),
inset 0 -1px 0 rgba(0, 0, 0, 0.48);
}
.indicator-summary div::before {
content: "";
position: absolute;
inset: 0 auto 0 0;
width: 3px;
background: rgba(212, 165, 116, 0.58);
}
.indicator-summary span {
display: block;
color: #9aa8ba;
font-size: 0.74rem;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.indicator-summary strong {
display: block;
margin-top: 9px;
color: #f8fafc;
font-size: 1.65rem;
font-variant-numeric: tabular-nums;
line-height: 1;
}
@media (max-width: 1200px) {
.indicator-summary {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.indicator-controls {
min-width: 100%;
justify-content: flex-start;
}
}
@media (max-width: 680px) {
.indicator-summary {
grid-template-columns: 1fr;
}
.indicator-controls {
flex-direction: column;
align-items: stretch;
}
}

View File

@@ -0,0 +1,81 @@
.detail-overview {
display: grid;
gap: 18px;
}
.summary-grid {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 12px;
}
.summary-card {
min-height: 149px;
padding: 18px;
border: 1px solid var(--line);
border-radius: var(--radius);
background: rgba(10, 13, 18, 0.62);
}
.summary-card span {
display: block;
color: var(--muted);
font-size: 0.78rem;
text-transform: uppercase;
letter-spacing: 0.12em;
}
.summary-card strong {
display: block;
margin-top: 18px;
font-size: clamp(1.5rem, 3vw, 2.3rem);
line-height: 1.1;
}
.detail-action-panel {
padding: 18px;
border: 1px solid var(--line);
border-radius: var(--radius);
background: rgba(10, 13, 18, 0.58);
}
.detail-action-grid {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 10px;
margin-top: 16px;
}
.detail-action-grid button {
min-height: 92px;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
gap: 10px;
border: 1px solid rgba(148, 163, 184, 0.16);
border-radius: var(--radius);
background: rgba(2, 6, 23, 0.28);
color: #cbd5e1;
cursor: pointer;
}
.detail-action-grid button:hover {
border-color: var(--line-strong);
background: rgba(201, 122, 61, 0.12);
color: var(--text);
}
@media (max-width: 1200px) {
.summary-grid,
.detail-action-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (max-width: 680px) {
.summary-grid,
.detail-action-grid {
grid-template-columns: 1fr;
}
}

View File

@@ -146,23 +146,12 @@
}
.workspace--archive,
.workspace--equipment,
.workspace--electrical {
display: flex;
flex-direction: column;
overflow: auto;
}
.workspace--equipment {
overflow: hidden;
padding: 14px;
}
.workspace--equipment .topbar {
flex: 0 0 auto;
margin-bottom: 12px;
}
.topbar {
display: flex;
justify-content: space-between;

View File

@@ -0,0 +1,62 @@
export type HistoryAxisLabelFormat =
| 'time-seconds'
| 'time-minutes'
| 'hour-zero'
| 'day-hour'
| 'weekday-day'
| 'day-month'
| 'day-month-name'
| 'month-name'
| 'month-year'
| 'quarter-year'
| 'year';
export type HistoryGranularity = {
granulate: string;
tickIntervalMs: number;
labelFormat: HistoryAxisLabelFormat;
};
const SECOND = 1000;
const MINUTE = 60 * SECOND;
const HOUR = 60 * MINUTE;
const DAY = 24 * HOUR;
const WEEK = 7 * DAY;
const MONTH = 30 * DAY;
const YEAR = 365 * DAY;
type Rule = {
maxMs: number;
granulate: string;
tickIntervalMs: number;
labelFormat: HistoryAxisLabelFormat;
};
const RULES: Rule[] = [
{ maxMs: 15 * MINUTE, granulate: '1 second', tickIntervalMs: MINUTE, labelFormat: 'time-seconds' },
{ maxMs: HOUR, granulate: '5 seconds', tickIntervalMs: 5 * MINUTE, labelFormat: 'time-minutes' },
{ maxMs: 3 * HOUR, granulate: '10 seconds', tickIntervalMs: 15 * MINUTE, labelFormat: 'time-minutes' },
{ maxMs: 6 * HOUR, granulate: '30 seconds', tickIntervalMs: 30 * MINUTE, labelFormat: 'time-minutes' },
{ maxMs: 12 * HOUR, granulate: '1 minute', tickIntervalMs: HOUR, labelFormat: 'hour-zero' },
{ maxMs: 3 * DAY, granulate: '5 minutes', tickIntervalMs: 6 * HOUR, labelFormat: 'day-hour' },
{ maxMs: 7 * DAY, granulate: '10 minutes', tickIntervalMs: DAY, labelFormat: 'weekday-day' },
{ maxMs: 10 * DAY, granulate: '15 minutes', tickIntervalMs: DAY, labelFormat: 'day-month' },
{ maxMs: 3 * WEEK, granulate: '30 minutes', tickIntervalMs: 2 * DAY, labelFormat: 'day-month' },
{ maxMs: 6 * WEEK, granulate: '1 hour', tickIntervalMs: WEEK, labelFormat: 'day-month' },
{ maxMs: 4 * MONTH, granulate: '3 hours', tickIntervalMs: 2 * WEEK, labelFormat: 'day-month-name' },
{ maxMs: 8 * MONTH, granulate: '6 hours', tickIntervalMs: MONTH, labelFormat: 'month-name' },
{ maxMs: 1.5 * YEAR, granulate: '12 hours', tickIntervalMs: MONTH, labelFormat: 'month-year' },
{ maxMs: 3 * YEAR, granulate: '1 day', tickIntervalMs: 3 * MONTH, labelFormat: 'quarter-year' },
];
/** Подбирает шаг данных и подписи X по длительности выбранного диапазона. */
export function getHistoryGranularity(from: string, to: string): HistoryGranularity {
const spanMs = new Date(to).getTime() - new Date(from).getTime();
return (
RULES.find((rule) => spanMs <= rule.maxMs) ?? {
granulate: '1 week',
tickIntervalMs: YEAR,
labelFormat: 'year',
}
);
}

View File

@@ -1,4 +1,4 @@
import type { CurrentItem } from '../api/cloud';
import type { CurrentItem } from '../entities/current/types';
export type MetricStatus = 'normal' | 'warning' | 'critical';
@@ -8,17 +8,19 @@ export type MetricStatusInfo = {
ageSeconds: number;
};
/** Классифицирует показатель по свежести данных до подключения реальных аварийных правил. */
function isConfiguredLimit(value: number | null): value is number {
return typeof value === 'number' && Number.isFinite(value);
}
/** Классифицирует показатель по уставкам min/max из справочника tag. */
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;
if (ageSeconds > 300) {
return { status: 'critical', label: 'нет связи', ageSeconds };
}
if (ageSeconds > 30) {
return { status: 'warning', label: 'устарело', ageSeconds };
if (belowMin || aboveMax) {
return { status: 'critical', label: 'за пределами уставки', ageSeconds };
}
return { status: 'normal', label: 'норма', ageSeconds };

2
src/vite-env.d.ts vendored
View File

@@ -1,7 +1,7 @@
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_CLOUD_API_URL?: string;
readonly VITE_DIAGRAM_API_URL?: string;
readonly VITE_TOIR_LIGHT_ORIGIN?: string;
readonly VITE_KEYCLOAK_URL?: string;
readonly VITE_KEYCLOAK_REALM?: string;

View File

@@ -1,34 +1,23 @@
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vite';
import { defineConfig, loadEnv } from 'vite';
export default defineConfig({
plugins: [react()],
build: {
chunkSizeWarningLimit: 700,
rollupOptions: {
output: {
manualChunks(id) {
if (id.includes('node_modules/echarts') || id.includes('node_modules/echarts-for-react')) {
return 'charts';
}
export default defineConfig(({ mode }) => {
const { DEV_API_URL } = loadEnv(mode, '.', '');
if (
id.includes('node_modules/react') ||
id.includes('node_modules/react-dom') ||
id.includes('node_modules/@tanstack/react-query')
) {
return 'react';
}
return undefined;
return {
plugins: [react()],
build: {
chunkSizeWarningLimit: 700,
},
server: {
port: 5173,
proxy: {
'/api': {
target: DEV_API_URL,
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
},
},
},
},
server: {
port: 5173,
},
preview: {
port: 4173,
},
};
});