u
This commit is contained in:
201
uiserver/src/components/Chart.js
vendored
201
uiserver/src/components/Chart.js
vendored
@@ -1,23 +1,50 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import React, { Component } from 'react';
|
||||
import { Paper, Typography, Box, CircularProgress } from '@mui/material';
|
||||
import { LineChart } from '@mui/x-charts/LineChart';
|
||||
import { useTheme } from '@mui/material/styles';
|
||||
|
||||
export default function Chart({ selectedChannels = [], channelConfig = null, axisConfig = null }) {
|
||||
const [data, setData] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const theme = useTheme();
|
||||
export default class Chart extends Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {
|
||||
data: [],
|
||||
loading: true
|
||||
};
|
||||
this.intervalId = null;
|
||||
}
|
||||
|
||||
// Determine effective channels list
|
||||
const effectiveChannels = channelConfig
|
||||
? channelConfig.map(c => c.id)
|
||||
: selectedChannels;
|
||||
componentDidMount() {
|
||||
this.fetchData();
|
||||
this.intervalId = setInterval(this.fetchData, 60000);
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps) {
|
||||
// Compare props to see if we need to refetch
|
||||
const prevEffective = this.getEffectiveChannels(prevProps);
|
||||
const currEffective = this.getEffectiveChannels(this.props);
|
||||
|
||||
if (prevEffective.join(',') !== currEffective.join(',')) {
|
||||
this.fetchData();
|
||||
}
|
||||
}
|
||||
|
||||
componentWillUnmount() {
|
||||
if (this.intervalId) {
|
||||
clearInterval(this.intervalId);
|
||||
}
|
||||
}
|
||||
|
||||
getEffectiveChannels(props) {
|
||||
return props.channelConfig
|
||||
? props.channelConfig.map(c => c.id)
|
||||
: props.selectedChannels;
|
||||
}
|
||||
|
||||
fetchData = () => {
|
||||
const effectiveChannels = this.getEffectiveChannels(this.props);
|
||||
|
||||
const fetchData = () => {
|
||||
// Only fetch if selection exists
|
||||
if (effectiveChannels.length === 0) {
|
||||
setData([]);
|
||||
setLoading(false);
|
||||
this.setState({ data: [], loading: false });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -47,48 +74,15 @@ export default function Chart({ selectedChannels = [], channelConfig = null, axi
|
||||
});
|
||||
|
||||
const sortedData = Array.from(timeMap.values()).sort((a, b) => a.time - b.time);
|
||||
setData(sortedData);
|
||||
setLoading(false);
|
||||
this.setState({ data: sortedData, loading: false });
|
||||
})
|
||||
.catch(err => {
|
||||
console.error("Failed to fetch data", err);
|
||||
setLoading(false);
|
||||
this.setState({ loading: false });
|
||||
});
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
const interval = setInterval(fetchData, 60000);
|
||||
return () => clearInterval(interval);
|
||||
}, [selectedChannels, channelConfig]);
|
||||
|
||||
if (loading) return <Box sx={{ display: 'flex', justifyContent: 'center', p: 4 }}><CircularProgress /></Box>;
|
||||
if (effectiveChannels.length === 0) return <Box sx={{ p: 4 }}><Typography>No channels selected.</Typography></Box>;
|
||||
|
||||
const series = effectiveChannels.map(id => {
|
||||
// Find alias and axis if config exists
|
||||
let label = id;
|
||||
let yAxisKey = 'left';
|
||||
if (channelConfig) {
|
||||
const item = channelConfig.find(c => c.id === id);
|
||||
if (item) {
|
||||
if (item.alias) label = item.alias;
|
||||
if (item.yAxis) yAxisKey = item.yAxis;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
dataKey: id,
|
||||
label: label,
|
||||
connectNulls: true,
|
||||
showMark: false,
|
||||
yAxisKey: yAxisKey,
|
||||
};
|
||||
});
|
||||
|
||||
const hasRightAxis = series.some(s => s.yAxisKey === 'right');
|
||||
|
||||
const computeAxisLimits = (axisKey) => {
|
||||
computeAxisLimits(axisKey, effectiveChannels, series) {
|
||||
// Collect all data points for this axis
|
||||
let axisMin = Infinity;
|
||||
let axisMax = -Infinity;
|
||||
@@ -98,6 +92,7 @@ export default function Chart({ selectedChannels = [], channelConfig = null, axi
|
||||
if (axisSeries.length === 0) return {}; // No data for this axis
|
||||
|
||||
// Check if config exists for this axis
|
||||
const { axisConfig } = this.props;
|
||||
let cfgMin = NaN;
|
||||
let cfgMax = NaN;
|
||||
if (axisConfig && axisConfig[axisKey]) {
|
||||
@@ -110,7 +105,7 @@ export default function Chart({ selectedChannels = [], channelConfig = null, axi
|
||||
|
||||
// Calculate data bounds
|
||||
let hasData = false;
|
||||
data.forEach(row => {
|
||||
this.state.data.forEach(row => {
|
||||
axisSeries.forEach(key => {
|
||||
const val = row[key];
|
||||
if (val !== null && val !== undefined) {
|
||||
@@ -128,43 +123,75 @@ export default function Chart({ selectedChannels = [], channelConfig = null, axi
|
||||
if (!isNaN(cfgMax)) axisMax = Math.max(axisMax, cfgMax);
|
||||
|
||||
return { min: axisMin, max: axisMax };
|
||||
};
|
||||
|
||||
const leftLimits = computeAxisLimits('left');
|
||||
const rightLimits = computeAxisLimits('right');
|
||||
|
||||
const yAxes = [
|
||||
{ id: 'left', scaleType: 'linear', ...leftLimits }
|
||||
];
|
||||
if (hasRightAxis) {
|
||||
yAxes.push({ id: 'right', scaleType: 'linear', ...rightLimits });
|
||||
}
|
||||
|
||||
return (
|
||||
<Box sx={{ width: '100%', height: '80vh', p: 2 }}>
|
||||
<Typography variant="h6" gutterBottom>Last 24 Hours</Typography>
|
||||
<Paper sx={{ p: 2, height: '100%', display: 'flex', flexDirection: 'column' }}>
|
||||
<Box sx={{ flexGrow: 1 }}>
|
||||
<LineChart
|
||||
dataset={data}
|
||||
series={series}
|
||||
xAxis={[{
|
||||
dataKey: 'time',
|
||||
scaleType: 'time',
|
||||
valueFormatter: (date) => date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
|
||||
}]}
|
||||
yAxis={yAxes}
|
||||
rightAxis={hasRightAxis ? 'right' : null}
|
||||
slotProps={{
|
||||
legend: {
|
||||
direction: 'row',
|
||||
position: { vertical: 'top', horizontal: 'middle' },
|
||||
padding: 0,
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
</Paper>
|
||||
</Box>
|
||||
);
|
||||
render() {
|
||||
const { loading, data } = this.state;
|
||||
const { channelConfig } = this.props;
|
||||
const effectiveChannels = this.getEffectiveChannels(this.props);
|
||||
|
||||
if (loading) return <Box sx={{ display: 'flex', justifyContent: 'center', p: 4 }}><CircularProgress /></Box>;
|
||||
if (effectiveChannels.length === 0) return <Box sx={{ p: 4 }}><Typography>No channels selected.</Typography></Box>;
|
||||
|
||||
const series = effectiveChannels.map(id => {
|
||||
// Find alias and axis if config exists
|
||||
let label = id;
|
||||
let yAxisKey = 'left';
|
||||
if (channelConfig) {
|
||||
const item = channelConfig.find(c => c.id === id);
|
||||
if (item) {
|
||||
if (item.alias) label = item.alias;
|
||||
if (item.yAxis) yAxisKey = item.yAxis;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
dataKey: id,
|
||||
label: label,
|
||||
connectNulls: true,
|
||||
showMark: false,
|
||||
yAxisKey: yAxisKey,
|
||||
};
|
||||
});
|
||||
|
||||
const hasRightAxis = series.some(s => s.yAxisKey === 'right');
|
||||
|
||||
const leftLimits = this.computeAxisLimits('left', effectiveChannels, series);
|
||||
const rightLimits = this.computeAxisLimits('right', effectiveChannels, series);
|
||||
|
||||
const yAxes = [
|
||||
{ id: 'left', scaleType: 'linear', ...leftLimits }
|
||||
];
|
||||
if (hasRightAxis) {
|
||||
yAxes.push({ id: 'right', scaleType: 'linear', ...rightLimits });
|
||||
}
|
||||
|
||||
return (
|
||||
<Box sx={{ width: '100%', height: '80vh', p: 2 }}>
|
||||
<Typography variant="h6" gutterBottom>Last 24 Hours</Typography>
|
||||
<Paper sx={{ p: 2, height: '100%', display: 'flex', flexDirection: 'column' }}>
|
||||
<Box sx={{ flexGrow: 1 }}>
|
||||
<LineChart
|
||||
dataset={data}
|
||||
series={series}
|
||||
xAxis={[{
|
||||
dataKey: 'time',
|
||||
scaleType: 'time',
|
||||
valueFormatter: (date) => date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
|
||||
}]}
|
||||
yAxis={yAxes}
|
||||
rightAxis={hasRightAxis ? 'right' : null}
|
||||
slotProps={{
|
||||
legend: {
|
||||
direction: 'row',
|
||||
position: { vertical: 'top', horizontal: 'middle' },
|
||||
padding: 0,
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
</Paper>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +1,21 @@
|
||||
import React, { useState } from 'react';
|
||||
import {
|
||||
Paper, TextField, Button, Typography, Container, Alert
|
||||
} from '@mui/material';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import React, { Component } from 'react';
|
||||
import { Container, Paper, TextField, Button, Typography, Box } from '@mui/material';
|
||||
import { withRouter } from './withRouter';
|
||||
|
||||
export default function Login({ onLogin }) {
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const navigate = useNavigate();
|
||||
class Login extends Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {
|
||||
username: '',
|
||||
password: '',
|
||||
error: ''
|
||||
};
|
||||
}
|
||||
|
||||
const handleSubmit = async (e) => {
|
||||
handleSubmit = async (e) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
const { username, password } = this.state;
|
||||
const { onLogin, router } = this.props;
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/login', {
|
||||
@@ -20,45 +23,53 @@ export default function Login({ onLogin }) {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username, password })
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(data.error || 'Login failed');
|
||||
if (res.ok) {
|
||||
onLogin(data);
|
||||
router.navigate('/');
|
||||
} else {
|
||||
this.setState({ error: data.error || 'Login failed' });
|
||||
}
|
||||
|
||||
onLogin(data); // { token, role, username }
|
||||
navigate('/');
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
this.setState({ error: 'Network error' });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Container maxWidth="xs" sx={{ mt: 8 }}>
|
||||
<Paper sx={{ p: 4, display: 'flex', flexDirection: 'column', gap: 2 }}>
|
||||
<Typography variant="h5" align="center">Login</Typography>
|
||||
{error && <Alert severity="error">{error}</Alert>}
|
||||
render() {
|
||||
const { username, password, error } = this.state;
|
||||
|
||||
<form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
|
||||
<TextField
|
||||
label="Username"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
fullWidth
|
||||
/>
|
||||
<TextField
|
||||
label="Password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
fullWidth
|
||||
/>
|
||||
<Button type="submit" variant="contained" color="primary" fullWidth>
|
||||
Sign In
|
||||
</Button>
|
||||
</form>
|
||||
</Paper>
|
||||
</Container>
|
||||
);
|
||||
return (
|
||||
<Container maxWidth="xs" sx={{ mt: 8 }}>
|
||||
<Paper sx={{ p: 4, display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
|
||||
<Typography variant="h5" gutterBottom>Login</Typography>
|
||||
{error && <Typography color="error">{error}</Typography>}
|
||||
<Box component="form" onSubmit={this.handleSubmit} sx={{ mt: 1, width: '100%' }}>
|
||||
<TextField
|
||||
margin="normal"
|
||||
required
|
||||
fullWidth
|
||||
label="Username"
|
||||
value={username}
|
||||
onChange={(e) => this.setState({ username: e.target.value })}
|
||||
/>
|
||||
<TextField
|
||||
margin="normal"
|
||||
required
|
||||
fullWidth
|
||||
label="Password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => this.setState({ password: e.target.value })}
|
||||
/>
|
||||
<Button type="submit" fullWidth variant="contained" sx={{ mt: 3, mb: 2 }}>
|
||||
Sign In
|
||||
</Button>
|
||||
</Box>
|
||||
</Paper>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default withRouter(Login);
|
||||
|
||||
@@ -1,71 +1,62 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import {
|
||||
List, ListItem, ListItemIcon, ListItemText, ListItemSecondaryAction,
|
||||
Switch, Paper, Typography, CircularProgress, Container
|
||||
} from '@mui/material';
|
||||
import SensorsIcon from '@mui/icons-material/Sensors';
|
||||
import React, { Component } from 'react';
|
||||
import { Container, Typography, List, ListItem, ListItemText, Switch, CircularProgress } from '@mui/material';
|
||||
|
||||
export default function Settings({ selectedChannels, onToggleChannel }) {
|
||||
const [devices, setDevices] = useState([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
export default class Settings extends Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {
|
||||
devices: [],
|
||||
loading: true
|
||||
};
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
componentDidMount() {
|
||||
fetch('/api/devices')
|
||||
.then(res => {
|
||||
if (!res.ok) throw new Error('Failed to load devices');
|
||||
return res.json();
|
||||
})
|
||||
.then(data => {
|
||||
setDevices(data);
|
||||
setLoading(false);
|
||||
})
|
||||
.then(res => res.json())
|
||||
.then(data => this.setState({ devices: data, loading: false }))
|
||||
.catch(err => {
|
||||
setError(err.message);
|
||||
setLoading(false);
|
||||
console.error("Failed to fetch devices", err);
|
||||
this.setState({ loading: false });
|
||||
});
|
||||
}, []);
|
||||
}
|
||||
|
||||
if (loading) return <Container sx={{ mt: 4, textAlign: 'center' }}><CircularProgress /></Container>;
|
||||
if (error) return <Container sx={{ mt: 4 }}><Typography color="error">Error: {error}</Typography></Container>;
|
||||
toggleChannel = (id) => {
|
||||
// Toggle selection
|
||||
// We need to notify parent component about change (onSelectionChange)
|
||||
const { selectedChannels, onSelectionChange } = this.props;
|
||||
const newSelection = selectedChannels.includes(id)
|
||||
? selectedChannels.filter(c => c !== id)
|
||||
: [...selectedChannels, id];
|
||||
|
||||
return (
|
||||
<Container maxWidth="md" sx={{ mt: 4 }}>
|
||||
<Typography variant="h4" gutterBottom>
|
||||
Channel Selection
|
||||
</Typography>
|
||||
<Paper>
|
||||
onSelectionChange(newSelection);
|
||||
};
|
||||
|
||||
render() {
|
||||
const { loading, devices } = this.state;
|
||||
const { selectedChannels } = this.props;
|
||||
|
||||
if (loading) return <Container sx={{ mt: 4, textAlign: 'center' }}><CircularProgress /></Container>;
|
||||
|
||||
return (
|
||||
<Container maxWidth="md" sx={{ mt: 4 }}>
|
||||
<Typography variant="h4" gutterBottom>Settings</Typography>
|
||||
<Typography variant="subtitle1" gutterBottom>Select Channels for Live View</Typography>
|
||||
<List>
|
||||
{devices.map((device, index) => {
|
||||
const id = `${device.device}:${device.channel}`;
|
||||
const isSelected = selectedChannels.includes(id);
|
||||
|
||||
{devices.map((item, idx) => {
|
||||
const id = `${item.device}:${item.channel}`;
|
||||
return (
|
||||
<ListItem key={id} divider={index !== devices.length - 1}>
|
||||
<ListItemIcon>
|
||||
<SensorsIcon />
|
||||
</ListItemIcon>
|
||||
<ListItemText
|
||||
primary={device.channel}
|
||||
secondary={`Device: ${device.device}`}
|
||||
<ListItem key={idx}>
|
||||
<ListItemText primary={`${item.device} - ${item.channel}`} />
|
||||
<Switch
|
||||
edge="end"
|
||||
checked={selectedChannels.includes(id)}
|
||||
onChange={() => this.toggleChannel(id)}
|
||||
/>
|
||||
<ListItemSecondaryAction>
|
||||
<Switch
|
||||
edge="end"
|
||||
checked={isSelected}
|
||||
onChange={() => onToggleChannel(id)}
|
||||
/>
|
||||
</ListItemSecondaryAction>
|
||||
</ListItem>
|
||||
);
|
||||
})}
|
||||
{devices.length === 0 && (
|
||||
<ListItem>
|
||||
<ListItemText primary="No devices found in database" />
|
||||
</ListItem>
|
||||
)}
|
||||
</List>
|
||||
</Paper>
|
||||
</Container>
|
||||
);
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,57 +1,77 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import React, { Component } from 'react';
|
||||
import { Box, Typography, Container, CircularProgress } from '@mui/material';
|
||||
import Chart from './Chart';
|
||||
import { withRouter } from './withRouter';
|
||||
|
||||
export default function ViewDisplay() {
|
||||
const { id } = useParams();
|
||||
const [view, setView] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
class ViewDisplay extends Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {
|
||||
view: null,
|
||||
loading: true,
|
||||
error: null
|
||||
};
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
this.fetchView();
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps) {
|
||||
if (prevProps.router.params.id !== this.props.router.params.id) {
|
||||
this.fetchView();
|
||||
}
|
||||
}
|
||||
|
||||
fetchView() {
|
||||
const { id } = this.props.router.params;
|
||||
this.setState({ loading: true, error: null });
|
||||
|
||||
useEffect(() => {
|
||||
fetch(`/api/views/${id}`)
|
||||
.then(res => {
|
||||
if (!res.ok) throw new Error('View not found');
|
||||
return res.json();
|
||||
})
|
||||
.then(data => {
|
||||
setView(data);
|
||||
setLoading(false);
|
||||
this.setState({ view: data, loading: false });
|
||||
})
|
||||
.catch(err => {
|
||||
setError(err.message);
|
||||
setLoading(false);
|
||||
this.setState({ error: err.message, loading: false });
|
||||
});
|
||||
}, [id]);
|
||||
|
||||
if (loading) return <Container sx={{ mt: 4, textAlign: 'center' }}><CircularProgress /></Container>;
|
||||
if (error) return <Container sx={{ mt: 4 }}><Typography color="error">{error}</Typography></Container>;
|
||||
|
||||
// Parse view config (compat with both array and object format)
|
||||
let channelsData = [];
|
||||
let axesData = null;
|
||||
|
||||
if (Array.isArray(view.config)) {
|
||||
channelsData = view.config;
|
||||
} else if (view.config && view.config.channels) {
|
||||
channelsData = view.config.channels;
|
||||
axesData = view.config.axes;
|
||||
}
|
||||
|
||||
// Map view config to Chart format with aliases and axis
|
||||
const channelConfig = channelsData.map(item => ({
|
||||
id: `${item.device}:${item.channel}`,
|
||||
alias: item.alias,
|
||||
yAxis: item.yAxis || 'left'
|
||||
}));
|
||||
render() {
|
||||
const { view, loading, error } = this.state;
|
||||
|
||||
return (
|
||||
<Box sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
|
||||
<Box sx={{ p: 2 }}>
|
||||
<Typography variant="h5">{view.name}</Typography>
|
||||
if (loading) return <Container sx={{ mt: 4, textAlign: 'center' }}><CircularProgress /></Container>;
|
||||
if (error) return <Container sx={{ mt: 4 }}><Typography color="error">{error}</Typography></Container>;
|
||||
|
||||
// Parse view config
|
||||
let channelsData = [];
|
||||
let axesData = null;
|
||||
|
||||
if (Array.isArray(view.config)) {
|
||||
channelsData = view.config;
|
||||
} else if (view.config && view.config.channels) {
|
||||
channelsData = view.config.channels;
|
||||
axesData = view.config.axes;
|
||||
}
|
||||
|
||||
const channelConfig = channelsData.map(item => ({
|
||||
id: `${item.device}:${item.channel}`,
|
||||
alias: item.alias,
|
||||
yAxis: item.yAxis || 'left'
|
||||
}));
|
||||
|
||||
return (
|
||||
<Box sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
|
||||
<Box sx={{ p: 2 }}>
|
||||
<Typography variant="h5">{view.name}</Typography>
|
||||
</Box>
|
||||
<Chart channelConfig={channelConfig} axisConfig={axesData} />
|
||||
</Box>
|
||||
<Chart channelConfig={channelConfig} axisConfig={axesData} />
|
||||
</Box>
|
||||
);
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default withRouter(ViewDisplay);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import React, { Component } from 'react';
|
||||
import {
|
||||
Container, Typography, List, ListItem, ListItemText, ListItemIcon,
|
||||
Button, TextField, Dialog, DialogTitle, DialogContent, DialogActions,
|
||||
@@ -8,61 +8,78 @@ import DashboardIcon from '@mui/icons-material/Dashboard';
|
||||
import AddIcon from '@mui/icons-material/Add';
|
||||
import DeleteIcon from '@mui/icons-material/Delete';
|
||||
import EditIcon from '@mui/icons-material/Edit';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { withRouter } from './withRouter';
|
||||
|
||||
export default function ViewManager({ user }) {
|
||||
const [views, setViews] = useState([]);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [editingId, setEditingId] = useState(null); // ID if editing, null if creating
|
||||
const [viewName, setViewName] = useState('');
|
||||
const [availableDevices, setAvailableDevices] = useState([]);
|
||||
class ViewManager extends Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.state = {
|
||||
views: [],
|
||||
open: false,
|
||||
editingId: null,
|
||||
viewName: '',
|
||||
availableDevices: [],
|
||||
viewConfig: [], // [{ device, channel, alias, yAxis }]
|
||||
axisConfig: {
|
||||
left: { min: '', max: '' },
|
||||
right: { min: '', max: '' }
|
||||
},
|
||||
// Config item selection state
|
||||
selDevice: '',
|
||||
selChannel: '',
|
||||
alias: '',
|
||||
yAxis: 'left'
|
||||
};
|
||||
}
|
||||
|
||||
const [viewConfig, setViewConfig] = useState([]); // [{ device, channel, alias, yAxis }]
|
||||
const [axisConfig, setAxisConfig] = useState({
|
||||
left: { min: '', max: '' },
|
||||
right: { min: '', max: '' }
|
||||
});
|
||||
|
||||
// Selection state for new item
|
||||
const [selDevice, setSelDevice] = useState('');
|
||||
const [selChannel, setSelChannel] = useState('');
|
||||
const [alias, setAlias] = useState('');
|
||||
const [yAxis, setYAxis] = useState('left');
|
||||
|
||||
const navigate = useNavigate();
|
||||
const isAdmin = user && user.role === 'admin';
|
||||
|
||||
useEffect(() => {
|
||||
refreshViews();
|
||||
if (isAdmin) {
|
||||
componentDidMount() {
|
||||
this.refreshViews();
|
||||
if (this.isAdmin()) {
|
||||
fetch('/api/devices')
|
||||
.then(res => res.json())
|
||||
.then(setAvailableDevices)
|
||||
.then(devices => this.setState({ availableDevices: devices }))
|
||||
.catch(console.error);
|
||||
}
|
||||
}, [isAdmin]);
|
||||
}
|
||||
|
||||
const refreshViews = () => {
|
||||
componentDidUpdate(prevProps) {
|
||||
if (prevProps.user !== this.props.user) {
|
||||
// If user changes (e.g. login/logout), refresh
|
||||
this.refreshViews();
|
||||
if (this.isAdmin()) {
|
||||
fetch('/api/devices')
|
||||
.then(res => res.json())
|
||||
.then(devices => this.setState({ availableDevices: devices }))
|
||||
.catch(console.error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
isAdmin() {
|
||||
const { user } = this.props;
|
||||
return user && user.role === 'admin';
|
||||
}
|
||||
|
||||
refreshViews = () => {
|
||||
fetch('/api/views')
|
||||
.then(res => res.json())
|
||||
.then(setViews)
|
||||
.then(views => this.setState({ views }))
|
||||
.catch(console.error);
|
||||
};
|
||||
|
||||
const handleOpenCreate = () => {
|
||||
setEditingId(null);
|
||||
setViewName('');
|
||||
setViewConfig([]);
|
||||
setAxisConfig({ left: { min: '', max: '' }, right: { min: '', max: '' } });
|
||||
setOpen(true);
|
||||
handleOpenCreate = () => {
|
||||
this.setState({
|
||||
editingId: null,
|
||||
viewName: '',
|
||||
viewConfig: [],
|
||||
axisConfig: { left: { min: '', max: '' }, right: { min: '', max: '' } },
|
||||
open: true
|
||||
});
|
||||
};
|
||||
|
||||
const handleOpenEdit = (v, e) => {
|
||||
handleOpenEdit = (v, e) => {
|
||||
e.stopPropagation();
|
||||
setEditingId(v.id);
|
||||
setViewName(v.name);
|
||||
|
||||
// Fetch full config for this view
|
||||
fetch(`/api/views/${v.id}`)
|
||||
.then(res => res.json())
|
||||
.then(data => {
|
||||
@@ -70,45 +87,48 @@ export default function ViewManager({ user }) {
|
||||
let axes = { left: { min: '', max: '' }, right: { min: '', max: '' } };
|
||||
|
||||
if (Array.isArray(data.config)) {
|
||||
// Legacy format: config is just the array of channels
|
||||
channels = data.config;
|
||||
} else if (data.config && data.config.channels) {
|
||||
// New format: { channels, axes }
|
||||
channels = data.config.channels;
|
||||
if (data.config.axes) {
|
||||
// Merge with defaults
|
||||
axes = {
|
||||
left: { ...axes.left, ...data.config.axes.left },
|
||||
right: { ...axes.right, ...data.config.axes.right }
|
||||
};
|
||||
}
|
||||
}
|
||||
// Ensure config items have yAxis
|
||||
channels = channels.map(c => ({ ...c, yAxis: c.yAxis || 'left' }));
|
||||
|
||||
setViewConfig(channels);
|
||||
setAxisConfig(axes);
|
||||
setOpen(true);
|
||||
this.setState({
|
||||
editingId: v.id,
|
||||
viewName: v.name,
|
||||
viewConfig: channels,
|
||||
axisConfig: axes,
|
||||
open: true
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const handleDelete = async (id, e) => {
|
||||
handleDelete = async (id, e) => {
|
||||
e.stopPropagation();
|
||||
if (!window.confirm("Are you sure?")) return;
|
||||
const { user } = this.props;
|
||||
await fetch(`/api/views/${id}`, {
|
||||
method: 'DELETE',
|
||||
headers: { 'Authorization': `Bearer ${user.token}` }
|
||||
});
|
||||
refreshViews();
|
||||
this.refreshViews();
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
handleSave = async () => {
|
||||
const { viewName, viewConfig, editingId, axisConfig } = this.state;
|
||||
const { user } = this.props;
|
||||
|
||||
if (!viewName || viewConfig.length === 0) return;
|
||||
|
||||
const url = editingId ? `/api/views/${editingId}` : '/api/views';
|
||||
const method = editingId ? 'PUT' : 'POST';
|
||||
|
||||
// Prepare config object
|
||||
const finalConfig = {
|
||||
channels: viewConfig,
|
||||
axes: axisConfig
|
||||
@@ -125,8 +145,8 @@ export default function ViewManager({ user }) {
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
setOpen(false);
|
||||
refreshViews();
|
||||
this.setState({ open: false });
|
||||
this.refreshViews();
|
||||
} else {
|
||||
alert('Failed to save view');
|
||||
}
|
||||
@@ -135,157 +155,173 @@ export default function ViewManager({ user }) {
|
||||
}
|
||||
};
|
||||
|
||||
const addConfigItem = () => {
|
||||
addConfigItem = () => {
|
||||
const { selDevice, selChannel, alias, yAxis, viewConfig } = this.state;
|
||||
if (selDevice && selChannel) {
|
||||
setViewConfig([...viewConfig, {
|
||||
device: selDevice,
|
||||
channel: selChannel,
|
||||
alias: alias || `${selDevice}:${selChannel}`,
|
||||
yAxis: yAxis
|
||||
}]);
|
||||
setSelDevice('');
|
||||
setSelChannel('');
|
||||
setAlias('');
|
||||
setYAxis('left');
|
||||
this.setState({
|
||||
viewConfig: [...viewConfig, {
|
||||
device: selDevice,
|
||||
channel: selChannel,
|
||||
alias: alias || `${selDevice}:${selChannel}`,
|
||||
yAxis: yAxis
|
||||
}],
|
||||
selDevice: '',
|
||||
selChannel: '',
|
||||
alias: '',
|
||||
yAxis: 'left'
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Derived state for channels
|
||||
const channelsForDevice = availableDevices.filter(d => d.device === selDevice).map(d => d.channel);
|
||||
const uniqueDevices = [...new Set(availableDevices.map(d => d.device))];
|
||||
|
||||
const handleAxisChange = (axis, field, value) => {
|
||||
setAxisConfig(prev => ({
|
||||
...prev,
|
||||
[axis]: { ...prev[axis], [field]: value }
|
||||
handleAxisChange = (axis, field, value) => {
|
||||
this.setState(prevState => ({
|
||||
axisConfig: {
|
||||
...prevState.axisConfig,
|
||||
[axis]: { ...prevState.axisConfig[axis], [field]: value }
|
||||
}
|
||||
}));
|
||||
};
|
||||
|
||||
return (
|
||||
<Container maxWidth="md" sx={{ mt: 4 }}>
|
||||
<Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 2 }}>
|
||||
<Typography variant="h4">Views</Typography>
|
||||
{isAdmin && (
|
||||
<Button variant="contained" startIcon={<AddIcon />} onClick={handleOpenCreate}>
|
||||
Create View
|
||||
</Button>
|
||||
)}
|
||||
</Box>
|
||||
render() {
|
||||
const {
|
||||
views, open, editingId, viewName, availableDevices, viewConfig, axisConfig,
|
||||
selDevice, selChannel, alias, yAxis
|
||||
} = this.state;
|
||||
const { router } = this.props;
|
||||
const isAdmin = this.isAdmin();
|
||||
|
||||
<List>
|
||||
{views.map(view => (
|
||||
<ListItem
|
||||
button
|
||||
key={view.id}
|
||||
divider
|
||||
onClick={() => navigate(`/views/${view.id}`)}
|
||||
>
|
||||
<ListItemIcon><DashboardIcon /></ListItemIcon>
|
||||
<ListItemText
|
||||
primary={view.name}
|
||||
secondary={`Created: ${new Date(view.created_at).toLocaleDateString()}`}
|
||||
/>
|
||||
{isAdmin && (
|
||||
<Box>
|
||||
<IconButton onClick={(e) => handleOpenEdit(view, e)}><EditIcon /></IconButton>
|
||||
<IconButton onClick={(e) => handleDelete(view.id, e)}><DeleteIcon /></IconButton>
|
||||
</Box>
|
||||
)}
|
||||
</ListItem>
|
||||
))}
|
||||
{views.length === 0 && <Typography>No views available.</Typography>}
|
||||
</List>
|
||||
const channelsForDevice = availableDevices.filter(d => d.device === selDevice).map(d => d.channel);
|
||||
const uniqueDevices = [...new Set(availableDevices.map(d => d.device))];
|
||||
|
||||
{/* Create/Edit Dialog */}
|
||||
<Dialog open={open} onClose={() => setOpen(false)} maxWidth="md" fullWidth>
|
||||
<DialogTitle>{editingId ? 'Edit View' : 'Create New View'}</DialogTitle>
|
||||
<DialogContent>
|
||||
<TextField
|
||||
autoFocus
|
||||
margin="dense"
|
||||
label="View Name"
|
||||
fullWidth
|
||||
value={viewName}
|
||||
onChange={(e) => setViewName(e.target.value)}
|
||||
sx={{ mb: 2 }}
|
||||
/>
|
||||
return (
|
||||
<Container maxWidth="md" sx={{ mt: 4 }}>
|
||||
<Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 2 }}>
|
||||
<Typography variant="h4">Views</Typography>
|
||||
{isAdmin && (
|
||||
<Button variant="contained" startIcon={<AddIcon />} onClick={this.handleOpenCreate}>
|
||||
Create View
|
||||
</Button>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
{/* Axis Config Section */}
|
||||
<Box sx={{ p: 2, border: '1px solid #444', borderRadius: 1, mb: 2 }}>
|
||||
<Typography variant="subtitle2" gutterBottom>Axis Configuration (Soft Limits)</Typography>
|
||||
<Box sx={{ display: 'flex', gap: 2 }}>
|
||||
<Box sx={{ flex: 1, display: 'flex', gap: 1, alignItems: 'center' }}>
|
||||
<Typography variant="caption" sx={{ width: 40 }}>Left:</Typography>
|
||||
<TextField size="small" label="Min" type="number" value={axisConfig.left.min} onChange={(e) => handleAxisChange('left', 'min', e.target.value)} />
|
||||
<TextField size="small" label="Max" type="number" value={axisConfig.left.max} onChange={(e) => handleAxisChange('left', 'max', e.target.value)} />
|
||||
</Box>
|
||||
<Box sx={{ flex: 1, display: 'flex', gap: 1, alignItems: 'center' }}>
|
||||
<Typography variant="caption" sx={{ width: 40 }}>Right:</Typography>
|
||||
<TextField size="small" label="Min" type="number" value={axisConfig.right.min} onChange={(e) => handleAxisChange('right', 'min', e.target.value)} />
|
||||
<TextField size="small" label="Max" type="number" value={axisConfig.right.max} onChange={(e) => handleAxisChange('right', 'max', e.target.value)} />
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Box sx={{ mt: 2, p: 2, border: '1px solid #444', borderRadius: 1 }}>
|
||||
<Typography variant="subtitle2">Add Channels</Typography>
|
||||
<Box sx={{ display: 'flex', gap: 1, mt: 1, alignItems: 'center' }}>
|
||||
<FormControl size="small" sx={{ minWidth: 150 }}>
|
||||
<InputLabel>Device</InputLabel>
|
||||
<Select value={selDevice} label="Device" onChange={(e) => setSelDevice(e.target.value)}>
|
||||
{uniqueDevices.map(d => <MenuItem key={d} value={d}>{d}</MenuItem>)}
|
||||
</Select>
|
||||
</FormControl>
|
||||
<FormControl size="small" sx={{ minWidth: 150 }}>
|
||||
<InputLabel>Channel</InputLabel>
|
||||
<Select value={selChannel} label="Channel" onChange={(e) => setSelChannel(e.target.value)}>
|
||||
{channelsForDevice.map(c => <MenuItem key={c} value={c}>{c}</MenuItem>)}
|
||||
</Select>
|
||||
</FormControl>
|
||||
<FormControl size="small" sx={{ minWidth: 100 }}>
|
||||
<InputLabel>Axis</InputLabel>
|
||||
<Select value={yAxis} label="Axis" onChange={(e) => setYAxis(e.target.value)}>
|
||||
<MenuItem value="left">Left</MenuItem>
|
||||
<MenuItem value="right">Right</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
<TextField
|
||||
size="small"
|
||||
label="Alias (Optional)"
|
||||
value={alias}
|
||||
onChange={(e) => setAlias(e.target.value)}
|
||||
sx={{ flexGrow: 1 }}
|
||||
<List>
|
||||
{views.map(view => (
|
||||
<ListItem
|
||||
button
|
||||
key={view.id}
|
||||
divider
|
||||
onClick={() => router.navigate(`/views/${view.id}`)}
|
||||
>
|
||||
<ListItemIcon><DashboardIcon /></ListItemIcon>
|
||||
<ListItemText
|
||||
primary={view.name}
|
||||
secondary={`Created: ${new Date(view.created_at).toLocaleDateString()}`}
|
||||
/>
|
||||
<Button variant="outlined" onClick={addConfigItem}>Add</Button>
|
||||
{isAdmin && (
|
||||
<Box>
|
||||
<IconButton onClick={(e) => this.handleOpenEdit(view, e)}><EditIcon /></IconButton>
|
||||
<IconButton onClick={(e) => this.handleDelete(view.id, e)}><DeleteIcon /></IconButton>
|
||||
</Box>
|
||||
)}
|
||||
</ListItem>
|
||||
))}
|
||||
{views.length === 0 && <Typography>No views available.</Typography>}
|
||||
</List>
|
||||
|
||||
<Dialog open={open} onClose={() => this.setState({ open: false })} maxWidth="md" fullWidth>
|
||||
<DialogTitle>{editingId ? 'Edit View' : 'Create New View'}</DialogTitle>
|
||||
<DialogContent>
|
||||
<TextField
|
||||
autoFocus
|
||||
margin="dense"
|
||||
label="View Name"
|
||||
fullWidth
|
||||
value={viewName}
|
||||
onChange={(e) => this.setState({ viewName: e.target.value })}
|
||||
sx={{ mb: 2 }}
|
||||
/>
|
||||
|
||||
{/* Axis Config Section */}
|
||||
<Box sx={{ p: 2, border: '1px solid #444', borderRadius: 1, mb: 2 }}>
|
||||
<Typography variant="subtitle2" gutterBottom>Axis Configuration (Soft Limits)</Typography>
|
||||
<Box sx={{ display: 'flex', gap: 2 }}>
|
||||
<Box sx={{ flex: 1, display: 'flex', gap: 1, alignItems: 'center' }}>
|
||||
<Typography variant="caption" sx={{ width: 40 }}>Left:</Typography>
|
||||
<TextField size="small" label="Min" type="number" value={axisConfig.left.min} onChange={(e) => this.handleAxisChange('left', 'min', e.target.value)} />
|
||||
<TextField size="small" label="Max" type="number" value={axisConfig.left.max} onChange={(e) => this.handleAxisChange('left', 'max', e.target.value)} />
|
||||
</Box>
|
||||
<Box sx={{ flex: 1, display: 'flex', gap: 1, alignItems: 'center' }}>
|
||||
<Typography variant="caption" sx={{ width: 40 }}>Right:</Typography>
|
||||
<TextField size="small" label="Min" type="number" value={axisConfig.right.min} onChange={(e) => this.handleAxisChange('right', 'min', e.target.value)} />
|
||||
<TextField size="small" label="Max" type="number" value={axisConfig.right.max} onChange={(e) => this.handleAxisChange('right', 'max', e.target.value)} />
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Box sx={{ mt: 2, display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
|
||||
{viewConfig.map((item, idx) => (
|
||||
<Chip
|
||||
key={idx}
|
||||
label={`${item.alias} (${item.yAxis})`}
|
||||
onClick={() => {
|
||||
setSelDevice(item.device);
|
||||
setSelChannel(item.channel);
|
||||
setAlias(item.alias);
|
||||
setYAxis(item.yAxis);
|
||||
setViewConfig(viewConfig.filter((_, i) => i !== idx));
|
||||
}}
|
||||
onDelete={() => setViewConfig(viewConfig.filter((_, i) => i !== idx))}
|
||||
sx={{ cursor: 'pointer' }}
|
||||
<Box sx={{ mt: 2, p: 2, border: '1px solid #444', borderRadius: 1 }}>
|
||||
<Typography variant="subtitle2">Add Channels</Typography>
|
||||
<Box sx={{ display: 'flex', gap: 1, mt: 1, alignItems: 'center' }}>
|
||||
<FormControl size="small" sx={{ minWidth: 150 }}>
|
||||
<InputLabel>Device</InputLabel>
|
||||
<Select value={selDevice} label="Device" onChange={(e) => this.setState({ selDevice: e.target.value })}>
|
||||
{uniqueDevices.map(d => <MenuItem key={d} value={d}>{d}</MenuItem>)}
|
||||
</Select>
|
||||
</FormControl>
|
||||
<FormControl size="small" sx={{ minWidth: 150 }}>
|
||||
<InputLabel>Channel</InputLabel>
|
||||
<Select value={selChannel} label="Channel" onChange={(e) => this.setState({ selChannel: e.target.value })}>
|
||||
{channelsForDevice.map(c => <MenuItem key={c} value={c}>{c}</MenuItem>)}
|
||||
</Select>
|
||||
</FormControl>
|
||||
<FormControl size="small" sx={{ minWidth: 100 }}>
|
||||
<InputLabel>Axis</InputLabel>
|
||||
<Select value={yAxis} label="Axis" onChange={(e) => this.setState({ yAxis: e.target.value })}>
|
||||
<MenuItem value="left">Left</MenuItem>
|
||||
<MenuItem value="right">Right</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
<TextField
|
||||
size="small"
|
||||
label="Alias (Optional)"
|
||||
value={alias}
|
||||
onChange={(e) => this.setState({ alias: e.target.value })}
|
||||
sx={{ flexGrow: 1 }}
|
||||
/>
|
||||
))}
|
||||
<Button variant="outlined" onClick={this.addConfigItem}>Add</Button>
|
||||
</Box>
|
||||
|
||||
<Box sx={{ mt: 2, display: 'flex', flexWrap: 'wrap', gap: 0.5 }}>
|
||||
{viewConfig.map((item, idx) => (
|
||||
<Chip
|
||||
key={idx}
|
||||
label={`${item.alias} (${item.yAxis})`}
|
||||
onClick={() => {
|
||||
this.setState({
|
||||
selDevice: item.device,
|
||||
selChannel: item.channel,
|
||||
alias: item.alias,
|
||||
yAxis: item.yAxis,
|
||||
viewConfig: viewConfig.filter((_, i) => i !== idx)
|
||||
});
|
||||
}}
|
||||
onDelete={() => this.setState({ viewConfig: viewConfig.filter((_, i) => i !== idx) })}
|
||||
sx={{ cursor: 'pointer' }}
|
||||
/>
|
||||
))}
|
||||
</Box>
|
||||
<Typography variant="caption" sx={{ mt: 1, display: 'block', color: 'text.secondary' }}>
|
||||
Click a chip to edit its settings.
|
||||
</Typography>
|
||||
</Box>
|
||||
<Typography variant="caption" sx={{ mt: 1, display: 'block', color: 'text.secondary' }}>
|
||||
Click a chip to edit its settings.
|
||||
</Typography>
|
||||
</Box>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={() => setOpen(false)}>Cancel</Button>
|
||||
<Button onClick={handleSave} color="primary">Save</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
</Container>
|
||||
);
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={() => this.setState({ open: false })}>Cancel</Button>
|
||||
<Button onClick={this.handleSave} color="primary">Save</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default withRouter(ViewManager);
|
||||
|
||||
18
uiserver/src/components/withRouter.js
Normal file
18
uiserver/src/components/withRouter.js
Normal file
@@ -0,0 +1,18 @@
|
||||
import React from 'react';
|
||||
import { useNavigate, useLocation, useParams } from 'react-router-dom';
|
||||
|
||||
export function withRouter(Component) {
|
||||
function ComponentWithRouterProp(props) {
|
||||
let location = useLocation();
|
||||
let navigate = useNavigate();
|
||||
let params = useParams();
|
||||
return (
|
||||
<Component
|
||||
{...props}
|
||||
router={{ location, navigate, params }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return ComponentWithRouterProp;
|
||||
}
|
||||
Reference in New Issue
Block a user