1
0
Fork 0
mirror of https://git.rwth-aachen.de/acs/public/villas/web/ synced 2025-03-09 00:00:01 +01:00

Merge branch '20-import-export-models' into 'develop'

Resolve "Import/Export "models""

Closes #20

See merge request !21
This commit is contained in:
Markus Grigull 2017-09-18 18:31:28 +02:00
commit 772c1d7718
16 changed files with 10215 additions and 88 deletions

9364
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

View file

@ -12,6 +12,7 @@
"d3-shape": "^1.2.0",
"d3-time-format": "^2.0.5",
"es6-promise": "^4.0.5",
"file-saver": "^1.3.3",
"flux": "^3.1.2",
"gaugeJS": "^1.3.2",
"immutable": "^3.8.1",

View file

@ -0,0 +1,125 @@
/**
* File: import-node.js
* Author: Markus Grigull <mgrigull@eonerc.rwth-aachen.de>
* Date: 03.09.2017
*
* This file is part of VILLASweb.
*
* VILLASweb is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* VILLASweb is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with VILLASweb. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
import React from 'react';
import { FormGroup, FormControl, ControlLabel } from 'react-bootstrap';
import Dialog from './dialog';
class ImportNodeDialog extends React.Component {
valid = false;
imported = false;
constructor(props) {
super(props);
this.state = {
name: '',
endpoint: '',
simulators: []
};
}
onClose(canceled) {
if (canceled === false) {
this.props.onClose(this.state);
} else {
this.props.onClose();
}
}
handleChange(e) {
this.setState({ [e.target.id]: e.target.value });
}
resetState() {
this.setState({ name: '', endpoint: '' });
this.imported = false;
}
loadFile(fileList) {
// get file
const file = fileList[0];
if (!file.type.match('application/json')) {
return;
}
// create file reader
var reader = new FileReader();
var self = this;
reader.onload = function(event) {
// read simulator
const node = JSON.parse(event.target.result);
self.imported = true;
self.setState({ name: node.name, endpoint: node.endpoint, simulators: node.simulators });
};
reader.readAsText(file);
}
validateForm(target) {
// check all controls
let endpoint = true;
let name = true;
if (this.state.name === '' || this.props.nodes.find(node => node.name === this.state.name) !== undefined) {
name = false;
}
if (this.state.endpoint === '' || this.props.nodes.find(node => node.endpoint === this.state.endpoint) !== undefined) {
endpoint = false;
}
this.valid = endpoint && name;
// return state to control
if (target === 'name') return name ? "success" : "error";
else return endpoint ? "success" : "error";
}
render() {
return (
<Dialog show={this.props.show} title="Import Simulator" buttonTitle="Import" onClose={(c) => this.onClose(c)} onReset={() => this.resetState()} valid={this.valid}>
<form>
<FormGroup controlId="file">
<ControlLabel>Simulator File</ControlLabel>
<FormControl type="file" onChange={(e) => this.loadFile(e.target.files)} />
</FormGroup>
<FormGroup controlId="name" validationState={this.validateForm('name')}>
<ControlLabel>Name</ControlLabel>
<FormControl readOnly={!this.imported} type="text" placeholder="Enter name" value={this.state.name} onChange={(e) => this.handleChange(e)} />
<FormControl.Feedback />
</FormGroup>
<FormGroup controlId="endpoint" validationState={this.validateForm('endpoint')}>
<ControlLabel>Endpoint</ControlLabel>
<FormControl readOnly={!this.imported} type="text" placeholder="Enter endpoint" value={this.state.endpoint} onChange={(e) => this.handleChange(e)} />
<FormControl.Feedback />
</FormGroup>
</form>
</Dialog>
);
}
}
export default ImportNodeDialog;

View file

@ -0,0 +1,189 @@
/**
* File: import-simulation-model.js
* Author: Markus Grigull <mgrigull@eonerc.rwth-aachen.de>
* Date: 03.09.2017
*
* This file is part of VILLASweb.
*
* VILLASweb is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* VILLASweb is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with VILLASweb. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
import React from 'react';
import { FormGroup, FormControl, ControlLabel } from 'react-bootstrap';
import Table from '../table';
import TableColumn from '../table-column';
import Dialog from './dialog';
class ImportSimulationModelDialog extends React.Component {
valid = false;
imported = false;
constructor(props) {
super(props);
this.state = {
name: '',
simulator: { node: '', simulator: '' },
length: '1',
mapping: [ { name: 'Signal', type: 'Type' } ]
};
}
onClose(canceled) {
if (canceled === false) {
this.props.onClose(this.state);
} else {
this.props.onClose();
}
}
resetState() {
this.setState({
name: '',
simulator: { node: this.props.nodes[0] ? this.props.nodes[0]._id : '', simulator: this.props.nodes[0].simulators[0] ? 0 : '' },
length: '1',
mapping: [ { name: 'Signal', type: 'Type' } ]
});
this.imported = false;
}
handleChange(e) {
if (e.target.id === 'length') {
// change mapping size
if (e.target.value > this.state.mapping.length) {
// add missing signals
while (this.state.mapping.length < e.target.value) {
this.state.mapping.push({ name: 'Signal', type: 'Type' });
}
} else {
// remove signals
this.state.mapping.splice(e.target.value, this.state.mapping.length - e.target.value);
}
}
if (e.target.id === 'simulator') {
this.setState({ simulator: JSON.parse(e.target.value) });
} else {
this.setState({ [e.target.id]: e.target.value });
}
}
handleMappingChange(event, row, column) {
var mapping = this.state.mapping;
if (column === 1) {
mapping[row].name = event.target.value;
} else if (column === 2) {
mapping[row].type = event.target.value;
}
this.setState({ mapping: mapping });
}
loadFile(fileList) {
// get file
const file = fileList[0];
if (!file.type.match('application/json')) {
return;
}
// create file reader
var reader = new FileReader();
var self = this;
reader.onload = function(event) {
// read simulator
const model = JSON.parse(event.target.result);
self.imported = true;
self.valid = true;
self.setState({ name: model.name, mapping: model.mapping, length: model.length, simulator: { node: self.props.nodes[0]._id, simulator: 0 } });
};
reader.readAsText(file);
}
validateForm(target) {
// check all controls
var name = true;
var length = true;
var simulator = true;
if (this.state.name === '') {
name = false;
}
if (this.state.simulator === '') {
simulator = false;
}
// test if simulatorid is a number (in a string, not type of number)
if (!/^\d+$/.test(this.state.length)) {
length = false;
}
this.valid = name && length && simulator;
// return state to control
if (target === 'name') return name ? "success" : "error";
else if (target === 'length') return length ? "success" : "error";
else if (target === 'simulator') return simulator ? "success" : "error";
}
render() {
return (
<Dialog show={this.props.show} title="Import Simulation Model" buttonTitle="Import" onClose={(c) => this.onClose(c)} onReset={() => this.resetState()} valid={this.valid}>
<form>
<FormGroup controlId="file">
<ControlLabel>Simulation Model File</ControlLabel>
<FormControl type="file" onChange={(e) => this.loadFile(e.target.files)} />
</FormGroup>
<FormGroup controlId="name" validationState={this.validateForm('name')}>
<ControlLabel>Name</ControlLabel>
<FormControl readOnly={!this.imported} type="text" placeholder="Enter name" value={this.state.name} onChange={(e) => this.handleChange(e)} />
<FormControl.Feedback />
</FormGroup>
<FormGroup controlId="simulator">
<ControlLabel>Simulator</ControlLabel>
<FormControl readOnly={!this.imported} componentClass="select" placeholder="Select simulator" value={JSON.stringify({ node: this.state.simulator.node, simulator: this.state.simulator.simulator})} onChange={(e) => this.handleChange(e)}>
{this.props.nodes.map(node => (
node.simulators.map((simulator, index) => (
<option key={node._id + index} value={JSON.stringify({ node: node.name, simulator: simulator.name })}>{node.name}/{simulator.name}</option>
))
))}
</FormControl>
</FormGroup>
<FormGroup controlId="length" validationState={this.validateForm('length')}>
<ControlLabel>Length</ControlLabel>
<FormControl readOnly={!this.imported} type="number" placeholder="Enter length" min="1" value={this.state.length} onChange={(e) => this.handleChange(e)} />
<FormControl.Feedback />
</FormGroup>
<FormGroup controlId="mapping">
<ControlLabel>Mapping</ControlLabel>
<Table data={this.state.mapping}>
<TableColumn title='ID' width='60' dataIndex />
<TableColumn title='Name' dataKey='name' inlineEditable onInlineChange={(event, row, column) => this.handleMappingChange(event, row, column)} />
<TableColumn title='Type' dataKey='type' inlineEditable onInlineChange={(event, row, column) => this.handleMappingChange(event, row, column)} />
</Table>
</FormGroup>
</form>
</Dialog>
);
}
}
export default ImportSimulationModelDialog;

View file

@ -0,0 +1,140 @@
/**
* File: import-simulation.js
* Author: Markus Grigull <mgrigull@eonerc.rwth-aachen.de>
* Date: 03.09.2017
*
* This file is part of VILLASweb.
*
* VILLASweb is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* VILLASweb is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with VILLASweb. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
import React from 'react';
import { FormGroup, FormControl, ControlLabel } from 'react-bootstrap';
import Dialog from './dialog';
class ImportSimulationDialog extends React.Component {
valid = false;
imported = false;
constructor(props) {
super(props);
this.state = {
name: '',
models: [],
};
}
onClose(canceled) {
if (canceled === false) {
this.props.onClose(this.state);
} else {
this.props.onClose();
}
}
handleChange(e, index) {
if (e.target.id === 'simulator') {
const models = this.state.models;
models[index].simulator = JSON.parse(e.target.value);
this.setState({ models });
} else {
this.setState({ [e.target.id]: e.target.value });
}
}
resetState() {
this.setState({ name: '', models: [] });
this.imported = false;
}
loadFile(fileList) {
// get file
const file = fileList[0];
if (!file.type.match('application/json')) {
return;
}
// create file reader
var reader = new FileReader();
var self = this;
reader.onload = function(event) {
// read simulator
const simulation = JSON.parse(event.target.result);
simulation.models.forEach(model => {
model.simulator = {
node: self.props.nodes[0]._id,
simulator: 0
}
});
self.imported = true;
self.setState({ name: simulation.name, models: simulation.models });
};
reader.readAsText(file);
}
validateForm(target) {
// check all controls
let name = true;
if (this.state.name === '') {
name = false;
}
this.valid = name;
// return state to control
if (target === 'name') return name ? "success" : "error";
}
render() {
return (
<Dialog show={this.props.show} title="Import Simulation" buttonTitle="Import" onClose={(c) => this.onClose(c)} onReset={() => this.resetState()} valid={this.valid}>
<form>
<FormGroup controlId="file">
<ControlLabel>Simulation File</ControlLabel>
<FormControl type="file" onChange={(e) => this.loadFile(e.target.files)} />
</FormGroup>
<FormGroup controlId="name" validationState={this.validateForm('name')}>
<ControlLabel>Name</ControlLabel>
<FormControl readOnly={!this.imported} type="text" placeholder="Enter name" value={this.state.name} onChange={(e) => this.handleChange(e)} />
<FormControl.Feedback />
</FormGroup>
{this.state.models.map((model, index) => (
<FormGroup controlId="simulator" key={index}>
<ControlLabel>{model.name} - Simulator</ControlLabel>
<FormControl componentClass="select" placeholder="Select simulator" value={JSON.stringify({ node: model.simulator.node, simulator: model.simulator.simulator})} onChange={(e) => this.handleChange(e, index)}>
{this.props.nodes.map(node => (
node.simulators.map((simulator, index) => (
<option key={node._id + index} value={JSON.stringify({ node: node._id, simulator: index })}>{node.name}/{simulator.name}</option>
))
))}
</FormControl>
</FormGroup>
))}
</form>
</Dialog>
);
}
}
export default ImportSimulationDialog;

View file

@ -0,0 +1,133 @@
/**
* File: import-simulator.js
* Author: Markus Grigull <mgrigull@eonerc.rwth-aachen.de>
* Date: 04.04.2017
*
* This file is part of VILLASweb.
*
* VILLASweb is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* VILLASweb is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with VILLASweb. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
import React from 'react';
import { FormGroup, FormControl, ControlLabel } from 'react-bootstrap';
import Dialog from './dialog';
class ImportVisualizationDialog extends React.Component {
valid = false;
imported = false;
constructor(props) {
super(props);
this.state = {
name: '',
widgets: [],
grid: 0
};
}
onClose(canceled) {
if (canceled === false) {
this.props.onClose(this.state);
} else {
this.props.onClose();
}
}
handleChange(e, index) {
this.setState({ [e.target.id]: e.target.value });
}
resetState() {
this.setState({ name: '', widgets: [], grid: 0 });
this.imported = false;
}
loadFile(fileList) {
// get file
const file = fileList[0];
if (!file.type.match('application/json')) {
return;
}
// create file reader
var reader = new FileReader();
var self = this;
reader.onload = function(event) {
// read simulator
const visualization = JSON.parse(event.target.result);
let defaultSimulator = "";
if (self.props.simulation.models != null) {
defaultSimulator = self.props.simulation.models[0].simulator;
}
visualization.widgets.forEach(widget => {
switch (widget.type) {
case 'Value':
case 'Plot':
case 'Table':
case 'PlotTable':
case 'Gauge':
widget.simulator = defaultSimulator;
break;
}
});
self.imported = true;
self.valid = true;
self.setState({ name: visualization.name, widgets: visualization.widgets, grid: visualization.grid });
};
reader.readAsText(file);
}
validateForm(target) {
// check all controls
let name = true;
if (this.state.name === '') {
name = false;
}
this.valid = name;
// return state to control
if (target === 'name') return name ? "success" : "error";
}
render() {
return (
<Dialog show={this.props.show} title="Import Visualization" buttonTitle="Import" onClose={(c) => this.onClose(c)} onReset={() => this.resetState()} valid={this.valid}>
<form>
<FormGroup controlId="file">
<ControlLabel>Visualization File</ControlLabel>
<FormControl type="file" onChange={(e) => this.loadFile(e.target.files)} />
</FormGroup>
<FormGroup controlId="name" validationState={this.validateForm('name')}>
<ControlLabel>Name</ControlLabel>
<FormControl readOnly={!this.imported} type="text" placeholder="Enter name" value={this.state.name} onChange={(e) => this.handleChange(e)} />
<FormControl.Feedback />
</FormGroup>
</form>
</Dialog>
);
}
}
export default ImportVisualizationDialog;

View file

@ -25,7 +25,7 @@ import { FormGroup, FormControl, ControlLabel } from 'react-bootstrap';
import Dialog from './dialog';
class NewNodeDialog extends React.Component {
valid: false;
valid = false;
constructor(props) {
super(props);

View file

@ -27,7 +27,7 @@ import TableColumn from '../table-column';
import Dialog from './dialog';
class NewSimulationModelDialog extends React.Component {
valid: false;
valid = false;
constructor(props) {
super(props);

View file

@ -47,6 +47,7 @@ class NodeTree extends React.Component {
buttons.push(<Button bsSize="small" onClick={() => this.props.onNodeAdd(rowInfo.node)}><Glyphicon glyph="plus" /></Button>);
buttons.push(<Button bsSize="small" onClick={() => this.props.onNodeEdit(rowInfo.node)}><Glyphicon glyph="pencil" /></Button>);
buttons.push(<Button bsSize="small" onClick={() => this.props.onNodeDelete(rowInfo.node)}><Glyphicon glyph="trash" /></Button>);
buttons.push(<Button bsSize="small" onClick={() => this.props.onNodeExport(rowInfo.node)}><Glyphicon glyph="export" /></Button>);
} else {
// get child index
var index = rowInfo.path[1] - rowInfo.path[0] - 1;

View file

@ -28,6 +28,7 @@ class TableColumn extends Component {
width: null,
editButton: false,
deleteButton: false,
exportButton: false,
link: '/',
linkKey: '',
dataIndex: false,

View file

@ -102,6 +102,10 @@ class CustomTable extends Component {
cell.push(<Checkbox className="table-control-checkbox" inline checked={checkboxKey ? data[checkboxKey] : null} onChange={e => child.props.onChecked(index, e)}></Checkbox>);
}
if (child.props.exportButton) {
cell.push(<Button bsClass='table-control-button' onClick={() => child.props.onExport(index)}><Glyphicon glyph='export' /></Button>);
}
return cell;
}

View file

@ -22,98 +22,80 @@
import React, { Component } from 'react';
import { Container } from 'flux/utils';
import { Button, Modal, Glyphicon } from 'react-bootstrap';
import FileSaver from 'file-saver';
import AppDispatcher from '../app-dispatcher';
import ProjectStore from '../stores/project-store';
import UserStore from '../stores/user-store';
import VisualizationStore from '../stores/visualization-store';
import SimulationStore from '../stores/simulation-store';
import CustomTable from '../components/table';
import TableColumn from '../components/table-column';
import NewVisualzationDialog from '../components/dialog/new-visualization';
import EditVisualizationDialog from '../components/dialog/edit-visualization';
import ImportVisualizationDialog from '../components/dialog/import-visualization';
class Visualizations extends Component {
static getStores() {
return [ ProjectStore, VisualizationStore, UserStore ];
return [ ProjectStore, VisualizationStore, UserStore, SimulationStore ];
}
static calculateState(prevState, props) {
prevState = prevState || {};
let currentProjects = ProjectStore.getState();
let currentVisualizations = VisualizationStore.getState();
let sessionToken = UserStore.getState().token;
// load project
const sessionToken = UserStore.getState().token;
if (prevState) {
var projectUpdate = prevState.project;
let project = ProjectStore.getState().find(project => project._id === props.match.params.project);
if (project == null) {
AppDispatcher.dispatch({
type: 'projects/start-load',
data: props.match.params.project,
token: sessionToken
});
// Compare content of the visualizations array, reload projects if changed
if (JSON.stringify(prevState.visualizations) !== JSON.stringify(currentVisualizations)) {
Visualizations.loadProjects(sessionToken);
}
// Compare content of the projects array, update visualizations if changed
if (JSON.stringify(prevState.projects) !== JSON.stringify(currentProjects)) {
projectUpdate = Visualizations.findProjectInState(currentProjects, props.match.params.project);
Visualizations.loadVisualizations(projectUpdate.visualizations, sessionToken);
}
return {
projects: currentProjects,
visualizations: currentVisualizations,
sessionToken,
newModal: prevState.newModal,
deleteModal: prevState.deleteModal,
editModal: prevState.editModal,
modalData: prevState.modalData,
project: projectUpdate
};
} else {
let initialProject = Visualizations.findProjectInState(currentProjects, props.match.params.project);
// If projects have been loaded already but visualizations not (redirect from Projects page)
if (initialProject && (!currentVisualizations || currentVisualizations.length === 0)) {
Visualizations.loadVisualizations(initialProject.visualizations, sessionToken);
}
return {
projects: currentProjects,
visualizations: currentVisualizations,
sessionToken,
newModal: false,
deleteModal: false,
editModal: false,
modalData: {},
project: initialProject || {}
};
project = {};
}
// load simulation
let simulation = {};
if (project.simulation != null) {
simulation = SimulationStore.getState().find(simulation => simulation._id === project.simulation);
}
// load visualizations
let visualizations = [];
if (project.visualizations != null) {
visualizations = VisualizationStore.getState().filter(visualization => project.visualizations.includes(visualization._id));
}
return {
visualizations,
project,
simulation,
sessionToken,
newModal: prevState.newModal || false,
deleteModal: prevState.deleteModal || false,
editModal: prevState.editModal || false,
importModal: prevState.importModal || false,
modalData: prevState.modalData || {}
};
}
static findProjectInState(projects, projectId) {
return projects.find((project) => project._id === projectId);
}
static loadProjects(token) {
AppDispatcher.dispatch({
type: 'projects/start-load',
token
});
}
static loadVisualizations(visualizations, token) {
componentDidMount() {
AppDispatcher.dispatch({
type: 'visualizations/start-load',
data: visualizations,
token
token: this.state.sessionToken
});
}
componentWillMount() {
Visualizations.loadProjects(this.state.sessionToken);
AppDispatcher.dispatch({
type: 'simulations/start-load',
token: this.state.sessionToken
});
}
closeNewModal(data) {
@ -153,6 +135,44 @@ class Visualizations extends Component {
}
}
closeImportModal(data) {
this.setState({ importModal: false });
if (data) {
data.project = this.state.project._id;
AppDispatcher.dispatch({
type: 'visualizations/start-add',
data,
token: this.state.sessionToken
});
this.setState({ project: {} }, () => {
AppDispatcher.dispatch({
type: 'projects/start-load',
data: this.props.match.params.project,
token: this.state.sessionToken
});
});
}
}
exportVisualization(index) {
// filter properties
let visualization = Object.assign({}, this.state.visualizations[index]);
delete visualization._id;
delete visualization.project;
delete visualization.user;
visualization.widgets.forEach(widget => {
delete widget.simulator;
});
// show save dialog
const blob = new Blob([JSON.stringify(visualization, null, 2)], { type: 'application/json' });
FileSaver.saveAs(blob, 'visualization - ' + visualization.name + '.json');
}
onModalKeyPress = (event) => {
if (event.key === 'Enter') {
event.preventDefault();
@ -162,30 +182,29 @@ class Visualizations extends Component {
}
render() {
// get visualizations for this project
var visualizations = [];
if (this.state.visualizations && this.state.project.visualizations) {
visualizations = this.state.visualizations.filter(
(visualization) => this.state.project.visualizations.includes(visualization._id)
).sort(
(visA, visB) => visA.name.localeCompare(visB.name)
);
}
return (
<div className='section'>
<h1>{this.state.project.name}</h1>
<CustomTable data={visualizations}>
<CustomTable data={this.state.visualizations}>
<TableColumn title='Name' dataKey='name' link='/visualizations/' linkKey='_id' />
<TableColumn width='70' editButton deleteButton onEdit={(index) => this.setState({ editModal: true, modalData: visualizations[index] })} onDelete={(index) => this.setState({ deleteModal: true, modalData: visualizations[index] })} />
<TableColumn
width='100'
editButton
deleteButton
exportButton
onEdit={(index) => this.setState({ editModal: true, modalData: this.state.visualizations[index] })}
onDelete={(index) => this.setState({ deleteModal: true, modalData: this.state.visualizations[index] })}
onExport={index => this.exportVisualization(index)}
/>
</CustomTable>
<Button onClick={() => this.setState({ newModal: true })}><Glyphicon glyph="plus" /> Visualization</Button>
<Button onClick={() => this.setState({ importModal: true })}><Glyphicon glyph="import" /> Import</Button>
<NewVisualzationDialog show={this.state.newModal} onClose={(data) => this.closeNewModal(data)} />
<EditVisualizationDialog show={this.state.editModal} onClose={(data) => this.closeEditModal(data)} visualization={this.state.modalData} />
<ImportVisualizationDialog show={this.state.importModal} onClose={data => this.closeImportModal(data)} simulation={this.state.simulation} />
<Modal keyboard show={this.state.deleteModal} onHide={() => this.setState({ deleteModal: false })} onKeyPress={this.onModalKeyPress}>
<Modal.Header>

View file

@ -22,6 +22,7 @@
import React from 'react';
import { Container } from 'flux/utils';
import { Button, Modal, Glyphicon } from 'react-bootstrap';
import FileSaver from 'file-saver';
import SimulationStore from '../stores/simulation-store';
import NodeStore from '../stores/node-store';
@ -32,6 +33,7 @@ import Table from '../components/table';
import TableColumn from '../components/table-column';
import NewSimulationModelDialog from '../components/dialog/new-simulation-model';
import EditSimulationModelDialog from '../components/dialog/edit-simulation-model';
import ImportSimulationModelDialog from '../components/dialog/import-simulation-model';
class Simulation extends React.Component {
static getStores() {
@ -47,6 +49,7 @@ class Simulation extends React.Component {
newModal: false,
deleteModal: false,
editModal: false,
importModal: false,
modalData: {},
modalIndex: null,
@ -126,6 +129,20 @@ class Simulation extends React.Component {
}
}
closeImportModal(data) {
this.setState({ importModal: false });
if (data) {
this.state.simulation.models.push(data);
AppDispatcher.dispatch({
type: 'simulations/start-edit',
data: this.state.simulation,
token: this.state.sessionToken
});
}
}
getSimulatorName(simulator) {
var name = "undefined";
@ -138,6 +155,16 @@ class Simulation extends React.Component {
return name;
}
exportModel(index) {
// filter properties
let simulationModel = Object.assign({}, this.state.simulation.models[index]);
delete simulationModel.simulator;
// show save dialog
const blob = new Blob([JSON.stringify(simulationModel, null, 2)], { type: 'application/json' });
FileSaver.saveAs(blob, 'simulation model - ' + simulationModel.name + '.json');
}
onModalKeyPress = (event) => {
if (event.key === 'Enter') {
event.preventDefault();
@ -155,14 +182,24 @@ class Simulation extends React.Component {
<TableColumn title='Name' dataKey='name' />
<TableColumn title='Simulator' dataKey='simulator' width='180' modifier={(simulator) => this.getSimulatorName(simulator)} />
<TableColumn title='Length' dataKey='length' width='100' />
<TableColumn title='' width='70' editButton deleteButton onEdit={(index) => this.setState({ editModal: true, modalData: this.state.simulation.models[index], modalIndex: index })} onDelete={(index) => this.setState({ deleteModal: true, modalData: this.state.simulation.models[index], modalIndex: index })} />
<TableColumn
title=''
width='100'
editButton
deleteButton
exportButton
onEdit={(index) => this.setState({ editModal: true, modalData: this.state.simulation.models[index], modalIndex: index })}
onDelete={(index) => this.setState({ deleteModal: true, modalData: this.state.simulation.models[index], modalIndex: index })}
onExport={index => this.exportModel(index)}
/>
</Table>
<Button onClick={() => this.setState({ newModal: true })}><Glyphicon glyph="plus" /> Simulation Model</Button>
<Button onClick={() => this.setState({ importModal: true })}><Glyphicon glyph="import" /> Import</Button>
<NewSimulationModelDialog show={this.state.newModal} onClose={(data) => this.closeNewModal(data)} nodes={this.state.nodes} />
<EditSimulationModelDialog show={this.state.editModal} onClose={(data) => this.closeEditModal(data)} data={this.state.modalData} nodes={this.state.nodes} />
<ImportSimulationModelDialog show={this.state.importModal} onClose={data => this.closeImportModal(data)} nodes={this.state.nodes} />
<Modal keyboard show={this.state.deleteModal} onHide={() => this.setState({ deleteModal: false })} onKeyPress={this.onModalKeyPress}>
<Modal.Header>

View file

@ -22,29 +22,34 @@
import React, { Component } from 'react';
import { Container } from 'flux/utils';
import { Button, Modal, Glyphicon } from 'react-bootstrap';
import FileSaver from 'file-saver';
import AppDispatcher from '../app-dispatcher';
import SimulationStore from '../stores/simulation-store';
import UserStore from '../stores/user-store';
import NodeStore from '../stores/node-store';
import Table from '../components/table';
import TableColumn from '../components/table-column';
import NewSimulationDialog from '../components/dialog/new-simulation';
import EditSimulationDialog from '../components/dialog/edit-simulation';
import ImportSimulationDialog from '../components/dialog/import-simulation';
class Simulations extends Component {
static getStores() {
return [ SimulationStore, UserStore ];
return [ SimulationStore, UserStore, NodeStore ];
}
static calculateState() {
return {
simulations: SimulationStore.getState(),
nodes: NodeStore.getState(),
sessionToken: UserStore.getState().token,
newModal: false,
deleteModal: false,
editModal: false,
importModal: false,
modalSimulation: {}
};
}
@ -116,6 +121,18 @@ class Simulations extends Component {
}
}
closeImportModal(data) {
this.setState({ importModal: false });
if (data) {
AppDispatcher.dispatch({
type: 'simulations/start-add',
data,
token: this.state.sessionToken
});
}
}
onModalKeyPress = (event) => {
if (event.key === 'Enter') {
event.preventDefault();
@ -124,6 +141,23 @@ class Simulations extends Component {
}
}
exportSimulation(index) {
// filter properties
let simulation = Object.assign({}, this.state.simulations[index]);
delete simulation._id;
delete simulation.projects;
delete simulation.running;
delete simulation.user;
simulation.models.forEach(model => {
delete model.simulator;
});
// show save dialog
const blob = new Blob([JSON.stringify(simulation, null, 2)], { type: 'application/json' });
FileSaver.saveAs(blob, 'simulation - ' + simulation.name + '.json');
}
render() {
return (
<div className='section'>
@ -131,14 +165,23 @@ class Simulations extends Component {
<Table data={this.state.simulations}>
<TableColumn title='Name' dataKey='name' link='/simulations/' linkKey='_id' />
<TableColumn width='70' editButton deleteButton onEdit={index => this.setState({ editModal: true, modalSimulation: this.state.simulations[index] })} onDelete={index => this.setState({ deleteModal: true, modalSimulation: this.state.simulations[index] })} />
<TableColumn
width='100'
editButton
deleteButton
exportButton
onEdit={index => this.setState({ editModal: true, modalSimulation: this.state.simulations[index] })}
onDelete={index => this.setState({ deleteModal: true, modalSimulation: this.state.simulations[index] })}
onExport={index => this.exportSimulation(index)}
/>
</Table>
<Button onClick={() => this.setState({ newModal: true })}><Glyphicon glyph="plus" /> Simulation</Button>
<Button onClick={() => this.setState({ importModal: true })}><Glyphicon glyph="import" /> Import</Button>
<NewSimulationDialog show={this.state.newModal} onClose={(data) => this.closeNewModal(data)} />
<EditSimulationDialog show={this.state.editModal} onClose={(data) => this.closeEditModal(data)} simulation={this.state.modalSimulation} />
<ImportSimulationDialog show={this.state.importModal} onClose={data => this.closeImportModal(data)} nodes={this.state.nodes} />
<Modal keyboard show={this.state.deleteModal} onHide={() => this.setState({ deleteModal: false })} onKeyPress={this.onModalKeyPress}>
<Modal.Header>

View file

@ -22,6 +22,7 @@
import React, { Component } from 'react';
import { Container } from 'flux/utils';
import { Button, Modal, Glyphicon } from 'react-bootstrap';
import FileSaver from 'file-saver';
import AppDispatcher from '../app-dispatcher';
import NodeStore from '../stores/node-store';
@ -32,6 +33,7 @@ import EditNodeDialog from '../components/dialog/edit-node';
import NewSimulatorDialog from '../components/dialog/new-simulator';
import EditSimulatorDialog from '../components/dialog/edit-simulator';
import NodeTree from '../components/node-tree';
import ImportNodeDialog from '../components/dialog/import-node';
class Simulators extends Component {
static getStores() {
@ -46,6 +48,8 @@ class Simulators extends Component {
newNodeModal: false,
deleteNodeModal: false,
editNodeModal: false,
importModal: false,
exportModal: false,
addSimulatorModal: false,
editSimulatorModal: false,
@ -186,6 +190,41 @@ class Simulators extends Component {
token: this.state.sessionToken
});
}
closeImportNodeModal(data) {
this.setState({ importNodeModal: false });
if (data) {
AppDispatcher.dispatch({
type: 'nodes/start-add',
data,
token: this.state.sessionToken
});
}
}
exportNode(data) {
const node = this.state.nodes.find((element) => {
return element._id === data.id;
});
// filter properties
let simulator = Object.assign({}, node);
delete simulator._id;
simulator.simulators.forEach(simulator => {
delete simulator.id;
});
// show save dialog
const blob = new Blob([JSON.stringify(simulator, null, 2)], { type: 'application/json' });
FileSaver.saveAs(blob, 'node - ' + node.name + '.json');
}
labelStyle(value) {
if (value === true) return 'success';
else return 'warning';
}
onTreeDataChange(nodes) {
// update all at once
@ -214,21 +253,52 @@ class Simulators extends Component {
}
}
loadFile(fileList) {
// get file
const file = fileList[0];
if (!file.type.match('application/json')) {
return;
}
// create file reader
var reader = new FileReader();
var self = this;
reader.onload = function(event) {
// read simulator
const simulator = JSON.parse(event.target.result);
self.setState({ importModal: true, modalSimulator: simulator });
};
reader.readAsText(file);
}
render() {
return (
<div className='section'>
<h1>Simulators</h1>
<Button onClick={() => this.setState({ newNodeModal: true })}><Glyphicon glyph="plus" /> Node</Button>
<Button onClick={() => this.setState({ importNodeModal: true })}><Glyphicon glyph="import" /> Import</Button>
<br />
<small><i>Hint: Node names must be unique. Simulator names must be unique on a node.</i></small>
<NodeTree data={this.state.nodes} onDataChange={(treeData) => this.onTreeDataChange(treeData)} onNodeDelete={(node) => this.showDeleteNodeModal(node)} onNodeEdit={(node) => this.showEditNodeModal(node)} onNodeAdd={(node) => this.showAddSimulatorModal(node)} onSimulatorEdit={(node, index) => this.showEditSimulatorModal(node, index)} onSimulatorDelete={(node, index) => this.showDeleteSimulatorModal(node, index)} />
<NodeTree
data={this.state.nodes}
onDataChange={(treeData) => this.onTreeDataChange(treeData)}
onNodeDelete={(node) => this.showDeleteNodeModal(node)}
onNodeEdit={(node) => this.showEditNodeModal(node)}
onNodeAdd={(node) => this.showAddSimulatorModal(node)}
onNodeExport={node => this.exportNode(node)}
onSimulatorEdit={(node, index) => this.showEditSimulatorModal(node, index)}
onSimulatorDelete={(node, index) => this.showDeleteSimulatorModal(node, index)}
/>
<NewNodeDialog show={this.state.newNodeModal} onClose={(data) => this.closeNewNodeModal(data)} nodes={this.state.nodes} />
<EditNodeDialog node={this.state.modalData} show={this.state.editNodeModal} onClose={(data) => this.closeEditNodeModal(data)} nodes={this.state.nodes} />
<NewSimulatorDialog show={this.state.addSimulatorModal} onClose={(data) => this.closeAddSimulatorModal(data)} node={this.state.modalData}/>
<ImportNodeDialog show={this.state.importNodeModal} onClose={data => this.closeImportNodeModal(data)} nodes={this.state.nodes} />
{this.state.editSimulatorModal &&
<EditSimulatorDialog simulator={this.state.modalData.simulators[this.state.modalIndex]} show={this.state.editSimulatorModal} onClose={(data) => this.closeEditSimulatorModal(data)} node={this.state.modalData} />

View file

@ -21,4 +21,4 @@
import RestDataManager from './rest-data-manager';
export default new RestDataManager('simulation', '/simulations');
export default new RestDataManager('simulation', '/simulations', [ '_id', 'name', 'projects', 'models' ]);