all files / src/workflows/generic/components/steps/ SimputReact.js

29.09% Statements 64/220
24% Branches 18/75
15.56% Functions 7/45
24.18% Lines 44/182
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423                                                                10×                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      
'use strict';
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
 
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; Eif ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { Eif (protoProps) defineProperties(Constructor.prototype, protoProps); Iif (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
 
var _react = require('react');
 
var _react2 = _interopRequireDefault(_react);
 
var _propTypes = require('prop-types');
 
var _propTypes2 = _interopRequireDefault(_propTypes);
 
var _deepClone = require('mout/src/lang/deepClone');
 
var _deepClone2 = _interopRequireDefault(_deepClone);
 
var _PropertyPanel = require('paraviewweb/src/React/Properties/PropertyPanel');
 
var _PropertyPanel2 = _interopRequireDefault(_PropertyPanel);
 
var _Simput = require('Simput');
 
var _Simput2 = _interopRequireDefault(_Simput);
 
var _Labels = require('simput/src/Labels');
 
var _Labels2 = _interopRequireDefault(_Labels);
 
var _ViewMenu = require('simput/src/ViewMenu');
 
var _ViewMenu2 = _interopRequireDefault(_ViewMenu);
 
var _modelGenerator = require('simput/src/modelGenerator');
 
var _modelGenerator2 = _interopRequireDefault(_modelGenerator);
 
var _PageWithMenu = require('HPCCloudStyle/PageWithMenu.mcss');
 
var _PageWithMenu2 = _interopRequireDefault(_PageWithMenu);
 
var _network = require('../../../../network');
 
var _network2 = _interopRequireDefault(_network);
 
var _simulations = require('../../../../network/helpers/simulations');
 
var simulationsHelper = _interopRequireWildcard(_simulations);
 
var _redux = require('../../../../redux');
 
var _projects = require('../../../../redux/actions/projects');
 
var Actions = _interopRequireWildcard(_projects);
 
function _interopRequireWildcard(obj) { Eif (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
 
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
 
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
 
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
 
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
 
function _inherits(subClass, superClass) { Iif (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); Eif (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
 
/* eslint-disable import/extensions */
 
/* eslint-enable import/extensions */
 
 
// ----------------------------------------------------------------------------
 
function saveSimulation(simulation) {
  (0, _redux.dispatch)(Actions.saveSimulation(simulation));
}
 
// ----------------------------------------------------------------------------
 
function updateSimulation(simulation) {
  (0, _redux.dispatch)(Actions.updateSimulation(simulation));
}
 
// ----------------------------------------------------------------------------
 
function patchSimulation(simulation) {
  (0, _redux.dispatch)(Actions.patchSimulation(simulation));
}
 
// ----------------------------------------------------------------------------
 
var SimputReact = function (_React$Component) {
  _inherits(SimputReact, _React$Component);
 
  function SimputReact(props) {
    _classCallCheck(this, SimputReact);
 
    // Manually bind this method to the component instance...
    var _this = _possibleConstructorReturn(this, (SimputReact.__proto__ || Object.getPrototypeOf(SimputReact)).call(this, props));
 
    _this.saveModel = _this.saveModel.bind(_this);
    _this.updateActive = _this.updateActive.bind(_this);
    _this.updateViewData = _this.updateViewData.bind(_this);
 
    // Manage internal state
    var simputModule = _Simput2.default.types[_this.props.simputType];
    var promises = [];
    _this.fileNameToKeyMap = {};
    _this.state = {
      // Simput root data
      jsonData: props.simputModelDecorator(props.initialDataModel, props, _this.saveModel),
 
      // Language support
      labels: new _Labels2.default(_Simput2.default.types[props.simputType], 'en'),
      help: _Simput2.default.types[props.simputType].lang.en.help,
 
      // UI content management
      data: [],
      viewData: {}
    };
 
    // Register all files in state
    props.inputFileKeys.forEach(function (_ref) {
      var key = _ref.key,
          name = _ref.name;
 
      _this.fileNameToKeyMap[name] = key;
      _this.state[key] = null;
      _this.fileContent = {};
 
      // Check if the file is part of project but not part of the simulation
      if (_this.props.project.metadata.inputFolder.files[key] && !_this.props.simulation.metadata.inputFolder.files[key]) {
        // Any project file that can be edited in simulation should be copied
        // into simulation so local edits could be performed within a simulation
        // without changing the project.
        promises.push(_network2.default.downloadFile(_this.props.project.metadata.inputFolder.files[key], 0, null, 'inline')
        // Upload file to simulation
        .then(function (resp) {
          // Capture file content in case we need to parse it
          _this.fileContent[key] = resp.data;
          return simulationsHelper.addFileForSimulationWithContents(_this.props.simulation, key, name, resp.data);
        })
        // update file id in simulation metadata
        .then(function (resp) {
          var _id = resp._id; // file Id, custom response
          var newSim = (0, _deepClone2.default)(_this.props.simulation);
          newSim.metadata.inputFolder.files[key] = _id;
          _this.setState(_defineProperty({}, key, _id));
          return simulationsHelper.saveSimulation(newSim);
        }));
      }
    });
 
    props.inputFileKeys.forEach(function (_ref2) {
      var key = _ref2.key,
          name = _ref2.name;
 
      // Process simulation file if any
      Promise.all(promises).then(function () {
        var inputFile = _this.props.simulation.metadata.inputFolder.files[key];
        if (!inputFile) {
          promises.push(simulationsHelper.addEmptyFileForSimulation(_this.props.simulation, key, name).then(function (resp) {
            var _id = resp.data._id; // itemId
            var newSim = (0, _deepClone2.default)(_this.props.simulation);
            newSim.metadata.inputFolder.files[key] = _id;
            _this.setState(_defineProperty({}, key, _id));
            var internalPromise = simulationsHelper.saveSimulation(newSim);
            internalPromise.then(function () {
              return _this.props.updateSimulation(newSim);
            });
            return internalPromise;
          }));
        } else {
          _this.setState(_defineProperty({}, key, inputFile));
        }
      });
    });
 
    // Handle simput data model if any
    var jsonData = _this.props.simulation.steps[_this.props.step].metadata.model;
    if (jsonData) {
      if (typeof jsonData === 'string') {
        _this.state.jsonData = props.simputModelDecorator(JSON.parse(jsonData), props);
      } else {
        console.log('Can not convert jsonData (?)', jsonData);
      }
    } else {
      // Generic empty value
      jsonData = props.simputModelDecorator(props.initialDataModel, props);
 
      // Make sure all previous network calls are done
      Promise.all(promises).then(function () {
        var updateSimulationStep = function updateSimulationStep() {
          jsonData = props.simputModelDecorator(jsonData, props);
          _this.setState({ jsonData: jsonData });
          // Update step metadata
          _network2.default.updateSimulationStep(_this.props.simulation._id, _this.props.step, {
            metadata: { model: JSON.stringify(jsonData) }
          }).then(function (resp) {
            var newSim = (0, _deepClone2.default)(_this.props.simulation);
            newSim.steps[_this.props.step].metadata.model = JSON.stringify(jsonData);
            _this.props.saveSimulation(newSim);
          });
        };
 
        // We don't have any data model but we might be able to generate one
        // by parsing data
        if (simputModule.parse && props.inputFileKeys.filter(function (i) {
          return i.parse;
        }).length) {
          // Ensure we have content for all the file we need to parse
          props.inputFileKeys.filter(function (i) {
            return i.parse;
          }).forEach(function (_ref3) {
            var key = _ref3.key,
                name = _ref3.name;
 
            if (!_this.fileContent[key] && _this.props.simulation.metadata.inputFolder.files[key]) {
              var internalPromise = _network2.default.downloadFile(_this.props.simulation.metadata.inputFolder.files[key], 0, null, 'inline');
              promises.push(internalPromise);
              internalPromise.then(function (resp) {
                _this.fileContent[key] = resp.data;
              });
            }
          });
          Promise.all(promises).then(function () {
            var fileNameToContentMap = {};
            props.inputFileKeys.filter(function (i) {
              return i.parse;
            }).forEach(function (_ref4) {
              var key = _ref4.key,
                  name = _ref4.name;
 
              fileNameToContentMap[name] = _this.fileContent[key];
            });
            try {
              jsonData = Object.assign({}, jsonData, {
                data: simputModule.parse(props.simputType, fileNameToContentMap)
              });
              updateSimulationStep();
            } catch (parseError) {
              jsonData = props.initialDataModel;
              updateSimulationStep();
              console.log('Parsing error', parseError);
              console.log('Data to parse', fileNameToContentMap);
            }
          });
        } else {
          updateSimulationStep();
        }
      });
    }
    return _this;
  }
 
  _createClass(SimputReact, [{
    key: 'componentWillUnmount',
    value: function componentWillUnmount() {
      this.saveModel();
    }
  }, {
    key: 'saveModel',
    value: function saveModel() {
      var _this2 = this;
 
      // Update step metadata with the latest json data model
      var jsonData = this.props.simputModelDecorator(this.state.jsonData, this.props);
      var model = JSON.stringify(jsonData);
      _network2.default.updateSimulationStep(this.props.simulation._id, this.props.step, {
        metadata: { model: model }
      }).then(function (resp) {
        var newSim = (0, _deepClone2.default)(_this2.props.simulation);
        newSim.steps[_this2.props.step].metadata.model = model;
        _this2.props.saveSimulation(newSim);
      }).catch(function (error) {
        console.error('problem saving model');
      });
 
      // Generate new input files and update content on server
      try {
        var convertedData = _Simput2.default.types[this.props.simputType].convert(jsonData);
        if (!convertedData.errors || convertedData.errors.length === 0) {
          // No error in convertion
          if (this.state.__export__) {
            var fileId = this.state.__export__;
            var content = JSON.stringify(convertedData);
            var blob = new Blob([content], { type: 'text/plain' });
            _network2.default.updateFileContent(fileId, content.length).then(function (upload) {
              _network2.default.uploadChunk(upload.data._id, 0, blob);
            }).catch(function (err) {
              console.log('Error update content __export__', err);
            });
 
            var simulationStepIndex = this.props.simulation.disabled.indexOf(this.props.nextStep);
            if (simulationStepIndex !== -1) {
              var newSim = (0, _deepClone2.default)(this.props.simulation);
              newSim.disabled.splice(simulationStepIndex, 1);
              this.props.patchSimulation(newSim);
            }
          } else {
            Object.keys(convertedData.results).forEach(function (fileName) {
              var fileKey = _this2.fileNameToKeyMap[fileName];
              if (_this2.state[fileKey]) {
                var _fileId = _this2.state[fileKey];
                var _content = convertedData.results[fileName];
                var _blob = new Blob([_content], { type: 'text/plain' });
                _network2.default.updateFileContent(_fileId, _content.length).then(function (upload) {
                  _network2.default.uploadChunk(upload.data._id, 0, _blob);
                }).catch(function (err) {
                  console.log('Error update content', fileKey, fileName, err);
                });
 
                var _simulationStepIndex = _this2.props.simulation.disabled.indexOf(_this2.props.nextStep);
                if (_simulationStepIndex !== -1) {
                  var _newSim = (0, _deepClone2.default)(_this2.props.simulation);
                  _newSim.disabled.splice(_simulationStepIndex, 1);
                  _this2.props.patchSimulation(_newSim);
                }
              } else {
                console.log('No file id associated with generated file name: ' + fileName);
                console.log(fileName, _this2.fileNameToKeyMap, _this2.state);
              }
            });
          }
        } else {
          console.error('Got errors when generating files from simput model: ');
          convertedData.errors.forEach(function (error) {
            return console.error(error);
          });
        }
      } catch (e) {
        console.error('Error when generating files from simput model: ', e);
      }
    }
  }, {
    key: 'updateActive',
    value: function updateActive(viewId, index) {
      var data = (0, _modelGenerator2.default)(_Simput2.default.types[this.props.simputType].model, this.state.jsonData, viewId, index, this.state.labels.activeLabels.attributes, this.state.help);
      var viewData = this.state.jsonData.data[viewId][index];
      this.setState({ data: data, viewData: viewData });
      setImmediate(this.saveModel);
    }
  }, {
    key: 'updateViewData',
    value: function updateViewData(newData) {
      var data = this.state.viewData;
      var keypath = newData.id.split('.');
      var attrName = keypath.shift();
 
      data[attrName][keypath.join('.')].value = newData.value;
      this.setState({ viewData: data });
    }
  }, {
    key: 'render',
    value: function render() {
      if (!this.state.jsonData) {
        console.log('no jsonData in state');
        return null;
      }
 
      return _react2.default.createElement(
        'div',
        { className: _PageWithMenu2.default.container },
        _react2.default.createElement(_ViewMenu2.default, {
          className: _PageWithMenu2.default.menu20,
          data: this.state.jsonData,
          model: _Simput2.default.types[this.props.simputType].model,
          labels: this.state.labels,
          onChange: this.updateActive
        }),
        _react2.default.createElement(
          'div',
          { className: _PageWithMenu2.default.content },
          _react2.default.createElement(_PropertyPanel2.default, {
            className: _PageWithMenu2.default.rootContainer,
            input: this.state.data,
            labels: this.state.labels,
            viewData: this.state.viewData,
            onChange: this.updateViewData
          })
        )
      );
    }
  }]);
 
  return SimputReact;
}(_react2.default.Component);
 
exports.default = SimputReact;
 
 
SimputReact.propTypes = {
  simputType: _propTypes2.default.string,
  inputFileKeys: _propTypes2.default.array, // [{ key: 'sh', name: 'run.sh', parse: false }, ...]
  initialDataModel: _propTypes2.default.object,
  nextStep: _propTypes2.default.string,
  simputModelDecorator: _propTypes2.default.func,
 
  project: _propTypes2.default.object.isRequired,
  simulation: _propTypes2.default.object.isRequired,
  step: _propTypes2.default.string.isRequired,
  saveSimulation: _propTypes2.default.func,
  updateSimulation: _propTypes2.default.func,
  patchSimulation: _propTypes2.default.func
};
 
SimputReact.defaultProps = {
  simputType: '',
  inputFileKeys: [],
  initialDataModel: null,
  nextStep: 'Simulation',
  simputModelDecorator: function simputModelDecorator(m, props, asynReady) {
    return m;
  },
  saveSimulation: saveSimulation,
  updateSimulation: updateSimulation,
  patchSimulation: patchSimulation
};