Compare commits

..

No commits in common. "c411142840782851e4aa60d9f46c7acf931e7a11" and "46cd1fa0fa872c12f92d76e71aff6733b831de76" have entirely different histories.

13 changed files with 500 additions and 1690 deletions

View File

@ -1,7 +0,0 @@
node_modules
.git
.gitignore
Dockerfile
.dockerignore
dist
npm-debug.log

View File

@ -31,10 +31,7 @@
"reactflow": "^11.11.4", "reactflow": "^11.11.4",
"recharts": "^2.15.1", "recharts": "^2.15.1",
"socket.io-client": "^4.8.1", "socket.io-client": "^4.8.1",
"vite-plugin-svgr": "^4.3.0", "vite-plugin-svgr": "^4.3.0"
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@dnd-kit/core": "^6.3.1"
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.17.0", "@eslint/js": "^9.17.0",

View File

@ -16,13 +16,13 @@ const formatXAxis = (tickItem) => {
}; };
const formatTooltip = (value, name, props) => { const formatTooltip = (value, name, props) => {
return [`${value.toFixed(2)}`, `Устройство ${name}`]; return [`${value.toFixed(2)}`, ` ${name}`];
}; };
const LineChartComponent = ({ const LineChartComponent = ({
data = [], data = [],
multipleLines = true, // По умолчанию включаем множественные линии multipleLines = false,
lineKey = 'device', // Ключ для разделения линий lineKey = 'device',
title, title,
description, description,
height = 400, height = 400,
@ -30,25 +30,27 @@ const LineChartComponent = ({
}) => { }) => {
if (!data || data.length === 0) return <div>Нет данных для отображения</div>; if (!data || data.length === 0) return <div>Нет данных для отображения</div>;
// Создаем массив уникальных устройств // Создаем массив уникальных линий
const devices = [...new Set(data.map(item => item.device))]; const lineKeys = [...new Set(data.map(item => item[lineKey] || 'default'))];
// Группируем данные по timestamp для правильного отображения // Преобразуем данные в формат, удобный для Recharts
const timestamps = [...new Set(data.map(item => item.timestamp))].sort(); const chartData = data.reduce((acc, item) => {
const timestamp = item.timestamp;
const existingPoint = acc.find(p => p.timestamp === timestamp);
const chartData = timestamps.map(timestamp => { if (existingPoint) {
const point = { timestamp }; return acc.map(p =>
p.timestamp === timestamp
// Для каждого устройства находим значение в этот timestamp ? { ...p, [item[lineKey] || 'default']: item.value }
devices.forEach(device => { : p
const deviceData = data.find(item =>
item.timestamp === timestamp && item.device === device
); );
point[`device_${device}`] = deviceData ? deviceData.value : null; }
});
return point; return [...acc, {
}); timestamp,
[item[lineKey] || 'default']: item.value
}];
}, []).sort((a, b) => a.timestamp - b.timestamp);
return ( return (
<div style={{ width: '100%', height: `${height}px` }}> <div style={{ width: '100%', height: `${height}px` }}>
@ -61,27 +63,39 @@ const LineChartComponent = ({
dataKey="timestamp" dataKey="timestamp"
tickFormatter={formatXAxis} tickFormatter={formatXAxis}
/> />
<YAxis /> <YAxis domain={[0, 25]} />
<Tooltip <Tooltip
formatter={formatTooltip} formatter={formatTooltip}
labelFormatter={(label) => format(new Date(label), 'yyyy-MM-dd HH:mm:ss')} labelFormatter={(label) => format(new Date(label), 'yyyy-MM-dd HH:mm:ss')}
/> />
<Legend /> <Legend />
{devices.map(device => ( {multipleLines ? (
lineKeys.map(key => (
<Line
key={`line-${key}`}
type="monotone"
dataKey={key}
name={` ${key}`}
stroke={lineColors[key] || lineColors.default}
strokeWidth={2}
dot={false}
activeDot={{ r: 6 }}
isAnimationActive={false}
/>
))
) : (
<Line <Line
key={`line-${device}`}
type="monotone" type="monotone"
dataKey={`device_${device}`} dataKey={lineKeys[0] || 'value'}
name={`Устройство ${device}`} name={title}
stroke={lineColors[device] || lineColors.default} stroke={lineColors.default}
strokeWidth={2} strokeWidth={2}
dot={false} dot={false}
activeDot={{ r: 6 }} activeDot={{ r: 6 }}
isAnimationActive={false} isAnimationActive={false}
connectNulls={true}
/> />
))} )}
{/* Добавляем диапазоны если они есть */} {/* Добавляем диапазоны если они есть */}
{ranges.map((range, idx) => ( {ranges.map((range, idx) => (

View File

@ -1,8 +1,8 @@
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect, useMemo } from 'react';
import LineChartComponent from './LineChartComponent'; import LineChartComponent from './LineChartComponent';
import DateRangeSelector from '../Charts2/Components/DateRangeSelector'; import DateRangeSelector from '../Charts2/Components/DateRangeSelector';
import metricsService from '../Charts2/Components/metricsService'; import metricsService from '../Charts2/Components/metricsService';
import { Button, Radio, message, Tag } from 'antd'; import { Button, Radio, message, Tag, Spin } from 'antd';
import moment from 'moment'; import moment from 'moment';
import StatusLogTable from '../Charts2/Components/StatusLogTable'; import StatusLogTable from '../Charts2/Components/StatusLogTable';
import { Box, IconButton, Tooltip as MuiTooltip } from '@mui/material'; import { Box, IconButton, Tooltip as MuiTooltip } from '@mui/material';
@ -15,12 +15,14 @@ const SystemChart = ({ metricInfo, chartHeight = 580 }) => {
title = metricName, title = metricName,
description, description,
context = {}, context = {},
ranges = [] ranges = [],
multipleLines = false,
lineKey = 'device'
} = metricInfo || {}; } = metricInfo || {};
const { device, source_id } = context; const { device, source_id } = context;
const [chartData, setChartData] = useState([]); const [rawData, setRawData] = useState([]);
const [isLoading, setIsLoading] = useState(true); const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null); const [error, setError] = useState(null);
const [metricMeta, setMetricMeta] = useState({}); const [metricMeta, setMetricMeta] = useState({});
@ -30,96 +32,43 @@ const SystemChart = ({ metricInfo, chartHeight = 580 }) => {
const [isLiveUpdating, setIsLiveUpdating] = useState(false); const [isLiveUpdating, setIsLiveUpdating] = useState(false);
const [showLogs, setShowLogs] = useState(false); const [showLogs, setShowLogs] = useState(false);
const [statusLogs, setStatusLogs] = useState([]); const [statusLogs, setStatusLogs] = useState([]);
const MAX_POINTS = 50;
const MAX_POINTS = 1000;
const TIME_WINDOW_MS = 3600 * 1000; const TIME_WINDOW_MS = 3600 * 1000;
const subscriptionKey = useMemo(() => {
// Эта функция может больше не понадобиться, так как
// сервис сам генерирует ключи, но оставьте для совместимости
const getSubscriptionKey = () => {
const filterParts = []; const filterParts = [];
if (device) filterParts.push(`device=${encodeURIComponent(device)}`); if (device) filterParts.push(`device=${encodeURIComponent(device)}`);
if (source_id) filterParts.push(`source_id=${encodeURIComponent(source_id)}`); if (source_id) filterParts.push(`source_id=${encodeURIComponent(source_id)}`);
return `${metricName}${filterParts.length ? `?${filterParts.join('&')}` : ''}`; return `${metricName}${filterParts.length ? `?${filterParts.join('&')}` : ''}`;
}; }, [metricName, device, source_id]);
const getStatusFromRanges = (value, ranges) => { const formatMetricData = (responseData) => {
if (!ranges || ranges.length === 0) return 1; const dataArray = Array.isArray(responseData) ? responseData : responseData.data;
for (const r of ranges) {
if (value >= r.min && value <= r.max) {
return r.status;
}
}
return 1;
};
const formatMetricData = (dataArray) => {
if (!Array.isArray(dataArray)) { if (!Array.isArray(dataArray)) {
console.error('Expected array in formatMetricData, got:', typeof dataArray); console.error('Expected array but got:', responseData);
return []; return [];
} }
return dataArray.map(item => { return dataArray.map(item => ({
if (item.timestamp === undefined || item.value === undefined) { ...item,
console.warn('Invalid metric item:', item); timestamp: item.timestamp,
return null; value: parseFloat(item.value),
} name: item.__name__ || metricName,
status: parseInt(item.status) || 0,
return { device: item.device?.trim() || null,
...item, source_id: item.source_id || null,
timestamp: Number(item.timestamp), description: item.description || description,
value: parseFloat(item.value), lineId: item[lineKey] || 'default'
status: getStatusFromRanges(parseFloat(item.value), ranges), }));
name: item.__name__ || metricName,
device: item.device?.trim() || null,
source_id: item.source_id || null,
description: item.description || description
};
}).filter(Boolean)
.sort((a, b) => a.timestamp - b.timestamp);
}; };
const calculateStep = (startTime, endTime, maxPoints = 10000) => { const calculateStep = (start, end) => {
const durationSeconds = (endTime.getTime() - startTime.getTime()) / 1000; const duration = end.getTime() - start.getTime();
return Math.max(Math.ceil(durationSeconds / maxPoints), 1); return Math.max(Math.floor(duration / (MAX_POINTS * 1000)), 1);
}; };
const downsampleData = (data, maxPoints = MAX_POINTS) => {
if (data.length <= maxPoints) return [...data];
const sortedData = [...data].sort((a, b) => a.timestamp - b.timestamp);
const step = Math.max(1, Math.floor(sortedData.length / maxPoints));
const result = [];
for (let i = 0; i < sortedData.length; i += step) {
if (result.length >= maxPoints) break;
result.push(sortedData[i]);
}
if (result.length > 0) {
const lastOriginalPoint = sortedData[sortedData.length - 1];
if (result[result.length - 1].timestamp !== lastOriginalPoint.timestamp) {
result[result.length - 1] = lastOriginalPoint;
}
}
return result;
};
useEffect(() => {
if (chartData.length > 0) {
const newLogs = chartData.reduce((acc, point, index) => {
if (index === 0 || point.status !== chartData[index - 1].status) {
return [...acc, point];
}
return acc;
}, []);
setStatusLogs(newLogs);
}
}, [chartData]);
const fetchHistoricalData = async (start, end) => { const fetchHistoricalData = async (start, end) => {
setIsLoading(true); setIsLoading(true);
setError(null); setError(null);
@ -133,23 +82,19 @@ const SystemChart = ({ metricInfo, chartHeight = 580 }) => {
const step = calculateStep(start, end); const step = calculateStep(start, end);
// Используем новый метод для исторических данных
const data = await metricsService.fetchMetricsRange( const data = await metricsService.fetchMetricsRange(
metricName, metricName,
start.getTime(), // Теперь передаем timestamp в миллисекундах Math.floor(start.getTime() / 1000),
end.getTime(), Math.floor(end.getTime() / 1000),
step, step,
extendedFilters extendedFilters
); );
const formattedData = formatMetricData(data) const responseData = Array.isArray(data) ? data : data.data;
.sort((a, b) => a.timestamp - b.timestamp); const formattedData = formatMetricData(responseData);
setRawData(formattedData);
const limitedData = formattedData.length > MAX_POINTS if (formattedData.length > 0) {
? downsampleData(formattedData, MAX_POINTS)
: formattedData;
if (limitedData.length > 0) {
setMetricMeta({ setMetricMeta({
type: data[0]?.type, type: data[0]?.type,
description: data[0]?.description || description, description: data[0]?.description || description,
@ -157,8 +102,6 @@ const SystemChart = ({ metricInfo, chartHeight = 580 }) => {
job: data[0]?.job job: data[0]?.job
}); });
} }
setChartData(limitedData);
} catch (err) { } catch (err) {
console.error(`Error loading historical data for ${metricName}:`, err); console.error(`Error loading historical data for ${metricName}:`, err);
setError(err.message); setError(err.message);
@ -174,55 +117,42 @@ const SystemChart = ({ metricInfo, chartHeight = 580 }) => {
const end = new Date(); const end = new Date();
const start = new Date(end.getTime() - TIME_WINDOW_MS); const start = new Date(end.getTime() - TIME_WINDOW_MS);
const cutoffTime = Date.now() - TIME_WINDOW_MS;
fetchHistoricalData(start, end).finally(() => setIsLoading(false)); fetchHistoricalData(start, end).finally(() => setIsLoading(false));
// Изменяем параметры подписки
return metricsService.subscribeToMetric( return metricsService.subscribeToMetric(
metricName, // Теперь передаем просто имя метрики subscriptionKey,
{ ...filters, device, source_id }, // Фильры отдельным параметром (newData) => {
(update) => { // Колбэк получает объект с данными setRawData(prev => {
console.log('Received WS update:', update); const actualData = Array.isArray(newData) ? newData : newData.data;
const formattedNewData = formatMetricData(actualData)
if (!update || !Array.isArray(update.data)) {
console.error('Invalid update format:', update);
return;
}
setChartData(prev => {
const now = Date.now();
const cutoffTime = now - TIME_WINDOW_MS;
const formattedNew = formatMetricData(update.data)
.filter(point => point.timestamp >= cutoffTime); .filter(point => point.timestamp >= cutoffTime);
const filteredPrev = prev.filter(point => const filteredPrev = prev.filter(point => point.timestamp >= cutoffTime);
point.timestamp >= cutoffTime
);
const merged = [...filteredPrev, ...formattedNew] const merged = [...filteredPrev, ...formattedNewData]
.filter((v, i, a) => .filter((v, i, a) =>
a.findIndex(t => t.timestamp === v.timestamp) === i a.findIndex(t =>
) t.timestamp === v.timestamp &&
.sort((a, b) => a.timestamp - b.timestamp); t[lineKey] === v[lineKey]
) === i
);
return merged.length > MAX_POINTS return merged;
? merged.slice(-MAX_POINTS)
: merged;
}); });
}, },
5000 // Интервал обновления (можно настроить) 5000,
{
...filters,
...(device && { device }),
...(source_id && { source_id })
}
); );
}; };
const stopRealtimeUpdates = () => { const stopRealtimeUpdates = () => {
setIsLiveUpdating(false); setIsLiveUpdating(false);
// Теперь отписываемся по метрике и фильтрам metricsService.unsubscribeFromMetric(subscriptionKey);
metricsService.unsubscribeFromMetric(
metricName,
{ ...filters, device, source_id }
);
}; };
const handleCustomRangeApply = () => { const handleCustomRangeApply = () => {
@ -232,29 +162,45 @@ const SystemChart = ({ metricInfo, chartHeight = 580 }) => {
}; };
useEffect(() => { useEffect(() => {
console.log('Metric changed:', { metricName, device, source_id, filters }); if (rawData.length > 0) {
const logs = [];
const devices = [...new Set(rawData.map(item => item[lineKey]))];
devices.forEach(dev => {
const deviceData = rawData
.filter(item => item[lineKey] === dev)
.sort((a, b) => a.timestamp - b.timestamp);
if (deviceData.length > 0) {
logs.push(deviceData[0]); // Первая точка
for (let i = 1; i < deviceData.length; i++) {
if (deviceData[i].status !== deviceData[i - 1].status) {
logs.push(deviceData[i]);
}
}
}
});
setStatusLogs(logs.sort((a, b) => b.timestamp - a.timestamp));
}
}, [rawData, lineKey]);
useEffect(() => {
let unsubscribe; let unsubscribe;
const init = async () => { if (mode === 'realtime') {
if (mode === 'realtime') { unsubscribe = startRealtimeUpdates();
unsubscribe = startRealtimeUpdates(); } else {
} else { stopRealtimeUpdates();
await fetchHistoricalData(startDate, endDate); fetchHistoricalData(startDate, endDate);
} }
};
init();
return () => { return () => {
if (unsubscribe) { if (unsubscribe) unsubscribe();
unsubscribe(); // Вызываем функцию отписки stopRealtimeUpdates();
}
if (mode === 'realtime') {
stopRealtimeUpdates(); // Дополнительная очистка
}
}; };
}, [mode, metricName, device, source_id, JSON.stringify(filters)]); // Добавляем JSON.stringify для фильтров }, [mode, metricName, device, source_id]);
const metaInfo = [ const metaInfo = [
metricMeta.instance && `Instance: ${metricMeta.instance}`, metricMeta.instance && `Instance: ${metricMeta.instance}`,
@ -263,7 +209,7 @@ const SystemChart = ({ metricInfo, chartHeight = 580 }) => {
].filter(Boolean).join(' | '); ].filter(Boolean).join(' | ');
return ( return (
<div> <div style={{ position: 'relative' }}>
<div style={{ marginBottom: 16 }}> <div style={{ marginBottom: 16 }}>
<Radio.Group <Radio.Group
value={mode} value={mode}
@ -285,15 +231,10 @@ const SystemChart = ({ metricInfo, chartHeight = 580 }) => {
/> />
)} )}
{mode === 'realtime' && isLiveUpdating && ( {mode === 'realtime' && (
<Button <Tag color={isLiveUpdating ? 'green' : 'red'}>
type="primary" {isLiveUpdating ? 'Обновление в реальном времени' : 'Режим реального времени остановлен'}
danger </Tag>
onClick={() => setMode('historical')}
style={{ marginTop: 10 }}
>
Остановить обновление
</Button>
)} )}
</div> </div>
@ -318,28 +259,26 @@ const SystemChart = ({ metricInfo, chartHeight = 580 }) => {
</MuiTooltip> </MuiTooltip>
{isLoading ? ( {isLoading ? (
<div>Загрузка графика...</div> <div style={{ height: chartHeight, display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
<Spin size="large" tip="Загрузка данных..." />
</div>
) : error ? ( ) : error ? (
<div>Ошибка: {error}</div> <div style={{ color: 'red', padding: 20 }}>Ошибка: {error}</div>
) : chartData.length === 0 ? ( ) : rawData.length === 0 ? (
<div>Нет данных для метрики: {metricName}</div> <div style={{ padding: 20 }}>Нет данных для метрики: {metricName}</div>
) : ( ) : (
<> <>
<LineChartComponent <LineChartComponent
data={chartData} data={rawData}
title={title} title={title}
description={description} description={description}
multipleLines={multipleLines}
lineKey={lineKey}
metaInfo={metaInfo} metaInfo={metaInfo}
height={chartHeight} height={chartHeight}
additionalFilters={{
device,
source_id
}}
ranges={ranges} ranges={ranges}
/> />
{showLogs && ( {showLogs && <StatusLogTable logs={statusLogs} />}
<StatusLogTable logs={statusLogs} />
)}
</> </>
)} )}
</Box> </Box>

View File

@ -2,28 +2,16 @@ class MetricsService {
constructor() { constructor() {
this.baseUrl = '/metrics-ws'; this.baseUrl = '/metrics-ws';
this.socket = null; this.socket = null;
this.subscriptions = new Map(); // Хранит подписки на real-time данные this.subscriptions = new Map();
this.pendingRequests = new Map(); // Для разовых запросов this.pendingRequests = new Map();
this.reconnectAttempts = 0; this.reconnectAttempts = 0;
this.maxReconnectAttempts = 5; this.maxReconnectAttempts = 5;
this.reconnectDelay = 5000; this.reconnectDelay = 5000;
this.connectionCallbacks = new Set(); // Колбэки для событий подключения
window.addEventListener('beforeunload', () => this.cleanupAll()); window.addEventListener('beforeunload', () => this.cleanupAll());
window.addEventListener('pagehide', () => this.cleanupAll()); window.addEventListener('pagehide', () => this.cleanupAll());
} }
// Новый метод для отслеживания состояния подключения
onConnectionChange(callback) {
this.connectionCallbacks.add(callback);
return () => this.connectionCallbacks.delete(callback);
}
// Уведомление всех подписчиков о изменении состояния
notifyConnectionChange(connected) {
this.connectionCallbacks.forEach(cb => cb(connected));
}
handleServerMessage(msg) { handleServerMessage(msg) {
try { try {
if (!msg || typeof msg !== 'object') { if (!msg || typeof msg !== 'object') {
@ -34,25 +22,25 @@ class MetricsService {
const { event, data, requestId } = msg; const { event, data, requestId } = msg;
switch (event) { switch (event) {
case 'connected': case 'metrics-data':
console.log('Server connection confirmed:', data); if (requestId && this.pendingRequests.has(requestId)) {
this.notifyConnectionChange(true); const { resolve } = this.pendingRequests.get(requestId);
resolve(data);
this.pendingRequests.delete(requestId);
} else {
const metricKey = data.metric;
const callbacks = this.subscriptions.get(metricKey) || [];
callbacks.forEach(cb => cb(data));
}
break; break;
case 'realtime-data': case 'metrics-error':
this.handleRealtimeData(data, requestId); if (requestId && this.pendingRequests.has(requestId)) {
break; const { reject } = this.pendingRequests.get(requestId);
reject(new Error(data.error));
case 'historical-data': this.pendingRequests.delete(requestId);
this.handleHistoricalData(data, requestId); }
break;
case 'current-data':
this.handleCurrentData(data, requestId);
break;
case 'error':
this.handleError(data, requestId);
break; break;
default: default:
@ -63,54 +51,6 @@ class MetricsService {
} }
} }
handleRealtimeData(data, requestId) {
const { metric, filters, data: metricsData, type } = data;
const metricKey = this.getMetricKey(metric, filters);
if (requestId && this.pendingRequests.has(requestId)) {
// Это ответ на разовый запрос
const { resolve } = this.pendingRequests.get(requestId);
resolve(metricsData);
this.pendingRequests.delete(requestId);
} else {
// Это обновление по подписке
const callbacks = this.subscriptions.get(metricKey) || [];
callbacks.forEach(cb => cb({
data: metricsData,
type: type || 'update',
metric,
filters,
timestamp: Date.now()
}));
}
}
handleHistoricalData(data, requestId) {
if (requestId && this.pendingRequests.has(requestId)) {
const { resolve } = this.pendingRequests.get(requestId);
resolve(data.data || data);
this.pendingRequests.delete(requestId);
}
}
handleCurrentData(data, requestId) {
if (requestId && this.pendingRequests.has(requestId)) {
const { resolve } = this.pendingRequests.get(requestId);
resolve(data.data || data);
this.pendingRequests.delete(requestId);
}
}
handleError(data, requestId) {
if (requestId && this.pendingRequests.has(requestId)) {
const { reject } = this.pendingRequests.get(requestId);
reject(new Error(data.error || 'Unknown error'));
this.pendingRequests.delete(requestId);
} else {
console.error('Server error:', data.error);
}
}
connectWebSocket() { connectWebSocket() {
if (this.socket && (this.socket.readyState === WebSocket.OPEN || this.socket.readyState === WebSocket.CONNECTING)) { if (this.socket && (this.socket.readyState === WebSocket.OPEN || this.socket.readyState === WebSocket.CONNECTING)) {
return; return;
@ -118,27 +58,25 @@ class MetricsService {
console.log('Connecting WebSocket...'); console.log('Connecting WebSocket...');
this.socket = new WebSocket(this.baseUrl); this.socket = new WebSocket(this.baseUrl);
this.notifyConnectionChange(false);
this.socket.addEventListener('open', () => { this.socket.addEventListener('open', () => {
console.log('WebSocket connected'); console.log('WebSocket connected');
this.reconnectAttempts = 0; this.reconnectAttempts = 0;
this.notifyConnectionChange(true); this.subscriptions.forEach((_, metricKey) => {
const filters = this.parseFiltersFromKey(metricKey);
// Переподписываемся на все активные подписки const [metric] = metricKey.split('?');
this.resubscribeAll(); this.sendMessage('subscribe-metric', { metric, filters });
});
}); });
this.socket.addEventListener('close', (event) => { this.socket.addEventListener('close', () => {
console.log('WebSocket disconnected', event.code, event.reason); console.log('WebSocket disconnected');
this.socket = null; this.socket = null;
this.notifyConnectionChange(false);
this.scheduleReconnect(); this.scheduleReconnect();
}); });
this.socket.addEventListener('error', (err) => { this.socket.addEventListener('error', (err) => {
console.error('WebSocket error:', err); console.error('WebSocket error:', err);
this.notifyConnectionChange(false);
}); });
this.socket.addEventListener('message', (event) => { this.socket.addEventListener('message', (event) => {
@ -151,18 +89,6 @@ class MetricsService {
}); });
} }
// Переподписка на все активные подписки после переподключения
resubscribeAll() {
this.subscriptions.forEach((_, metricKey) => {
const { metric, filters } = this.parseMetricKey(metricKey);
this.sendMessage('subscribe-realtime', {
metric,
filters,
interval: 10000 // Дефолтный интервал
});
});
}
scheduleReconnect() { scheduleReconnect() {
if (this.reconnectAttempts >= this.maxReconnectAttempts) { if (this.reconnectAttempts >= this.maxReconnectAttempts) {
console.warn('Max reconnect attempts reached'); console.warn('Max reconnect attempts reached');
@ -178,13 +104,12 @@ class MetricsService {
}, delay); }, delay);
} }
sendMessage(event, data, requestId) { sendMessage(event, data) {
if (!this.socket || this.socket.readyState !== WebSocket.OPEN) { if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
if (this.socket && this.socket.readyState === WebSocket.CONNECTING) { if (this.socket && this.socket.readyState === WebSocket.CONNECTING) {
// Ждем открытия соединения
const waitForOpen = () => { const waitForOpen = () => {
if (this.socket.readyState === WebSocket.OPEN) { if (this.socket.readyState === WebSocket.OPEN) {
this.doSendMessage(event, data, requestId); this.socket.send(JSON.stringify({ event, data }));
} else if (this.socket.readyState === WebSocket.CONNECTING) { } else if (this.socket.readyState === WebSocket.CONNECTING) {
setTimeout(waitForOpen, 100); setTimeout(waitForOpen, 100);
} }
@ -193,188 +118,95 @@ class MetricsService {
} else { } else {
console.warn('WebSocket not connected, cannot send:', event); console.warn('WebSocket not connected, cannot send:', event);
this.connectWebSocket(); this.connectWebSocket();
// Сохраняем сообщение для отправки после подключения
setTimeout(() => {
if (this.socket?.readyState === WebSocket.OPEN) {
this.doSendMessage(event, data, requestId);
}
}, 1000);
} }
return; return;
} }
this.doSendMessage(event, data, requestId); this.socket.send(JSON.stringify({ event, data }));
} }
doSendMessage(event, data, requestId) { async fetchMetricsRange(metric, start, end, step = 15, filters = {}) {
const message = requestId ? { event, data, requestId } : { event, data }; return new Promise((resolve, reject) => {
this.socket.send(JSON.stringify(message)); this.connectWebSocket();
const requestId = `range-${Date.now()}`;
// Таймаут для очистки
const timeout = setTimeout(() => {
reject(new Error('Request timeout'));
this.pendingRequests.delete(requestId);
}, 12000);
this.pendingRequests.set(requestId, {
resolve: (responseData) => {
clearTimeout(timeout);
const data = Array.isArray(responseData) ? responseData :
(responseData?.data || []);
resolve(data);
},
reject: (err) => {
clearTimeout(timeout);
reject(err);
}
});
this.sendMessage('get-metrics', {
metric, start, end, step, filters, isRangeQuery: true, requestId
});
});
} }
// ============ ПУБЛИЧНЫЕ МЕТОДЫ ============ subscribeToMetric(metricKey, callback, interval = 5000, filters = {}) {
// Подписка на real-time данные
subscribeToMetric(metric, filters = {}, callback, interval = 10000) {
this.connectWebSocket(); this.connectWebSocket();
const metricKey = this.getMetricKey(metric, filters);
if (!this.subscriptions.has(metricKey)) { if (!this.subscriptions.has(metricKey)) {
this.subscriptions.set(metricKey, []); this.subscriptions.set(metricKey, []);
const [metric] = metricKey.split('?');
this.sendMessage('subscribe-realtime', { this.sendMessage('subscribe-metric', { metric, interval, filters });
metric,
filters,
interval
});
} }
const callbacks = this.subscriptions.get(metricKey); const callbacks = this.subscriptions.get(metricKey);
callbacks.push(callback); callbacks.push(callback);
// Возвращаем функцию для отписки return () => this.unsubscribeFromMetric(metricKey, callback);
return () => this.unsubscribeFromMetric(metric, filters, callback);
} }
// Отписка от real-time данных unsubscribeFromMetric(metricKey, callback) {
unsubscribeFromMetric(metric, filters = {}, callback) {
const metricKey = this.getMetricKey(metric, filters);
const callbacks = this.subscriptions.get(metricKey) || []; const callbacks = this.subscriptions.get(metricKey) || [];
const filtered = callbacks.filter(cb => cb !== callback); const filtered = callbacks.filter(cb => cb !== callback);
if (filtered.length === 0) { if (filtered.length === 0) {
this.subscriptions.delete(metricKey); this.subscriptions.delete(metricKey);
this.sendMessage('unsubscribe-realtime', { metric, filters }); const [metric] = metricKey.split('?');
this.sendMessage('unsubscribe-metric', { metric });
} else { } else {
this.subscriptions.set(metricKey, filtered); this.subscriptions.set(metricKey, filtered);
} }
} }
// Запрос исторических данных (разовый) parseFiltersFromKey(metricKey) {
async fetchMetricsRange(metric, start, end, step = 60, filters = {}) { const parts = metricKey.split('?');
return new Promise((resolve, reject) => { if (parts.length < 2) return {};
this.connectWebSocket(); return parts[1].split('&').reduce((acc, pair) => {
const requestId = `historical-${Date.now()}-${Math.random().toString(36).slice(2)}`; const [key, value] = pair.split('=');
if (key && value) acc[key] = value;
const timeout = setTimeout(() => { return acc;
reject(new Error('Historical data request timeout')); }, {});
this.pendingRequests.delete(requestId);
}, 30000); // 30 секунд таймаут для historical данных
this.pendingRequests.set(requestId, {
resolve: (data) => {
clearTimeout(timeout);
resolve(data);
},
reject: (err) => {
clearTimeout(timeout);
reject(err);
}
});
this.sendMessage('get-historical', {
metric,
start: Math.floor(start / 1000) * 1000, // Ensure milliseconds
end: Math.floor(end / 1000) * 1000,
step,
filters
}, requestId);
});
}
// Запрос текущих данных (разовый)
async fetchCurrentMetrics(metric, filters = {}) {
return new Promise((resolve, reject) => {
this.connectWebSocket();
const requestId = `current-${Date.now()}-${Math.random().toString(36).slice(2)}`;
const timeout = setTimeout(() => {
reject(new Error('Current data request timeout'));
this.pendingRequests.delete(requestId);
}, 10000); // 10 секунд таймаут
this.pendingRequests.set(requestId, {
resolve: (data) => {
clearTimeout(timeout);
resolve(data);
},
reject: (err) => {
clearTimeout(timeout);
reject(err);
}
});
this.sendMessage('get-current', {
metric,
filters
}, requestId);
});
}
// Отписка от всех подписок
unsubscribeAll() {
this.sendMessage('unsubscribe-all', {});
this.subscriptions.clear();
}
// ============ ВСПОМОГАТЕЛЬНЫЕ МЕТОДЫ ============
getMetricKey(metric, filters) {
const sortedKeys = Object.keys(filters).sort();
const filterString = sortedKeys
.map(key => `${key}=${encodeURIComponent(filters[key])}`)
.join('&');
return filterString ? `${metric}?${filterString}` : metric;
}
parseMetricKey(metricKey) {
const [metric, query] = metricKey.split('?');
const filters = {};
if (query) {
query.split('&').forEach(pair => {
const [key, value] = pair.split('=');
if (key && value) {
filters[decodeURIComponent(key)] = decodeURIComponent(value);
}
});
}
return { metric, filters };
} }
cleanupAll() { cleanupAll() {
this.unsubscribeAll(); this.sendMessage('unsubscribe-all', {});
this.subscriptions.clear();
this.disconnectWebSocket(); this.disconnectWebSocket();
} }
disconnectWebSocket() { disconnectWebSocket() {
if (this.socket) { if (this.socket) {
this.socket.close(1000, 'Client disconnected'); this.socket.close();
this.socket = null; this.socket = null;
} }
this.notifyConnectionChange(false);
}
// Проверка состояния подключения
isConnected() {
return this.socket?.readyState === WebSocket.OPEN;
}
// Получение текущего состояния
getConnectionState() {
return this.socket ? this.socket.readyState : WebSocket.CLOSED;
} }
} }
// Создаем глобальный экземпляр
const metricsService = new MetricsService(); const metricsService = new MetricsService();
// Экспорт для использования в модульной системе
export default metricsService; export default metricsService;
// Глобальный экспорт для прямого использования в браузере
if (typeof window !== 'undefined') {
window.MetricsService = metricsService;
}

View File

@ -34,8 +34,6 @@ const PrometheusChart = ({ metricInfo, chartHeight = 580 }) => {
const TIME_WINDOW_MS = 3600 * 1000; const TIME_WINDOW_MS = 3600 * 1000;
// Эта функция может больше не понадобиться, так как
// сервис сам генерирует ключи, но оставьте для совместимости
const getSubscriptionKey = () => { const getSubscriptionKey = () => {
const filterParts = []; const filterParts = [];
if (device) filterParts.push(`device=${encodeURIComponent(device)}`); if (device) filterParts.push(`device=${encodeURIComponent(device)}`);
@ -43,16 +41,6 @@ const PrometheusChart = ({ metricInfo, chartHeight = 580 }) => {
return `${metricName}${filterParts.length ? `?${filterParts.join('&')}` : ''}`; return `${metricName}${filterParts.length ? `?${filterParts.join('&')}` : ''}`;
}; };
const getStatusFromRanges = (value, ranges) => {
if (!ranges || ranges.length === 0) return 1;
for (const r of ranges) {
if (value >= r.min && value <= r.max) {
return r.status;
}
}
return 1;
};
const formatMetricData = (dataArray) => { const formatMetricData = (dataArray) => {
if (!Array.isArray(dataArray)) { if (!Array.isArray(dataArray)) {
console.error('Expected array in formatMetricData, got:', typeof dataArray); console.error('Expected array in formatMetricData, got:', typeof dataArray);
@ -69,7 +57,7 @@ const PrometheusChart = ({ metricInfo, chartHeight = 580 }) => {
...item, ...item,
timestamp: Number(item.timestamp), timestamp: Number(item.timestamp),
value: parseFloat(item.value), value: parseFloat(item.value),
status: getStatusFromRanges(parseFloat(item.value), ranges), status: parseInt(item.status || '0'),
name: item.__name__ || metricName, name: item.__name__ || metricName,
device: item.device?.trim() || null, device: item.device?.trim() || null,
source_id: item.source_id || null, source_id: item.source_id || null,
@ -132,12 +120,10 @@ const PrometheusChart = ({ metricInfo, chartHeight = 580 }) => {
}; };
const step = calculateStep(start, end); const step = calculateStep(start, end);
// Используем новый метод для исторических данных
const data = await metricsService.fetchMetricsRange( const data = await metricsService.fetchMetricsRange(
metricName, metricName,
start.getTime(), // Теперь передаем timestamp в миллисекундах Math.floor(start.getTime() / 1000),
end.getTime(), Math.floor(end.getTime() / 1000),
step, step,
extendedFilters extendedFilters
); );
@ -146,7 +132,7 @@ const PrometheusChart = ({ metricInfo, chartHeight = 580 }) => {
.sort((a, b) => a.timestamp - b.timestamp); .sort((a, b) => a.timestamp - b.timestamp);
const limitedData = formattedData.length > MAX_POINTS const limitedData = formattedData.length > MAX_POINTS
? downsampleData(formattedData, MAX_POINTS) ? formattedData.slice(-MAX_POINTS)
: formattedData; : formattedData;
if (limitedData.length > 0) { if (limitedData.length > 0) {
@ -177,15 +163,12 @@ const PrometheusChart = ({ metricInfo, chartHeight = 580 }) => {
fetchHistoricalData(start, end).finally(() => setIsLoading(false)); fetchHistoricalData(start, end).finally(() => setIsLoading(false));
// Изменяем параметры подписки
return metricsService.subscribeToMetric( return metricsService.subscribeToMetric(
metricName, // Теперь передаем просто имя метрики getSubscriptionKey(),
{ ...filters, device, source_id }, // Фильры отдельным параметром (newData) => {
(update) => { // Колбэк получает объект с данными console.log('Received WS update:', newData);
console.log('Received WS update:', update); if (!Array.isArray(newData)) {
console.error('Expected array in WS update, got:', typeof newData);
if (!update || !Array.isArray(update.data)) {
console.error('Invalid update format:', update);
return; return;
} }
@ -193,7 +176,7 @@ const PrometheusChart = ({ metricInfo, chartHeight = 580 }) => {
const now = Date.now(); const now = Date.now();
const cutoffTime = now - TIME_WINDOW_MS; const cutoffTime = now - TIME_WINDOW_MS;
const formattedNew = formatMetricData(update.data) const formattedNew = formatMetricData(newData)
.filter(point => point.timestamp >= cutoffTime); .filter(point => point.timestamp >= cutoffTime);
const filteredPrev = prev.filter(point => const filteredPrev = prev.filter(point =>
@ -211,18 +194,15 @@ const PrometheusChart = ({ metricInfo, chartHeight = 580 }) => {
: merged; : merged;
}); });
}, },
5000 // Интервал обновления (можно настроить) 1000,
{ ...filters, device, source_id }
); );
}; };
const stopRealtimeUpdates = () => { const stopRealtimeUpdates = () => {
setIsLiveUpdating(false); setIsLiveUpdating(false);
// Теперь отписываемся по метрике и фильтрам metricsService.unsubscribeFromMetric(getSubscriptionKey());
metricsService.unsubscribeFromMetric(
metricName,
{ ...filters, device, source_id }
);
}; };
const handleCustomRangeApply = () => { const handleCustomRangeApply = () => {
@ -235,7 +215,6 @@ const PrometheusChart = ({ metricInfo, chartHeight = 580 }) => {
console.log('Metric changed:', { metricName, device, source_id, filters }); console.log('Metric changed:', { metricName, device, source_id, filters });
let unsubscribe; let unsubscribe;
const init = async () => { const init = async () => {
if (mode === 'realtime') { if (mode === 'realtime') {
unsubscribe = startRealtimeUpdates(); unsubscribe = startRealtimeUpdates();
@ -247,14 +226,10 @@ const PrometheusChart = ({ metricInfo, chartHeight = 580 }) => {
init(); init();
return () => { return () => {
if (unsubscribe) { if (unsubscribe) unsubscribe();
unsubscribe(); // Вызываем функцию отписки stopRealtimeUpdates();
}
if (mode === 'realtime') {
stopRealtimeUpdates(); // Дополнительная очистка
}
}; };
}, [mode, metricName, device, source_id, JSON.stringify(filters)]); // Добавляем JSON.stringify для фильтров }, [mode, metricName, device, source_id, filters]);
const metaInfo = [ const metaInfo = [
metricMeta.instance && `Instance: ${metricMeta.instance}`, metricMeta.instance && `Instance: ${metricMeta.instance}`,

View File

@ -1,303 +0,0 @@
import React, { useState, useEffect } from 'react';
import {
Box,
Typography,
List,
ListItem,
ListItemText,
ListItemSecondaryAction,
IconButton,
TextField,
Dialog,
DialogTitle,
DialogContent,
DialogActions,
Button,
Chip,
Collapse,
CircularProgress
} from '@mui/material';
import {
Edit as EditIcon,
Delete as DeleteIcon,
ExpandMore as ExpandMoreIcon,
ExpandLess as ExpandLessIcon
} from '@mui/icons-material';
import axios from 'axios';
const MenuItemComponent = ({ item, level = 0, onEdit, onDelete }) => {
const [expanded, setExpanded] = useState(false);
const hasChildren = item.items && item.items.length > 0;
const handleToggle = () => {
if (hasChildren) {
setExpanded(!expanded);
}
};
return (
<>
<ListItem
sx={{
pl: level * 4,
borderBottom: '1px solid',
borderColor: 'divider'
}}
>
<ListItemText
primary={
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Typography variant="body1">{item.title}</Typography>
{item.isDynamic && (
<Chip
label="Динамический"
size="small"
color="info"
variant="outlined"
/>
)}
</Box>
}
secondary={item.id}
/>
<ListItemSecondaryAction>
{/* */}
<>
<IconButton
edge="end"
aria-label="edit"
onClick={() => onEdit(item)}
sx={{ mr: 1 }}
>
<EditIcon />
</IconButton>
<IconButton
edge="end"
aria-label="delete"
onClick={() => onDelete(item)}
color="error"
>
<DeleteIcon />
</IconButton>
</>
{hasChildren && (
<IconButton
edge="end"
aria-label="expand"
onClick={handleToggle}
sx={{ ml: 1 }}
>
{expanded ? <ExpandLessIcon /> : <ExpandMoreIcon />}
</IconButton>
)}
</ListItemSecondaryAction>
</ListItem>
{hasChildren && (
<Collapse in={expanded} timeout="auto" unmountOnExit>
<List component="div" disablePadding>
{item.items.map((child) => (
<MenuItemComponent
key={child.id}
item={child}
level={level + 1}
onEdit={onEdit}
onDelete={onDelete}
/>
))}
</List>
</Collapse>
)}
</>
);
};
const EditDialog = ({ open, item, onClose, onSave }) => {
const [title, setTitle] = useState(item?.title || '');
useEffect(() => {
setTitle(item?.title || '');
}, [item]);
const handleSave = () => {
onSave(item.id, { title });
onClose();
};
return (
<Dialog open={open} onClose={onClose} maxWidth="sm" fullWidth>
<DialogTitle>Редактировать элемент меню</DialogTitle>
<DialogContent>
<TextField
autoFocus
margin="dense"
label="Название"
fullWidth
variant="outlined"
value={title}
onChange={(e) => setTitle(e.target.value)}
sx={{ mt: 2 }}
/>
</DialogContent>
<DialogActions>
<Button onClick={onClose}>Отмена</Button>
<Button onClick={handleSave} variant="contained">
Сохранить
</Button>
</DialogActions>
</Dialog>
);
};
const MenuEditor = ({ onSave }) => {
const [menuData, setMenuData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [editDialogOpen, setEditDialogOpen] = useState(false);
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [selectedItem, setSelectedItem] = useState(null);
const [hasChanges, setHasChanges] = useState(false);
useEffect(() => {
fetchMenuData();
}, []);
const fetchMenuData = async () => {
try {
setLoading(true);
const response = await axios.get('/api/menu/full');
setMenuData(response.data);
setError(null);
} catch (err) {
setError('Ошибка загрузки меню');
console.error('Error fetching menu:', err);
} finally {
setLoading(false);
}
};
const handleEdit = (item) => {
setSelectedItem(item);
setEditDialogOpen(true);
};
const handleDelete = (item) => {
setSelectedItem(item);
setDeleteDialogOpen(true);
};
const handleEditSave = async (id, updates) => {
try {
await axios.put(`/api/menu/${id}`, updates);
setHasChanges(true);
fetchMenuData();
} catch (err) {
console.error('Error updating menu item:', err);
alert('Ошибка при сохранении изменений');
}
};
const handleDeleteConfirm = async () => {
try {
await axios.delete(`/api/menu/items/${selectedItem.id}`);
setHasChanges(true);
setDeleteDialogOpen(false);
fetchMenuData();
} catch (err) {
console.error('Error deleting menu item:', err);
alert('Ошибка при удалении элемента');
}
};
const handleSave = async () => {
if (hasChanges) {
onSave({
hasChanges: true, saveChanges: async () => {
// Принудительно обновляем кэш
try {
await axios.post('/api/menu/invalidate-cache');
return true;
} catch (err) {
console.error('Error invalidating cache:', err);
return false;
}
}
});
setHasChanges(false);
}
};
if (loading) {
return (
<Box sx={{ display: 'flex', justifyContent: 'center', p: 3 }}>
<CircularProgress />
</Box>
);
}
if (error) {
return (
<Box sx={{ p: 3 }}>
<Typography color="error">{error}</Typography>
</Box>
);
}
return (
<Box>
<Typography variant="h6" gutterBottom>
Редактирование меню
</Typography>
<Typography variant="body2" color="text.secondary" paragraph>
Вы можете редактировать названия и удалять элементы меню. Динамические элементы (помечены синим) нельзя редактировать.
</Typography>
<List>
{menuData.items.map((item) => (
<MenuItemComponent
key={item.id}
item={item}
onEdit={handleEdit}
onDelete={handleDelete}
/>
))}
</List>
<EditDialog
open={editDialogOpen}
item={selectedItem}
onClose={() => setEditDialogOpen(false)}
onSave={handleEditSave}
/>
<Dialog
open={deleteDialogOpen}
onClose={() => setDeleteDialogOpen(false)}
>
<DialogTitle>Подтверждение удаления</DialogTitle>
<DialogContent>
<Typography>
Вы уверены, что хотите удалить элемент "{selectedItem?.title}"?
</Typography>
</DialogContent>
<DialogActions>
<Button onClick={() => setDeleteDialogOpen(false)}>Отмена</Button>
<Button onClick={handleDeleteConfirm} color="error" variant="contained">
Удалить
</Button>
</DialogActions>
</Dialog>
<Box sx={{ mt: 2, display: 'flex', justifyContent: 'flex-end' }}>
<Button
variant="contained"
onClick={handleSave}
disabled={!hasChanges}
>
Применить изменения
</Button>
</Box>
</Box>
);
};
export default MenuEditor;

View File

@ -21,7 +21,6 @@ import CloseIcon from '@mui/icons-material/Close';
import SaveIcon from '@mui/icons-material/Save'; import SaveIcon from '@mui/icons-material/Save';
import MetricRangeEditor from './SettingsComponents/MetricRangeEditor'; import MetricRangeEditor from './SettingsComponents/MetricRangeEditor';
import UserManagement from './SettingsComponents/UserManagement'; import UserManagement from './SettingsComponents/UserManagement';
import MenuEditor from './SettingsComponents/MenuEditor'
const Transition = React.forwardRef(function Transition(props, ref) { const Transition = React.forwardRef(function Transition(props, ref) {
return <Slide direction="up" ref={ref} {...props} />; return <Slide direction="up" ref={ref} {...props} />;
@ -65,10 +64,6 @@ const SettingsModal = ({ open, onClose, onMenuUpdate }) => {
hasChanges: false, hasChanges: false,
save: () => { } save: () => { }
}); });
const [menuEditorState, setMenuEditorState] = useState({
hasChanges: false,
save: () => Promise.resolve(true)
});
const handleTabChange = (event, newValue) => { const handleTabChange = (event, newValue) => {
if (hasChanges) { if (hasChanges) {
@ -78,22 +73,12 @@ const SettingsModal = ({ open, onClose, onMenuUpdate }) => {
} }
}; };
const handleMenuEditorChange = ({ hasChanges, saveChanges }) => {
setMenuEditorState({ hasChanges, save: saveChanges });
setHasChanges(hasChanges);
};
const handleSave = async () => { const handleSave = async () => {
setIsSaving(true); setIsSaving(true);
try { try {
let success = true; let success = true;
if (tabValue === 0 && menuEditorState.hasChanges) {
success = await menuEditorState.save();
}
if (tabValue === 1 && metricEditorState.hasChanges) { if (tabValue === 1 && metricEditorState.hasChanges) {
success = success && await metricEditorState.save(); success = await metricEditorState.save();
} }
if (success) { if (success) {
@ -128,6 +113,7 @@ const SettingsModal = ({ open, onClose, onMenuUpdate }) => {
} }
}; };
// Пример обработчика изменений
const handleSettingChange = () => { const handleSettingChange = () => {
setHasChanges(true); setHasChanges(true);
}; };
@ -163,13 +149,14 @@ const SettingsModal = ({ open, onClose, onMenuUpdate }) => {
<Tab label="Меню" id="settings-tab-0" aria-controls="settings-tabpanel-0" /> <Tab label="Меню" id="settings-tab-0" aria-controls="settings-tabpanel-0" />
<Tab label="Границы метрик" id="settings-tab-1" aria-controls="settings-tabpanel-1" /> <Tab label="Границы метрик" id="settings-tab-1" aria-controls="settings-tabpanel-1" />
<Tab label="Управление пользователями" id="settings-tab-2" aria-controls="settings-tabpanel-2" /> <Tab label="Управление пользователями" id="settings-tab-2" aria-controls="settings-tabpanel-2" />
{/* Добавить новые вкладки здесь */} {/* Добавляйте новые вкладки здесь */}
</Tabs> </Tabs>
</Box> </Box>
<DialogContent dividers> <DialogContent dividers>
<TabPanel value={tabValue} index={0}> <TabPanel value={tabValue} index={0}>
<MenuEditor onSave={handleMenuEditorChange} /> <Typography variant="h6">Настройки меню</Typography>
{/* Добавьте содержимое для вкладки меню */}
</TabPanel> </TabPanel>
<TabPanel value={tabValue} index={1}> <TabPanel value={tabValue} index={1}>

View File

@ -1,4 +1,5 @@
import { useState, useEffect } from "react"; // SidebarMenu.jsx
import React, { useState, useEffect } from "react";
import { import {
Drawer, Drawer,
List, List,
@ -6,30 +7,14 @@ import {
IconButton, IconButton,
Tooltip, Tooltip,
Box, Box,
alpha
} from "@mui/material"; } from "@mui/material";
import MenuItem from "./SidebarMenuComponents/MenuItem";
import SidebarFooter from "./SidebarMenuComponents/SidebarFooter"; import SidebarFooter from "./SidebarMenuComponents/SidebarFooter";
import useSidebarResize from "../hooks/useSidebarResize"; import useSidebarResize from "../hooks/useSidebarResize";
import ChevronLeft from "@mui/icons-material/ChevronLeft"; import ChevronLeft from '@mui/icons-material/ChevronLeft';
import ChevronRight from "@mui/icons-material/ChevronRight"; import ChevronRight from '@mui/icons-material/ChevronRight';
import LogoFull from "../../assets/images/logo.svg?react"; import LogoFull from '../../assets/images/logo.svg?react';
import LogoSmall from "../../assets/images/system_monitor_icon.svg?react"; import LogoSmall from '../../assets/images/system_monitor_icon.svg?react';
import {
DndContext,
closestCenter,
PointerSensor,
useSensor,
useSensors,
DragOverlay,
MeasuringStrategy
} from "@dnd-kit/core";
import {
SortableContext,
verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import SortableMenuItem from "./SidebarMenuComponents/SortableMenuItem";
const SidebarMenu = ({ const SidebarMenu = ({
data, data,
@ -37,385 +22,107 @@ const SidebarMenu = ({
setIsDarkMode, setIsDarkMode,
onSelectItem, onSelectItem,
forceRefreshMenu, forceRefreshMenu,
user, user
}) => { }) => {
const [collapsed, setCollapsed] = useState(false); const [collapsed, setCollapsed] = useState(false);
const { sidebarWidth, startResizing } = useSidebarResize(320); // Увеличил минимальную ширину const { sidebarWidth, startResizing } = useSidebarResize(290);
const [menuItems, setMenuItems] = useState(data.items || []); const [hovered, setHovered] = useState(false);
const [activeItem, setActiveItem] = useState(null);
const [hoveredItem, setHoveredItem] = useState(null);
const [dropIndicator, setDropIndicator] = useState({ show: false, position: null, targetId: null });
const sensors = useSensors(useSensor(PointerSensor, {
activationConstraint: {
distance: 4,
},
}));
useEffect(() => {
const cached = localStorage.getItem("menuTree");
if (cached) {
try {
setMenuItems(JSON.parse(cached));
} catch {
setMenuItems(data.items || []);
}
} else {
setMenuItems(data.items || []);
}
}, [data]);
const handleToggleCollapse = () => { const handleToggleCollapse = () => {
setCollapsed(!collapsed); setCollapsed(!collapsed);
setHoveredItem(null);
}; };
// Функции для работы с деревом (остаются без изменений) const SidebarResizer = styled('div')(({ theme }) => ({
const findItemInTree = (items, id) => { width: '4px',
for (const item of items) { cursor: 'ew-resize',
if (item.id === id) return item; backgroundColor: 'transparent',
if (item.items) { '&:hover': {
const found = findItemInTree(item.items, id); backgroundColor: theme.palette.action.hover,
if (found) return found;
}
}
return null;
};
const removeItemFromTree = (items, id) => {
return items.filter(item => {
if (item.id === id) return false;
if (item.items) {
item.items = removeItemFromTree(item.items, id);
}
return true;
});
};
const addItemToFolder = (items, folderId, newItem) => {
return items.map(item => {
if (item.id === folderId) {
return {
...item,
items: [...(item.items || []), newItem]
};
}
if (item.items) {
return {
...item,
items: addItemToFolder(item.items, folderId, newItem)
};
}
return item;
});
};
const findParent = (items, childId, parent = null) => {
for (const item of items) {
if (item.id === childId) return parent;
if (item.items) {
const found = findParent(item.items, childId, item);
if (found) return found;
}
}
return null;
};
const addItemAtSameLevel = (items, parentId, newItem, afterId = null) => {
return items.map(item => {
if (item.id === parentId) {
const children = item.items || [];
const insertIndex = afterId ? children.findIndex(i => i.id === afterId) + 1 : children.length;
const newChildren = [
...children.slice(0, insertIndex),
newItem,
...children.slice(insertIndex)
];
return { ...item, items: newChildren };
}
if (item.items) {
return { ...item, items: addItemAtSameLevel(item.items, parentId, newItem, afterId) };
}
return item;
});
};
const handleDragStart = (event) => {
const { active } = event;
const item = findItemInTree(menuItems, active.id);
setActiveItem(item);
setDropIndicator({ show: false, position: null, targetId: null });
};
const handleDragEnd = (event) => {
const { active, over } = event;
setActiveItem(null);
setHoveredItem(null);
setDropIndicator({ show: false, position: null, targetId: null });
if (!over) return;
if (active.id === over.id) return;
const draggedItem = findItemInTree(menuItems, active.id);
if (!draggedItem) return;
const overItem = findItemInTree(menuItems, over.id);
// Проверяем, не пытаемся ли переместить элемент в его же потомка
if (isDescendant(draggedItem, overItem)) {
return;
}
let newTree;
if (dropIndicator.position === 'inside' && overItem && Array.isArray(overItem.items)) {
// Вставка внутрь папки
newTree = removeItemFromTree([...menuItems], active.id);
newTree = addItemToFolder(newTree, over.id, draggedItem);
} else {
// Вставка на том же уровне
const overParent = findParent(menuItems, over.id);
if (!overParent) return;
newTree = removeItemFromTree([...menuItems], active.id);
// Определяем позицию для вставки
let insertAfterId = null;
if (dropIndicator.position === 'below') {
insertAfterId = over.id;
} else if (dropIndicator.position === 'above') {
const siblings = overParent.items || [];
const overIndex = siblings.findIndex(item => item.id === over.id);
if (overIndex > 0) {
insertAfterId = siblings[overIndex - 1].id;
}
}
newTree = addItemAtSameLevel(newTree, overParent.id, draggedItem, insertAfterId);
}
setMenuItems(newTree);
localStorage.setItem("menuTree", JSON.stringify(newTree));
};
const handleDragOver = (event) => {
const { active, over } = event;
if (!over) {
setDropIndicator({ show: false, position: null, targetId: null });
return;
}
const overItem = findItemInTree(menuItems, over.id);
const activeItem = findItemInTree(menuItems, active.id);
if (!overItem || !activeItem || active.id === over.id) {
setDropIndicator({ show: false, position: null, targetId: null });
return;
}
// Проверяем, можно ли перемещать элемент
if (isDescendant(activeItem, overItem)) {
setDropIndicator({ show: false, position: null, targetId: null });
return;
}
const overRect = over.rect.current;
if (!overRect) return;
const relativeY = event.delta.y;
const isOverFolder = overItem && Array.isArray(overItem.items);
const isTopHalf = relativeY < overRect.height * 0.4;
const isBottomHalf = relativeY > overRect.height * 0.6;
if (isOverFolder && !isTopHalf && !isBottomHalf) {
// Показываем индикатор для вставки в папку
setDropIndicator({
show: true,
position: 'inside',
targetId: over.id
});
setHoveredItem(over.id);
} else if (isTopHalf) {
// Показываем индикатор для вставки выше
setDropIndicator({
show: true,
position: 'above',
targetId: over.id
});
setHoveredItem(null);
} else if (isBottomHalf) {
// Показываем индикатор для вставки ниже
setDropIndicator({
show: true,
position: 'below',
targetId: over.id
});
setHoveredItem(null);
} else {
setDropIndicator({ show: false, position: null, targetId: null });
setHoveredItem(null);
}
};
const isDescendant = (parent, child) => {
if (!parent || !child || !parent.items) return false;
const checkChildren = (items, targetId) => {
for (const item of items) {
if (item.id === targetId) return true;
if (item.items && checkChildren(item.items, targetId)) return true;
}
return false;
};
return checkChildren(parent.items, child.id);
};
const SidebarResizer = styled("div")(({ theme }) => ({
width: "3px",
cursor: "col-resize",
backgroundColor: alpha(theme.palette.primary.main, 0.3),
"&:hover": {
backgroundColor: theme.palette.primary.main,
}, },
height: "100%", height: '100%',
position: "absolute", position: 'absolute',
top: 0, top: 0,
right: 0, right: 0,
zIndex: 1000, zIndex: 1000,
transition: "background-color 0.2s ease",
})); }));
const DropIndicator = ({ position, targetId }) => {
if (!targetId) return null;
return (
<Box
sx={{
position: 'absolute',
left: 0,
right: 0,
height: '2px',
backgroundColor: 'primary.main',
zIndex: 1001,
...(position === 'above' && { top: 0 }),
...(position === 'below' && { bottom: 0 }),
'&::before': {
content: '""',
position: 'absolute',
top: '-3px',
left: '10%',
width: '80%',
height: '8px',
backgroundColor: 'primary.main',
borderRadius: '2px',
}
}}
/>
);
};
return ( return (
<Box <Box
onMouseEnter={() => setHovered(true)}
onMouseLeave={() => setHovered(false)}
sx={{ sx={{
position: "relative", position: 'relative',
width: collapsed ? 72 : sidebarWidth, width: collapsed ? 64 : sidebarWidth,
transition: "width 0.2s ease", transition: 'width 0.3s ease',
height: "100vh",
}} }}
> >
<Drawer <Drawer
variant="permanent" variant="permanent"
sx={{ sx={{
width: collapsed ? 72 : sidebarWidth, width: collapsed ? 64 : sidebarWidth,
flexShrink: 0, flexShrink: 0,
"& .MuiDrawer-paper": { '& .MuiDrawer-paper': {
width: collapsed ? 72 : sidebarWidth, width: collapsed ? 64 : sidebarWidth,
boxSizing: "border-box", boxSizing: "border-box",
display: "flex", display: "flex",
flexDirection: "column", flexDirection: "column",
backgroundColor: "background.paper", backgroundColor: 'custom.sidebar',
color: "text.primary", color: 'custom.sidebarText',
transition: "width 0.2s ease, background-color 0.2s ease", transition: 'width 0.3s ease',
overflowX: "hidden", overflowX: 'hidden',
borderRight: "1px solid", borderRight: 'none'
borderColor: "divider",
boxShadow: "0 2px 12px rgba(0, 0, 0, 0.08)",
}, },
}} }}
> >
{/* Заголовок с логотипом */} {/* Заголовок с логотипом */}
<Box <Box sx={{
sx={{ display: 'flex',
display: "flex", alignItems: 'center',
alignItems: "center", justifyContent: 'center', // Центрируем содержимое
justifyContent: "center", p: 1,
p: 2, borderBottom: '1px solid',
borderBottom: "1px solid", borderColor: 'divider',
borderColor: "divider", backgroundColor: 'custom.sidebar',
backgroundColor: "background.paper", height: 80, // Фиксированная высота
height: 80, position: 'relative' // Для позиционирования кнопки
position: "relative", }}>
transition: "all 0.2s ease", {/* Логотип (занимает все пространство) */}
minHeight: 80, <Box sx={{
}} display: 'flex',
> alignItems: 'center',
<Box justifyContent: 'center',
sx={{ width: '100%',
display: "flex", height: '100%',
alignItems: "center", '& svg': {
justifyContent: "center", width: '100%',
width: "100%", height: '100%',
height: "100%", padding: collapsed ? '8px' : '12px',
transition: "all 0.2s ease", objectFit: 'contain'
"& svg": { }
width: "auto", }}>
height: "40px", // Фиксированная высота для лого
objectFit: "contain",
transition: "all 0.2s ease",
},
}}
>
{collapsed ? ( {collapsed ? (
<LogoSmall style={{ <LogoSmall style={{
color: "inherit", color: 'inherit' // Наследует цвет темы
filter: "drop-shadow(0 2px 4px rgba(0,0,0,0.1))",
width: "32px",
height: "32px"
}} /> }} />
) : ( ) : (
<LogoFull style={{ <LogoFull style={{
color: "inherit", color: 'inherit' // Наследует цвет темы
filter: "drop-shadow(0 2px 4px rgba(0,0,0,0.1))",
maxWidth: "180px",
height: "40px"
}} /> }} />
)} )}
</Box> </Box>
<Tooltip {/* Кнопка сворачивания (абсолютное позиционирование) */}
title={collapsed ? "Развернуть меню" : "Свернуть меню"} <Tooltip title={collapsed ? "Развернуть меню" : "Свернуть меню"}>
placement="right"
>
<IconButton <IconButton
onClick={handleToggleCollapse} onClick={handleToggleCollapse}
size="small" size="small"
sx={{ sx={{
color: "text.secondary", color: 'custom.sidebarText',
"&:hover": { '&:hover': { backgroundColor: 'custom.sidebarHover' },
backgroundColor: "action.hover", position: 'absolute',
color: "text.primary" right: 8,
}, top: '50%',
position: "absolute", transform: 'translateY(-50%)'
right: 12,
top: "50%",
transform: "translateY(-50%)",
transition: "all 0.2s ease",
width: 32,
height: 32,
}} }}
> >
{collapsed ? <ChevronRight /> : <ChevronLeft />} {collapsed ? <ChevronRight /> : <ChevronLeft />}
@ -424,97 +131,18 @@ const SidebarMenu = ({
</Box> </Box>
{/* Основное содержимое меню */} {/* Основное содержимое меню */}
<Box <Box sx={{ flexGrow: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
sx={{ <List sx={{ overflowY: 'auto', overflowX: 'hidden', flex: '1 1 auto' }}>
flexGrow: 1, {data && (
display: "flex", <MenuItem
flexDirection: "column", item={data}
overflow: "hidden", collapsed={collapsed}
position: "relative", level={0}
}}
>
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
onDragOver={handleDragOver}
measuring={{
droppable: {
strategy: MeasuringStrategy.Always
}
}}
>
<SortableContext items={menuItems.map((i) => i.id)} strategy={verticalListSortingStrategy}>
<List
sx={{
overflowY: "auto",
flex: "1 1 auto",
py: 1,
px: 1,
position: 'relative',
'&::-webkit-scrollbar': {
width: '6px',
},
'&::-webkit-scrollbar-track': {
background: 'transparent',
},
'&::-webkit-scrollbar-thumb': {
background: 'text.disabled',
borderRadius: '3px',
},
'&::-webkit-scrollbar-thumb:hover': {
background: 'text.secondary',
},
}}
>
{menuItems.map((item) => (
<Box key={item.id} position="relative">
{dropIndicator.show && dropIndicator.targetId === item.id &&
dropIndicator.position !== 'inside' && (
<DropIndicator
position={dropIndicator.position}
targetId={dropIndicator.targetId}
/>
)}
<SortableMenuItem
item={item}
collapsed={collapsed}
onSelectItem={onSelectItem}
isHovered={hoveredItem === item.id}
showDropIndicator={dropIndicator.show && dropIndicator.targetId === item.id && dropIndicator.position === 'inside'}
sidebarWidth={sidebarWidth}
/>
</Box>
))}
</List>
</SortableContext>
<DragOverlay> onSelectItem={onSelectItem}
{activeItem ? ( />
<Box )}
sx={{ </List>
backgroundColor: 'primary.main',
color: 'white',
padding: '8px 12px',
borderRadius: '8px',
boxShadow: '0 4px 20px rgba(0, 0, 0, 0.15)',
maxWidth: 250,
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
fontSize: '0.875rem',
fontWeight: 500,
backdropFilter: 'blur(10px)',
border: '1px solid rgba(255, 255, 255, 0.1)',
transform: 'rotate(5deg)',
}}
>
{activeItem.title}
</Box>
) : null}
</DragOverlay>
</DndContext>
<SidebarFooter <SidebarFooter
collapsed={collapsed} collapsed={collapsed}
@ -524,11 +152,8 @@ const SidebarMenu = ({
user={user} user={user}
/> />
</Box> </Box>
{!collapsed && ( {!collapsed && (
<Tooltip title="Изменить ширину" placement="top"> <SidebarResizer onMouseDown={startResizing} />
<SidebarResizer onMouseDown={startResizing} />
</Tooltip>
)} )}
</Drawer> </Drawer>
</Box> </Box>

View File

@ -1,121 +1,121 @@
// // MenuItem.jsx // MenuItem.jsx
// import React, { useState } from "react"; import React, { useState } from "react";
// import { import {
// ListItem, ListItem,
// ListItemIcon, ListItemIcon,
// ListItemText, ListItemText,
// Collapse, Collapse,
// List, List,
// styled, styled,
// Menu, Menu,
// MenuItem as MuiMenuItem MenuItem as MuiMenuItem
// } from "@mui/material"; } from "@mui/material";
// import { ExpandLess, ExpandMore, Folder, FolderOpen } from "@mui/icons-material"; import { ExpandLess, ExpandMore, Folder, FolderOpen } from "@mui/icons-material";
// import StatusIndicator from "./StatusIndicator"; import StatusIndicator from "./StatusIndicator";
// const StyledListItem = styled(ListItem)(({ theme, level }) => ({ const StyledListItem = styled(ListItem)(({ theme, level }) => ({
// cursor: "pointer", cursor: "pointer",
// paddingLeft: theme.spacing(2 + level * 2), paddingLeft: theme.spacing(2 + level * 2),
// position: 'relative', position: 'relative',
// '&:hover': { '&:hover': {
// backgroundColor: theme.palette.action.hover, backgroundColor: theme.palette.action.hover,
// }, },
// '&.Mui-selected': { '&.Mui-selected': {
// backgroundColor: theme.palette.custom.sidebarHover, backgroundColor: theme.palette.custom.sidebarHover,
// }, },
// })); }));
// const MenuItem = ({ item, onSelectItem, level = 0, collapsed, onEdit }) => { const MenuItem = ({ item, onSelectItem, level = 0, collapsed, onEdit }) => {
// const [isOpen, setIsOpen] = useState(false); const [isOpen, setIsOpen] = useState(false);
// const [contextMenu, setContextMenu] = useState(null); const [contextMenu, setContextMenu] = useState(null);
// const hasChildren = Array.isArray(item.items) && item.items.length > 0; const hasChildren = Array.isArray(item.items) && item.items.length > 0;
// const handleContextMenu = (e) => { const handleContextMenu = (e) => {
// e.preventDefault(); e.preventDefault();
// setContextMenu( setContextMenu(
// contextMenu === null contextMenu === null
// ? { mouseX: e.clientX - 2, mouseY: e.clientY - 4 } ? { mouseX: e.clientX - 2, mouseY: e.clientY - 4 }
// : null : null
// ); );
// }; };
// const handleCloseContextMenu = () => { const handleCloseContextMenu = () => {
// setContextMenu(null); setContextMenu(null);
// }; };
// const handleToggle = (e) => { const handleToggle = (e) => {
// e.stopPropagation(); e.stopPropagation();
// setIsOpen(!isOpen); setIsOpen(!isOpen);
// }; };
// const handleClick = () => { const handleClick = () => {
// if (onSelectItem) { if (onSelectItem) {
// onSelectItem(item); onSelectItem(item);
// } }
// }; };
// return ( return (
// <> <>
// <StyledListItem <StyledListItem
// component="div" component="div"
// onClick={hasChildren ? handleToggle : handleClick} onClick={hasChildren ? handleToggle : handleClick}
// onContextMenu={handleContextMenu} onContextMenu={handleContextMenu}
// level={level} level={level}
// sx={{ sx={{
// pl: collapsed ? 2 : 2 + level * 2, pl: collapsed ? 2 : 2 + level * 2,
// justifyContent: collapsed ? 'center' : 'flex-start', justifyContent: collapsed ? 'center' : 'flex-start',
// }} }}
// > >
// {!collapsed && <StatusIndicator status={item.status} />} {!collapsed && <StatusIndicator status={item.status} />}
// <ListItemIcon sx={{ minWidth: collapsed ? 'auto' : 56 }}> <ListItemIcon sx={{ minWidth: collapsed ? 'auto' : 56 }}>
// {hasChildren ? (isOpen ? <FolderOpen /> : <Folder />) : <Folder />} {hasChildren ? (isOpen ? <FolderOpen /> : <Folder />) : <Folder />}
// </ListItemIcon> </ListItemIcon>
// {!collapsed && ( {!collapsed && (
// <> <>
// <ListItemText <ListItemText
// primary={item.title} primary={item.title}
// primaryTypographyProps={{ primaryTypographyProps={{
// color: 'custom.sidebarText' color: 'custom.sidebarText'
// }} }}
// /> />
// {hasChildren && (isOpen ? <ExpandLess /> : <ExpandMore />)} {hasChildren && (isOpen ? <ExpandLess /> : <ExpandMore />)}
// </> </>
// )} )}
// </StyledListItem> </StyledListItem>
// <Menu <Menu
// open={contextMenu !== null} open={contextMenu !== null}
// onClose={handleCloseContextMenu} onClose={handleCloseContextMenu}
// anchorReference="anchorPosition" anchorReference="anchorPosition"
// anchorPosition={ anchorPosition={
// contextMenu !== null contextMenu !== null
// ? { top: contextMenu.mouseY, left: contextMenu.mouseX } ? { top: contextMenu.mouseY, left: contextMenu.mouseX }
// : undefined : undefined
// } }
// > >
// </Menu> </Menu>
// {hasChildren && !collapsed && ( {hasChildren && !collapsed && (
// <Collapse in={isOpen} timeout="auto" unmountOnExit> <Collapse in={isOpen} timeout="auto" unmountOnExit>
// <List component="div" disablePadding> <List component="div" disablePadding>
// {item.items.map((child, index) => ( {item.items.map((child, index) => (
// <MenuItem <MenuItem
// key={child.id ?? index} key={child.id ?? index}
// item={child} item={child}
// onSelectItem={onSelectItem} onSelectItem={onSelectItem}
// onEdit={onEdit} onEdit={onEdit}
// level={level + 1} level={level + 1}
// collapsed={collapsed} collapsed={collapsed}
// /> />
// ))} ))}
// </List> </List>
// </Collapse> </Collapse>
// )} )}
// </> </>
// ); );
// }; };
// export default MenuItem; export default MenuItem;

View File

@ -1,24 +1,20 @@
import React, { useState } from "react"; import React, { useState } from "react";
import { Brightness4, Brightness7, Settings, Help } from "@mui/icons-material"; import { Brightness4, Brightness7 } from "@mui/icons-material";
import { import { IconButton, Tooltip } from "@mui/material";
IconButton,
Tooltip,
Box,
Button,
alpha
} from "@mui/material";
import { import {
List, List,
ListItem, ListItem,
ListItemText, ListItemText,
styled, styled,
Switch, Switch,
Box,
Button
} from "@mui/material"; } from "@mui/material";
import SettingsModal from "../SettingsModal"; import SettingsModal from "../SettingsModal";
import { RoleBasedRender } from "../../UI/RoleBasedRender"; import { RoleBasedRender } from "../../UI/RoleBasedRender";
const FooterList = styled(List)(({ theme }) => ({ const FooterList = styled(List)(({ theme }) => ({
backgroundColor: 'background.paper', backgroundColor: theme.palette.custom.sidebar,
padding: theme.spacing(1, 0), padding: theme.spacing(1, 0),
borderTop: `1px solid ${theme.palette.divider}`, borderTop: `1px solid ${theme.palette.divider}`,
marginTop: 'auto' marginTop: 'auto'
@ -26,15 +22,12 @@ const FooterList = styled(List)(({ theme }) => ({
const FooterListItem = styled(ListItem)(({ theme }) => ({ const FooterListItem = styled(ListItem)(({ theme }) => ({
'&:hover': { '&:hover': {
backgroundColor: alpha(theme.palette.action.hover, 0.4), backgroundColor: theme.palette.custom.sidebarHover,
}, },
padding: theme.spacing(1, 2), padding: theme.spacing(1, 2),
display: 'flex', display: 'flex',
justifyContent: 'space-between', justifyContent: 'space-between',
alignItems: 'center', alignItems: 'center'
borderRadius: '8px',
margin: '0 8px 4px',
transition: 'all 0.2s ease',
})); }));
const SidebarFooter = ({ const SidebarFooter = ({
@ -53,93 +46,72 @@ const SidebarFooter = ({
const handleSettingsClose = () => { const handleSettingsClose = () => {
setSettingsOpen(false); setSettingsOpen(false);
}; };
/*console.log('SidebarFooter user with role:', {
...user,
hasRole: 'role' in user,
roleValue: user?.role
}); */
return ( return (
<> <>
<FooterList> <FooterList>
{!collapsed ? ( {!collapsed && (
<> <FooterListItem button>
<FooterListItem> <ListItemText
<Button primary="Помощь"
onClick={handleSettingsOpen} primaryTypographyProps={{
startIcon={<Settings />} color: 'custom.sidebarText',
sx={{ variant: 'body2'
color: 'text.secondary', }}
textTransform: 'none', />
fontSize: '0.875rem',
fontWeight: 500,
'&:hover': {
color: 'text.primary',
backgroundColor: 'transparent'
}
}}
>
Настройки
</Button>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Tooltip title="Переключить тему">
<IconButton
size="small"
onClick={() => setIsDarkMode(!isDarkMode)}
sx={{
color: 'text.secondary',
'&:hover': {
color: 'text.primary',
backgroundColor: alpha('#000000', 0.1)
}
}}
>
{isDarkMode ? <Brightness4 /> : <Brightness7 />}
</IconButton>
</Tooltip>
<Switch
checked={isDarkMode}
onChange={() => setIsDarkMode(!isDarkMode)}
size="small"
color="primary"
/>
</Box>
</FooterListItem>
<FooterListItem button>
<Button
startIcon={<Help />}
sx={{
color: 'text.secondary',
textTransform: 'none',
fontSize: '0.875rem',
fontWeight: 500,
'&:hover': {
color: 'text.primary',
backgroundColor: 'transparent'
}
}}
>
Помощь
</Button>
</FooterListItem>
</>
) : (
<FooterListItem sx={{ justifyContent: 'center' }}>
<Tooltip title="Настройки" placement="right">
<IconButton
onClick={handleSettingsOpen}
sx={{
color: 'text.secondary',
'&:hover': {
color: 'text.primary',
backgroundColor: alpha('#000000', 0.1)
}
}}
>
<Settings />
</IconButton>
</Tooltip>
</FooterListItem> </FooterListItem>
)} )}
<FooterListItem>
{/* кнопка настроек */}
<RoleBasedRender user={user} allowedRoles={['admin']}>
{!collapsed && (
<Button
onClick={handleSettingsOpen}
sx={{
color: 'custom.sidebarText',
textTransform: 'none',
minWidth: 0,
padding: 0,
marginRight: 'auto'
}}
>
<ListItemText
primary="Настройки"
primaryTypographyProps={{
color: 'custom.sidebarText',
variant: 'body2'
}}
/>
</Button>
)}
</RoleBasedRender>
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Tooltip title="Переключить тему">
<IconButton
size="small"
onClick={() => setIsDarkMode(!isDarkMode)}
sx={{ color: 'custom.sidebarText' }}
>
{isDarkMode ? <Brightness4 /> : <Brightness7 />}
</IconButton>
</Tooltip>
{!collapsed && (
<Switch
checked={isDarkMode}
onChange={() => setIsDarkMode(!isDarkMode)}
size="small"
/>
)}
</Box>
</FooterListItem>
</FooterList> </FooterList>
{/* Используем RoleBasedRender для модального окна */}
<RoleBasedRender user={user} allowedRoles={['admin']}> <RoleBasedRender user={user} allowedRoles={['admin']}>
<SettingsModal <SettingsModal
open={settingsOpen} open={settingsOpen}

View File

@ -1,222 +0,0 @@
import { useState } from "react";
import {
ListItem,
ListItemIcon,
ListItemText,
Collapse,
List,
IconButton,
Box,
alpha,
Typography,
Tooltip
} from "@mui/material";
import { ChevronRight, DragIndicator, Folder, FolderOpen } from "@mui/icons-material";
import { useSortable } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
const SortableMenuItem = ({
item,
collapsed,
onSelectItem,
level = 0,
isHovered = false,
showDropIndicator = false,
sidebarWidth = 300
}) => {
const [isOpen, setIsOpen] = useState(false);
const [isLocalHovered, setIsLocalHovered] = useState(false);
const {
attributes,
listeners,
setNodeRef,
transform,
transition,
isDragging,
isOver
} = useSortable({
id: item.id,
data: {
type: 'menu-item',
item,
level
}
});
const style = {
transform: CSS.Transform.toString(transform),
transition: transition || 'all 0.2s ease',
opacity: isDragging ? 0.6 : 1,
zIndex: isDragging ? 1000 : 1,
};
const hasChildren = Array.isArray(item.items) && item.items.length > 0;
const isFolder = hasChildren;
const isHighlighted = isHovered || isOver;
// Рассчитываем максимальную ширину текста в зависимости от уровня вложенности
const calculateMaxTextWidth = () => {
const baseWidth = sidebarWidth - 40; // Отступы и иконки
const levelOffset = level * 24; // Отступ для каждого уровня
return baseWidth - levelOffset - 60; // Оставляем место для иконок и отступов
};
const handleClick = (e) => {
e.stopPropagation();
if (hasChildren) {
setIsOpen(!isOpen);
} else {
onSelectItem?.(item);
}
};
const handleMouseEnter = () => {
setIsLocalHovered(true);
};
const handleMouseLeave = () => {
setIsLocalHovered(false);
};
const getBackgroundColor = (theme) => {
if (isDragging) return alpha(theme.palette.primary.main, 0.1);
if (isHighlighted) return alpha(theme.palette.primary.main, 0.08);
if (isLocalHovered) return alpha(theme.palette.action.hover, 0.4);
return 'transparent';
};
return (
<Box
ref={setNodeRef}
style={style}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
sx={{
position: 'relative',
'&::before': isHighlighted ? {
content: '""',
position: 'absolute',
left: 0,
top: 4,
bottom: 4,
width: 3,
backgroundColor: 'primary.main',
borderRadius: '0 2px 2px 0',
} : {},
...(showDropIndicator && {
backgroundColor: (theme) => alpha(theme.palette.primary.main, 0.1),
border: (theme) => `2px dashed ${theme.palette.primary.main}`,
borderRadius: '8px',
})
}}
>
<ListItem
button
sx={{
pl: collapsed ? 1 : Math.max(0.1, 0.1 + level * 0.1),
pr: 0.5,
py: 0.25,
minHeight: 32,
justifyContent: collapsed ? "center" : "flex-start",
backgroundColor: (theme) => getBackgroundColor(theme),
borderRadius: '6px',
margin: '1px 4px',
transition: 'all 0.2s ease',
}}
onClick={handleClick}
>
{!collapsed && (
<IconButton
{...attributes}
{...listeners}
size="small"
sx={{
cursor: isDragging ? "grabbing" : "grab",
mr: 1,
opacity: isLocalHovered || isDragging ? 1 : 0.4,
color: 'text.secondary',
'&:hover': {
color: 'text.primary',
backgroundColor: 'transparent'
},
flexShrink: 0
}}
>
<DragIndicator fontSize="small" />
</IconButton>
)}
{!collapsed && (
<>
<Tooltip title={item.title} placement="right" enterDelay={400} arrow>
<ListItemText
primary={
<Typography
variant="body2"
sx={{
fontWeight: isFolder ? 600 : 400,
color: isFolder ? 'text.primary' : 'text.secondary',
maxWidth: calculateMaxTextWidth(),
display: "-webkit-box",
WebkitLineClamp: 2, // максимум 2 строки
WebkitBoxOrient: "vertical",
overflow: "hidden",
lineHeight: 1.2,
fontSize: "0.85rem", // компактнее текст
}}
>
{item.title}
</Typography>
}
sx={{ mr: 0.5, flex: '1 1 auto', minWidth: 0 }}
/>
</Tooltip>
{hasChildren && (
<ChevronRight
sx={{
fontSize: 18,
color: 'text.disabled',
transform: isOpen ? 'rotate(90deg)' : 'none',
transition: 'transform 0.2s ease',
flexShrink: 0,
}}
/>
)}
</>
)}
</ListItem>
{hasChildren && !collapsed && (
<Collapse in={isOpen} timeout="auto" unmountOnExit>
<List
disablePadding
sx={{
pl: 1.5,
borderLeft: (theme) => `1px solid ${alpha(theme.palette.divider, 0.1)}`,
marginLeft: 2,
position: 'relative',
}}
>
{item.items.map((child) => (
<Box key={child.id} position="relative">
<SortableMenuItem
item={child}
collapsed={collapsed}
onSelectItem={onSelectItem}
level={level + 1}
isHovered={isHovered}
showDropIndicator={showDropIndicator}
sidebarWidth={sidebarWidth}
/>
</Box>
))}
</List>
</Collapse>
)}
</Box>
);
};
export default SortableMenuItem;

View File

@ -14,12 +14,13 @@ export default defineConfig({
rewrite: (path) => path.replace(/^\/ai-api/, ''), rewrite: (path) => path.replace(/^\/ai-api/, ''),
}, },
'/metrics-ws': { '/metrics-ws': {
target: 'ws://192.168.2.39:3001', target: 'ws://localhost:3001',
ws: true, ws: true,
changeOrigin: true, changeOrigin: true,
}, },
'/api': { '/api': {
target: 'http://192.168.2.39:3000', target: 'http://localhost:3000',
ws: true,
changeOrigin: true, changeOrigin: true,
bypass(req, res, options) { bypass(req, res, options) {
console.log('Proxying request:', req.url); console.log('Proxying request:', req.url);