diff options
| author | Georgios Andreadis <G.Andreadis@student.tudelft.nl> | 2017-10-04 23:23:09 +0200 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2017-10-04 23:23:09 +0200 |
| commit | fcaaae65d34003874c76e0c01134dedf94248e09 (patch) | |
| tree | 2aae1422168651e832a1904623f6f5b100fc17ec | |
| parent | 0a62dfb55c5700013d42a589b930c7448e5bff71 (diff) | |
| parent | 606d1de0be09f3597165248f65d54e158a13860c (diff) | |
Merge pull request #42 from atlarge-research/auto-reformat
Standardize code format
240 files changed, 6445 insertions, 5673 deletions
diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 00000000..823e6853 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,15 @@ +# EditorConfig helps developers define and maintain consistent +# coding styles between different editors and IDEs +# editorconfig.org +root = true + +[*] +indent_style = space +indent_size = 2 + +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[*.md] +trim_trailing_whitespace = false @@ -9,6 +9,7 @@ Collaborative Datacenter Simulation and Exploration for Everybody [](https://travis-ci.org/atlarge-research/opendc-frontend) [](https://opensource.org/licenses/MIT) +[](https://github.com/prettier/prettier) The user-facing component of the OpenDC stack, allowing users to build and interact with their own (virtual) datacenters. Built in *React.js* and *Redux*, with the help of `create-react-app`. diff --git a/package.json b/package.json index 00e56349..c6c0994a 100644 --- a/package.json +++ b/package.json @@ -20,10 +20,13 @@ "dependencies": { "approximate-number": "^2.0.0", "classnames": "^2.2.5", + "husky": "^0.14.3", "isomorphic-fetch": "^2.2.1", "konva": "^1.6.8", + "lint-staged": "^4.2.3", "node-sass-chokidar": "^0.0.3", "npm-run-all": "^4.1.1", + "prettier": "^1.7.4", "prop-types": "^15.5.10", "react": "^15.6.1", "react-document-title": "^2.0.3", @@ -45,7 +48,14 @@ "svgsaver": "^0.9.0", "victory": "^0.22.2" }, + "lint-staged": { + "src/**/*.{js,jsx,json}": [ + "prettier --write", + "git add" + ] + }, "scripts": { + "precommit": "lint-staged", "build-css": "node-sass-chokidar src/ -o src/", "watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive", "start-js": "react-scripts start", diff --git a/public/index.html b/public/index.html index cf0ab795..a076ac66 100644 --- a/public/index.html +++ b/public/index.html @@ -1,40 +1,40 @@ <!doctype html> <html lang="en"> <head> - <meta charset="utf-8"> - <title>OpenDC</title> + <meta charset="utf-8"> + <title>OpenDC</title> - <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> - <meta name="theme-color" content="#000000"> + <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> + <meta name="theme-color" content="#000000"> - <!-- Standard meta tags --> - <meta name="description" content="Collaborative Datacenter Simulation and Exploration for Everybody"> - <meta name="author" content="Alexandru Iosup, Leon Overweel, Georgios Andreadis, Matthijs Bijman"> - <meta name="keywords" content="OpenDC, Datacenter, Simulation, Simulator, Collaborative, Distributed, Cluster"> + <!-- Standard meta tags --> + <meta name="description" content="Collaborative Datacenter Simulation and Exploration for Everybody"> + <meta name="author" content="Alexandru Iosup, Leon Overweel, Georgios Andreadis, Matthijs Bijman"> + <meta name="keywords" content="OpenDC, Datacenter, Simulation, Simulator, Collaborative, Distributed, Cluster"> - <!-- OpenGraph meta tags --> - <meta property="og:title" content="OpenDC: Collaborative Datacenter Simulation and Exploration for Everybody"> - <meta property="og:type" content="website"> - <meta property="og:image" content="http://opendc.org/img/logo.png"> - <meta property="og:url" content="http://opendc.org/"> - <meta property="og:description" - content="OpenDC provides collaborative online datacenter modeling, diverse and effective datacenter + <!-- OpenGraph meta tags --> + <meta property="og:title" content="OpenDC: Collaborative Datacenter Simulation and Exploration for Everybody"> + <meta property="og:type" content="website"> + <meta property="og:image" content="http://opendc.org/img/logo.png"> + <meta property="og:url" content="http://opendc.org/"> + <meta property="og:description" + content="OpenDC provides collaborative online datacenter modeling, diverse and effective datacenter simulation, and exploratory datacenter performance feedback."> - <meta property="og:locale" content="en_US"> + <meta property="og:locale" content="en_US"> - <link rel="manifest" href="/manifest.json"> - <link rel="shortcut icon" href="/favicon.ico"> + <link rel="manifest" href="/manifest.json"> + <link rel="shortcut icon" href="/favicon.ico"> - <meta name="google-signin-client_id" content="%REACT_APP_OAUTH_CLIENT_ID%"> + <meta name="google-signin-client_id" content="%REACT_APP_OAUTH_CLIENT_ID%"> - <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" - integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous"> - <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet"> - <script src="https://use.fontawesome.com/ece66a2e7c.js"></script> + <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" + integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous"> + <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet"> + <script src="https://use.fontawesome.com/ece66a2e7c.js"></script> </head> <body data-spy="scroll" data-target="#navbar"> <noscript> - You need to enable JavaScript to run this app. + You need to enable JavaScript to run this app. </noscript> <div id="root"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" diff --git a/src/actions/auth.js b/src/actions/auth.js index 2ca6a986..45e2eb35 100644 --- a/src/actions/auth.js +++ b/src/actions/auth.js @@ -3,21 +3,21 @@ export const LOG_IN_SUCCEEDED = "LOG_IN_SUCCEEDED"; export const LOG_OUT = "LOG_OUT"; export function logIn(payload) { - return { - type: LOG_IN, - payload - }; + return { + type: LOG_IN, + payload + }; } export function logInSucceeded(payload) { - return { - type: LOG_IN_SUCCEEDED, - payload - }; + return { + type: LOG_IN_SUCCEEDED, + payload + }; } export function logOut() { - return { - type: LOG_OUT - }; + return { + type: LOG_OUT + }; } diff --git a/src/actions/experiments.js b/src/actions/experiments.js index c64df019..b5709981 100644 --- a/src/actions/experiments.js +++ b/src/actions/experiments.js @@ -1,33 +1,34 @@ -export const FETCH_EXPERIMENTS_OF_SIMULATION = "FETCH_EXPERIMENTS_OF_SIMULATION"; +export const FETCH_EXPERIMENTS_OF_SIMULATION = + "FETCH_EXPERIMENTS_OF_SIMULATION"; export const ADD_EXPERIMENT = "ADD_EXPERIMENT"; export const DELETE_EXPERIMENT = "DELETE_EXPERIMENT"; export const OPEN_EXPERIMENT_SUCCEEDED = "OPEN_EXPERIMENT_SUCCEEDED"; export function fetchExperimentsOfSimulation(simulationId) { - return { - type: FETCH_EXPERIMENTS_OF_SIMULATION, - simulationId - }; + return { + type: FETCH_EXPERIMENTS_OF_SIMULATION, + simulationId + }; } export function addExperiment(experiment) { - return { - type: ADD_EXPERIMENT, - experiment - }; + return { + type: ADD_EXPERIMENT, + experiment + }; } export function deleteExperiment(id) { - return { - type: DELETE_EXPERIMENT, - id - }; + return { + type: DELETE_EXPERIMENT, + id + }; } export function openExperimentSucceeded(simulationId, experimentId) { - return { - type: OPEN_EXPERIMENT_SUCCEEDED, - simulationId, - experimentId - } + return { + type: OPEN_EXPERIMENT_SUCCEEDED, + simulationId, + experimentId + }; } diff --git a/src/actions/interaction-level.js b/src/actions/interaction-level.js index 2003f45e..31120146 100644 --- a/src/actions/interaction-level.js +++ b/src/actions/interaction-level.js @@ -4,47 +4,47 @@ export const GO_FROM_RACK_TO_MACHINE = "GO_FROM_RACK_TO_MACHINE"; export const GO_DOWN_ONE_INTERACTION_LEVEL = "GO_DOWN_ONE_INTERACTION_LEVEL"; export function goFromBuildingToRoom(roomId) { - return (dispatch, getState) => { - const {interactionLevel} = getState(); - if (interactionLevel.mode !== "BUILDING") { - return; - } + return (dispatch, getState) => { + const { interactionLevel } = getState(); + if (interactionLevel.mode !== "BUILDING") { + return; + } - dispatch({ - type: GO_FROM_BUILDING_TO_ROOM, - roomId - }); - }; + dispatch({ + type: GO_FROM_BUILDING_TO_ROOM, + roomId + }); + }; } export function goFromRoomToRack(tileId) { - return (dispatch, getState) => { - const {interactionLevel} = getState(); - if (interactionLevel.mode !== "ROOM") { - return; - } - dispatch({ - type: GO_FROM_ROOM_TO_RACK, - tileId - }); - }; + return (dispatch, getState) => { + const { interactionLevel } = getState(); + if (interactionLevel.mode !== "ROOM") { + return; + } + dispatch({ + type: GO_FROM_ROOM_TO_RACK, + tileId + }); + }; } export function goFromRackToMachine(position) { - return (dispatch, getState) => { - const {interactionLevel} = getState(); - if (interactionLevel.mode !== "RACK") { - return; - } - dispatch({ - type: GO_FROM_RACK_TO_MACHINE, - position - }); - }; + return (dispatch, getState) => { + const { interactionLevel } = getState(); + if (interactionLevel.mode !== "RACK") { + return; + } + dispatch({ + type: GO_FROM_RACK_TO_MACHINE, + position + }); + }; } export function goDownOneInteractionLevel() { - return { - type: GO_DOWN_ONE_INTERACTION_LEVEL - }; + return { + type: GO_DOWN_ONE_INTERACTION_LEVEL + }; } diff --git a/src/actions/map.js b/src/actions/map.js index 47d4714d..82546c00 100644 --- a/src/actions/map.js +++ b/src/actions/map.js @@ -1,8 +1,8 @@ import { - MAP_MAX_SCALE, - MAP_MIN_SCALE, - MAP_SCALE_PER_EVENT, - MAP_SIZE_IN_PIXELS + MAP_MAX_SCALE, + MAP_MIN_SCALE, + MAP_SCALE_PER_EVENT, + MAP_SIZE_IN_PIXELS } from "../components/app/map/MapConstants"; export const SET_MAP_POSITION = "SET_MAP_POSITION"; @@ -10,67 +10,84 @@ export const SET_MAP_DIMENSIONS = "SET_MAP_DIMENSIONS"; export const SET_MAP_SCALE = "SET_MAP_SCALE"; export function setMapPosition(x, y) { - return { - type: SET_MAP_POSITION, - x, - y - }; + return { + type: SET_MAP_POSITION, + x, + y + }; } export function setMapDimensions(width, height) { - return { - type: SET_MAP_DIMENSIONS, - width, - height - }; + return { + type: SET_MAP_DIMENSIONS, + width, + height + }; } export function setMapScale(scale) { - return { - type: SET_MAP_SCALE, - scale - }; + return { + type: SET_MAP_SCALE, + scale + }; } export function zoomInOnCenter(zoomIn) { - return (dispatch, getState) => { - const state = getState(); + return (dispatch, getState) => { + const state = getState(); - dispatch(zoomInOnPosition(zoomIn, state.map.dimensions.width / 2, state.map.dimensions.height / 2)); - } + dispatch( + zoomInOnPosition( + zoomIn, + state.map.dimensions.width / 2, + state.map.dimensions.height / 2 + ) + ); + }; } export function zoomInOnPosition(zoomIn, x, y) { - return (dispatch, getState) => { - const state = getState(); + return (dispatch, getState) => { + const state = getState(); - const centerPoint = { - x: x / state.map.scale - state.map.position.x / state.map.scale, - y: y / state.map.scale - state.map.position.y / state.map.scale, - }; - const newScale = zoomIn ? state.map.scale * MAP_SCALE_PER_EVENT : state.map.scale / MAP_SCALE_PER_EVENT; - const boundedScale = Math.min(Math.max(MAP_MIN_SCALE, newScale), MAP_MAX_SCALE); + const centerPoint = { + x: x / state.map.scale - state.map.position.x / state.map.scale, + y: y / state.map.scale - state.map.position.y / state.map.scale + }; + const newScale = zoomIn + ? state.map.scale * MAP_SCALE_PER_EVENT + : state.map.scale / MAP_SCALE_PER_EVENT; + const boundedScale = Math.min( + Math.max(MAP_MIN_SCALE, newScale), + MAP_MAX_SCALE + ); - const newX = -(centerPoint.x - x / boundedScale) * boundedScale; - const newY = -(centerPoint.y - y / boundedScale) * boundedScale; + const newX = -(centerPoint.x - x / boundedScale) * boundedScale; + const newY = -(centerPoint.y - y / boundedScale) * boundedScale; - dispatch(setMapPositionWithBoundsCheck(newX, newY)); - dispatch(setMapScale(boundedScale)); - } + dispatch(setMapPositionWithBoundsCheck(newX, newY)); + dispatch(setMapScale(boundedScale)); + }; } export function setMapPositionWithBoundsCheck(x, y) { - return (dispatch, getState) => { - const state = getState(); + return (dispatch, getState) => { + const state = getState(); - const scaledMapSize = MAP_SIZE_IN_PIXELS * state.map.scale; - const updatedX = x > 0 ? 0 : - (x < -scaledMapSize + state.map.dimensions.width - ? -scaledMapSize + state.map.dimensions.width : x); - const updatedY = y > 0 ? 0 : - (y < -scaledMapSize + state.map.dimensions.height - ? -scaledMapSize + state.map.dimensions.height : y); + const scaledMapSize = MAP_SIZE_IN_PIXELS * state.map.scale; + const updatedX = + x > 0 + ? 0 + : x < -scaledMapSize + state.map.dimensions.width + ? -scaledMapSize + state.map.dimensions.width + : x; + const updatedY = + y > 0 + ? 0 + : y < -scaledMapSize + state.map.dimensions.height + ? -scaledMapSize + state.map.dimensions.height + : y; - dispatch(setMapPosition(updatedX, updatedY)); - } + dispatch(setMapPosition(updatedX, updatedY)); + }; } diff --git a/src/actions/modals/experiments.js b/src/actions/modals/experiments.js index 43a53a3a..df939fa5 100644 --- a/src/actions/modals/experiments.js +++ b/src/actions/modals/experiments.js @@ -2,13 +2,13 @@ export const OPEN_NEW_EXPERIMENT_MODAL = "OPEN_NEW_EXPERIMENT_MODAL"; export const CLOSE_NEW_EXPERIMENT_MODAL = "CLOSE_EXPERIMENT_MODAL"; export function openNewExperimentModal() { - return { - type: OPEN_NEW_EXPERIMENT_MODAL - }; + return { + type: OPEN_NEW_EXPERIMENT_MODAL + }; } export function closeNewExperimentModal() { - return { - type: CLOSE_NEW_EXPERIMENT_MODAL - }; + return { + type: CLOSE_NEW_EXPERIMENT_MODAL + }; } diff --git a/src/actions/modals/profile.js b/src/actions/modals/profile.js index 421e7602..ee52610c 100644 --- a/src/actions/modals/profile.js +++ b/src/actions/modals/profile.js @@ -2,13 +2,13 @@ export const OPEN_DELETE_PROFILE_MODAL = "OPEN_DELETE_PROFILE_MODAL"; export const CLOSE_DELETE_PROFILE_MODAL = "CLOSE_DELETE_PROFILE_MODAL"; export function openDeleteProfileModal() { - return { - type: OPEN_DELETE_PROFILE_MODAL - }; + return { + type: OPEN_DELETE_PROFILE_MODAL + }; } export function closeDeleteProfileModal() { - return { - type: CLOSE_DELETE_PROFILE_MODAL - }; + return { + type: CLOSE_DELETE_PROFILE_MODAL + }; } diff --git a/src/actions/modals/simulations.js b/src/actions/modals/simulations.js index 8281238d..b11d356c 100644 --- a/src/actions/modals/simulations.js +++ b/src/actions/modals/simulations.js @@ -2,13 +2,13 @@ export const OPEN_NEW_SIMULATION_MODAL = "OPEN_NEW_SIMULATION_MODAL"; export const CLOSE_NEW_SIMULATION_MODAL = "CLOSE_SIMULATION_MODAL"; export function openNewSimulationModal() { - return { - type: OPEN_NEW_SIMULATION_MODAL - }; + return { + type: OPEN_NEW_SIMULATION_MODAL + }; } export function closeNewSimulationModal() { - return { - type: CLOSE_NEW_SIMULATION_MODAL - }; + return { + type: CLOSE_NEW_SIMULATION_MODAL + }; } diff --git a/src/actions/modals/topology.js b/src/actions/modals/topology.js index b8e297e0..7ee16522 100644 --- a/src/actions/modals/topology.js +++ b/src/actions/modals/topology.js @@ -10,61 +10,61 @@ export const OPEN_DELETE_MACHINE_MODAL = "OPEN_DELETE_MACHINE_MODAL"; export const CLOSE_DELETE_MACHINE_MODAL = "CLOSE_DELETE_MACHINE_MODAL"; export function openEditRoomNameModal() { - return { - type: OPEN_EDIT_ROOM_NAME_MODAL - }; + return { + type: OPEN_EDIT_ROOM_NAME_MODAL + }; } export function closeEditRoomNameModal() { - return { - type: CLOSE_EDIT_ROOM_NAME_MODAL - }; + return { + type: CLOSE_EDIT_ROOM_NAME_MODAL + }; } export function openDeleteRoomModal() { - return { - type: OPEN_DELETE_ROOM_MODAL - }; + return { + type: OPEN_DELETE_ROOM_MODAL + }; } export function closeDeleteRoomModal() { - return { - type: CLOSE_DELETE_ROOM_MODAL - }; + return { + type: CLOSE_DELETE_ROOM_MODAL + }; } export function openEditRackNameModal() { - return { - type: OPEN_EDIT_RACK_NAME_MODAL - }; + return { + type: OPEN_EDIT_RACK_NAME_MODAL + }; } export function closeEditRackNameModal() { - return { - type: CLOSE_EDIT_RACK_NAME_MODAL - }; + return { + type: CLOSE_EDIT_RACK_NAME_MODAL + }; } export function openDeleteRackModal() { - return { - type: OPEN_DELETE_RACK_MODAL - }; + return { + type: OPEN_DELETE_RACK_MODAL + }; } export function closeDeleteRackModal() { - return { - type: CLOSE_DELETE_RACK_MODAL - }; + return { + type: CLOSE_DELETE_RACK_MODAL + }; } export function openDeleteMachineModal() { - return { - type: OPEN_DELETE_MACHINE_MODAL - }; + return { + type: OPEN_DELETE_MACHINE_MODAL + }; } export function closeDeleteMachineModal() { - return { - type: CLOSE_DELETE_MACHINE_MODAL - }; + return { + type: CLOSE_DELETE_MACHINE_MODAL + }; } diff --git a/src/actions/objects.js b/src/actions/objects.js index 60885471..80b56c0c 100644 --- a/src/actions/objects.js +++ b/src/actions/objects.js @@ -1,41 +1,48 @@ export const ADD_TO_STORE = "ADD_TO_STORE"; export const ADD_PROP_TO_STORE_OBJECT = "ADD_PROP_TO_STORE_OBJECT"; -export const ADD_ID_TO_STORE_OBJECT_LIST_PROP = "ADD_ID_TO_STORE_OBJECT_LIST_PROP"; -export const REMOVE_ID_FROM_STORE_OBJECT_LIST_PROP = "REMOVE_ID_FROM_STORE_OBJECT_LIST_PROP"; +export const ADD_ID_TO_STORE_OBJECT_LIST_PROP = + "ADD_ID_TO_STORE_OBJECT_LIST_PROP"; +export const REMOVE_ID_FROM_STORE_OBJECT_LIST_PROP = + "REMOVE_ID_FROM_STORE_OBJECT_LIST_PROP"; export function addToStore(objectType, object) { - return { - type: ADD_TO_STORE, - objectType, - object - }; + return { + type: ADD_TO_STORE, + objectType, + object + }; } export function addPropToStoreObject(objectType, objectId, propObject) { - return { - type: ADD_PROP_TO_STORE_OBJECT, - objectType, - objectId, - propObject - }; + return { + type: ADD_PROP_TO_STORE_OBJECT, + objectType, + objectId, + propObject + }; } export function addIdToStoreObjectListProp(objectType, objectId, propName, id) { - return { - type: ADD_ID_TO_STORE_OBJECT_LIST_PROP, - objectType, - objectId, - propName, - id - }; + return { + type: ADD_ID_TO_STORE_OBJECT_LIST_PROP, + objectType, + objectId, + propName, + id + }; } -export function removeIdFromStoreObjectListProp(objectType, objectId, propName, id) { - return { - type: REMOVE_ID_FROM_STORE_OBJECT_LIST_PROP, - objectType, - objectId, - propName, - id - }; +export function removeIdFromStoreObjectListProp( + objectType, + objectId, + propName, + id +) { + return { + type: REMOVE_ID_FROM_STORE_OBJECT_LIST_PROP, + objectType, + objectId, + propName, + id + }; } diff --git a/src/actions/profile.js b/src/actions/profile.js index b28b04f6..e69de29b 100644 --- a/src/actions/profile.js +++ b/src/actions/profile.js @@ -1,3 +0,0 @@ - - - diff --git a/src/actions/simulation/load-metric.js b/src/actions/simulation/load-metric.js index e426a7d2..c59e3596 100644 --- a/src/actions/simulation/load-metric.js +++ b/src/actions/simulation/load-metric.js @@ -1,8 +1,8 @@ export const CHANGE_LOAD_METRIC = "CHANGE_LOAD_METRIC"; export function changeLoadMetric(metric) { - return { - type: CHANGE_LOAD_METRIC, - metric - }; + return { + type: CHANGE_LOAD_METRIC, + metric + }; } diff --git a/src/actions/simulation/playback.js b/src/actions/simulation/playback.js index bddb9a0a..8e913914 100644 --- a/src/actions/simulation/playback.js +++ b/src/actions/simulation/playback.js @@ -1,15 +1,15 @@ export const SET_PLAYING = "SET_PLAYING"; export function playSimulation() { - return { - type: SET_PLAYING, - playing: true - } + return { + type: SET_PLAYING, + playing: true + }; } export function pauseSimulation() { - return { - type: SET_PLAYING, - playing: false - } + return { + type: SET_PLAYING, + playing: false + }; } diff --git a/src/actions/simulation/tick.js b/src/actions/simulation/tick.js index 06066662..a629b340 100644 --- a/src/actions/simulation/tick.js +++ b/src/actions/simulation/tick.js @@ -1,44 +1,49 @@ -import {getDatacenterIdOfTick} from "../../util/timeline"; -import {setCurrentDatacenter} from "../topology/building"; +import { getDatacenterIdOfTick } from "../../util/timeline"; +import { setCurrentDatacenter } from "../topology/building"; export const GO_TO_TICK = "GO_TO_TICK"; export const SET_LAST_SIMULATED_TICK = "SET_LAST_SIMULATED_TICK"; export function incrementTick() { - return (dispatch, getState) => { - const {currentTick} = getState(); - dispatch(goToTick(currentTick + 1)); - } + return (dispatch, getState) => { + const { currentTick } = getState(); + dispatch(goToTick(currentTick + 1)); + }; } export function goToTick(tick) { - return (dispatch, getState) => { - const state = getState(); - - let sections = []; - if (state.currentExperimentId !== -1) { - const sectionIds = state.objects.path[state.objects.experiment[state.currentExperimentId].pathId].sectionIds; - - if (sectionIds) { - sections = sectionIds.map(sectionId => state.objects.section[sectionId]); - } - } - - const newDatacenterId = getDatacenterIdOfTick(tick, sections); - if (state.currentDatacenterId !== newDatacenterId) { - dispatch(setCurrentDatacenter(newDatacenterId)); - } - - dispatch({ - type: GO_TO_TICK, - tick - }); + return (dispatch, getState) => { + const state = getState(); + + let sections = []; + if (state.currentExperimentId !== -1) { + const sectionIds = + state.objects.path[ + state.objects.experiment[state.currentExperimentId].pathId + ].sectionIds; + + if (sectionIds) { + sections = sectionIds.map( + sectionId => state.objects.section[sectionId] + ); + } + } + + const newDatacenterId = getDatacenterIdOfTick(tick, sections); + if (state.currentDatacenterId !== newDatacenterId) { + dispatch(setCurrentDatacenter(newDatacenterId)); } + + dispatch({ + type: GO_TO_TICK, + tick + }); + }; } export function setLastSimulatedTick(tick) { - return { - type: SET_LAST_SIMULATED_TICK, - tick - } + return { + type: SET_LAST_SIMULATED_TICK, + tick + }; } diff --git a/src/actions/simulations.js b/src/actions/simulations.js index 145ceab2..6da7aa3a 100644 --- a/src/actions/simulations.js +++ b/src/actions/simulations.js @@ -6,47 +6,47 @@ export const DELETE_SIMULATION_SUCCEEDED = "DELETE_SIMULATION_SUCCEEDED"; export const OPEN_SIMULATION_SUCCEEDED = "OPEN_SIMULATION_SUCCEEDED"; export function setAuthVisibilityFilter(filter) { - return { - type: SET_AUTH_VISIBILITY_FILTER, - filter - }; + return { + type: SET_AUTH_VISIBILITY_FILTER, + filter + }; } export function addSimulation(name) { - return (dispatch, getState) => { - const {auth} = getState(); - dispatch({ - type: ADD_SIMULATION, - name, - userId: auth.userId - }); - }; + return (dispatch, getState) => { + const { auth } = getState(); + dispatch({ + type: ADD_SIMULATION, + name, + userId: auth.userId + }); + }; } export function addSimulationSucceeded(authorization) { - return { - type: ADD_SIMULATION_SUCCEEDED, - authorization - }; + return { + type: ADD_SIMULATION_SUCCEEDED, + authorization + }; } export function deleteSimulation(id) { - return { - type: DELETE_SIMULATION, - id - }; + return { + type: DELETE_SIMULATION, + id + }; } export function deleteSimulationSucceeded(id) { - return { - type: DELETE_SIMULATION_SUCCEEDED, - id - }; + return { + type: DELETE_SIMULATION_SUCCEEDED, + id + }; } export function openSimulationSucceeded(id) { - return { - type: OPEN_SIMULATION_SUCCEEDED, - id - }; + return { + type: OPEN_SIMULATION_SUCCEEDED, + id + }; } diff --git a/src/actions/states.js b/src/actions/states.js index 29baa326..b3a355a2 100644 --- a/src/actions/states.js +++ b/src/actions/states.js @@ -1,9 +1,9 @@ export const ADD_BATCH_TO_STATES = "ADD_BATCH_TO_STATES"; export function addBatchToStates(objectType, objects) { - return { - type: ADD_BATCH_TO_STATES, - objectType, - objects - }; + return { + type: ADD_BATCH_TO_STATES, + objectType, + objects + }; } diff --git a/src/actions/topology/building.js b/src/actions/topology/building.js index 019a473c..5aef2932 100644 --- a/src/actions/topology/building.js +++ b/src/actions/topology/building.js @@ -1,92 +1,99 @@ export const SET_CURRENT_DATACENTER = "SET_CURRENT_DATACENTER"; export const RESET_CURRENT_DATACENTER = "RESET_CURRENT_DATACENTER"; export const START_NEW_ROOM_CONSTRUCTION = "START_NEW_ROOM_CONSTRUCTION"; -export const START_NEW_ROOM_CONSTRUCTION_SUCCEEDED = "START_NEW_ROOM_CONSTRUCTION_SUCCEEDED"; +export const START_NEW_ROOM_CONSTRUCTION_SUCCEEDED = + "START_NEW_ROOM_CONSTRUCTION_SUCCEEDED"; export const FINISH_NEW_ROOM_CONSTRUCTION = "FINISH_NEW_ROOM_CONSTRUCTION"; export const CANCEL_NEW_ROOM_CONSTRUCTION = "CANCEL_NEW_ROOM_CONSTRUCTION"; -export const CANCEL_NEW_ROOM_CONSTRUCTION_SUCCEEDED = "CANCEL_NEW_ROOM_CONSTRUCTION_SUCCEEDED"; +export const CANCEL_NEW_ROOM_CONSTRUCTION_SUCCEEDED = + "CANCEL_NEW_ROOM_CONSTRUCTION_SUCCEEDED"; export const ADD_TILE = "ADD_TILE"; export const DELETE_TILE = "DELETE_TILE"; export function setCurrentDatacenter(datacenterId) { - return { - type: SET_CURRENT_DATACENTER, - datacenterId - }; + return { + type: SET_CURRENT_DATACENTER, + datacenterId + }; } export function resetCurrentDatacenter() { - return { - type: RESET_CURRENT_DATACENTER - }; + return { + type: RESET_CURRENT_DATACENTER + }; } export function startNewRoomConstruction() { - return { - type: START_NEW_ROOM_CONSTRUCTION - }; + return { + type: START_NEW_ROOM_CONSTRUCTION + }; } export function startNewRoomConstructionSucceeded(roomId) { - return { - type: START_NEW_ROOM_CONSTRUCTION_SUCCEEDED, - roomId - }; + return { + type: START_NEW_ROOM_CONSTRUCTION_SUCCEEDED, + roomId + }; } export function finishNewRoomConstruction() { - return (dispatch, getState) => { - const {objects, construction} = getState(); - if (objects.room[construction.currentRoomInConstruction].tileIds.length === 0) { - dispatch(cancelNewRoomConstruction()); - return; - } + return (dispatch, getState) => { + const { objects, construction } = getState(); + if ( + objects.room[construction.currentRoomInConstruction].tileIds.length === 0 + ) { + dispatch(cancelNewRoomConstruction()); + return; + } - dispatch({ - type: FINISH_NEW_ROOM_CONSTRUCTION - }); - }; + dispatch({ + type: FINISH_NEW_ROOM_CONSTRUCTION + }); + }; } export function cancelNewRoomConstruction() { - return { - type: CANCEL_NEW_ROOM_CONSTRUCTION - }; + return { + type: CANCEL_NEW_ROOM_CONSTRUCTION + }; } export function cancelNewRoomConstructionSucceeded() { - return { - type: CANCEL_NEW_ROOM_CONSTRUCTION_SUCCEEDED - }; + return { + type: CANCEL_NEW_ROOM_CONSTRUCTION_SUCCEEDED + }; } export function toggleTileAtLocation(positionX, positionY) { - return (dispatch, getState) => { - const {objects, construction} = getState(); + return (dispatch, getState) => { + const { objects, construction } = getState(); - const tileIds = objects.room[construction.currentRoomInConstruction].tileIds; - for (let index in tileIds) { - if (objects.tile[tileIds[index]].positionX === positionX - && objects.tile[tileIds[index]].positionY === positionY) { - dispatch(deleteTile(tileIds[index])); - return; - } - } - dispatch(addTile(positionX, positionY)); - }; + const tileIds = + objects.room[construction.currentRoomInConstruction].tileIds; + for (let index in tileIds) { + if ( + objects.tile[tileIds[index]].positionX === positionX && + objects.tile[tileIds[index]].positionY === positionY + ) { + dispatch(deleteTile(tileIds[index])); + return; + } + } + dispatch(addTile(positionX, positionY)); + }; } export function addTile(positionX, positionY) { - return { - type: ADD_TILE, - positionX, - positionY - }; + return { + type: ADD_TILE, + positionX, + positionY + }; } export function deleteTile(tileId) { - return { - type: DELETE_TILE, - tileId - } + return { + type: DELETE_TILE, + tileId + }; } diff --git a/src/actions/topology/machine.js b/src/actions/topology/machine.js index 48d88052..56968b7d 100644 --- a/src/actions/topology/machine.js +++ b/src/actions/topology/machine.js @@ -3,23 +3,23 @@ export const ADD_UNIT = "ADD_UNIT"; export const DELETE_UNIT = "DELETE_UNIT"; export function deleteMachine() { - return { - type: DELETE_MACHINE - }; + return { + type: DELETE_MACHINE + }; } export function addUnit(unitType, id) { - return { - type: ADD_UNIT, - unitType, - id - }; + return { + type: ADD_UNIT, + unitType, + id + }; } export function deleteUnit(unitType, index) { - return { - type: DELETE_UNIT, - unitType, - index - }; + return { + type: DELETE_UNIT, + unitType, + index + }; } diff --git a/src/actions/topology/rack.js b/src/actions/topology/rack.js index 043d6190..06988424 100644 --- a/src/actions/topology/rack.js +++ b/src/actions/topology/rack.js @@ -3,21 +3,21 @@ export const DELETE_RACK = "DELETE_RACK"; export const ADD_MACHINE = "ADD_MACHINE"; export function editRackName(name) { - return { - type: EDIT_RACK_NAME, - name - }; + return { + type: EDIT_RACK_NAME, + name + }; } export function deleteRack() { - return { - type: DELETE_RACK - }; + return { + type: DELETE_RACK + }; } export function addMachine(position) { - return { - type: ADD_MACHINE, - position - }; + return { + type: ADD_MACHINE, + position + }; } diff --git a/src/actions/topology/room.js b/src/actions/topology/room.js index 884c7e84..4e0fc3a2 100644 --- a/src/actions/topology/room.js +++ b/src/actions/topology/room.js @@ -1,4 +1,4 @@ -import {findTileWithPosition} from "../../util/tile-calculations"; +import { findTileWithPosition } from "../../util/tile-calculations"; export const EDIT_ROOM_NAME = "EDIT_ROOM_NAME"; export const DELETE_ROOM = "DELETE_ROOM"; @@ -7,42 +7,42 @@ export const STOP_RACK_CONSTRUCTION = "STOP_RACK_CONSTRUCTION"; export const ADD_RACK_TO_TILE = "ADD_RACK_TO_TILE"; export function editRoomName(name) { - return { - type: EDIT_ROOM_NAME, - name - }; + return { + type: EDIT_ROOM_NAME, + name + }; } export function startRackConstruction() { - return { - type: START_RACK_CONSTRUCTION - }; + return { + type: START_RACK_CONSTRUCTION + }; } export function stopRackConstruction() { - return { - type: STOP_RACK_CONSTRUCTION - }; + return { + type: STOP_RACK_CONSTRUCTION + }; } export function addRackToTile(positionX, positionY) { - return (dispatch, getState) => { - const {objects, interactionLevel} = getState(); - const currentRoom = objects.room[interactionLevel.roomId]; - const tiles = currentRoom.tileIds.map(tileId => objects.tile[tileId]); - const tile = findTileWithPosition(tiles, positionX, positionY); + return (dispatch, getState) => { + const { objects, interactionLevel } = getState(); + const currentRoom = objects.room[interactionLevel.roomId]; + const tiles = currentRoom.tileIds.map(tileId => objects.tile[tileId]); + const tile = findTileWithPosition(tiles, positionX, positionY); - if (tile !== null) { - dispatch({ - type: ADD_RACK_TO_TILE, - tileId: tile.id - }); - } - }; + if (tile !== null) { + dispatch({ + type: ADD_RACK_TO_TILE, + tileId: tile.id + }); + } + }; } export function deleteRoom() { - return { - type: DELETE_ROOM - }; + return { + type: DELETE_ROOM + }; } diff --git a/src/actions/users.js b/src/actions/users.js index 04a5b95a..dc393df9 100644 --- a/src/actions/users.js +++ b/src/actions/users.js @@ -1,37 +1,41 @@ -export const FETCH_AUTHORIZATIONS_OF_CURRENT_USER = "FETCH_AUTHORIZATIONS_OF_CURRENT_USER"; -export const FETCH_AUTHORIZATIONS_OF_CURRENT_USER_SUCCEEDED = "FETCH_AUTHORIZATIONS_OF_CURRENT_USER_SUCCEEDED"; +export const FETCH_AUTHORIZATIONS_OF_CURRENT_USER = + "FETCH_AUTHORIZATIONS_OF_CURRENT_USER"; +export const FETCH_AUTHORIZATIONS_OF_CURRENT_USER_SUCCEEDED = + "FETCH_AUTHORIZATIONS_OF_CURRENT_USER_SUCCEEDED"; export const DELETE_CURRENT_USER = "DELETE_CURRENT_USER"; export const DELETE_CURRENT_USER_SUCCEEDED = "DELETE_CURRENT_USER_SUCCEEDED"; export function fetchAuthorizationsOfCurrentUser() { - return (dispatch, getState) => { - const {auth} = getState(); - dispatch({ - type: FETCH_AUTHORIZATIONS_OF_CURRENT_USER, - userId: auth.userId - }); - }; + return (dispatch, getState) => { + const { auth } = getState(); + dispatch({ + type: FETCH_AUTHORIZATIONS_OF_CURRENT_USER, + userId: auth.userId + }); + }; } -export function fetchAuthorizationsOfCurrentUserSucceeded(authorizationsOfCurrentUser) { - return { - type: FETCH_AUTHORIZATIONS_OF_CURRENT_USER_SUCCEEDED, - authorizationsOfCurrentUser - }; +export function fetchAuthorizationsOfCurrentUserSucceeded( + authorizationsOfCurrentUser +) { + return { + type: FETCH_AUTHORIZATIONS_OF_CURRENT_USER_SUCCEEDED, + authorizationsOfCurrentUser + }; } export function deleteCurrentUser() { - return (dispatch, getState) => { - const {auth} = getState(); - dispatch({ - type: DELETE_CURRENT_USER, - userId: auth.userId - }); - }; + return (dispatch, getState) => { + const { auth } = getState(); + dispatch({ + type: DELETE_CURRENT_USER, + userId: auth.userId + }); + }; } export function deleteCurrentUserSucceeded() { - return { - type: DELETE_CURRENT_USER_SUCCEEDED - }; + return { + type: DELETE_CURRENT_USER_SUCCEEDED + }; } diff --git a/src/api/index.js b/src/api/index.js index a26422c0..37c288a3 100644 --- a/src/api/index.js +++ b/src/api/index.js @@ -1,13 +1,13 @@ -import {sendSocketRequest} from "./socket"; +import { sendSocketRequest } from "./socket"; export function sendRequest(request) { - return new Promise((resolve, reject) => { - sendSocketRequest(request, response => { - if (response.status.code === 200) { - resolve(response.content); - } else { - reject(response); - } - }) + return new Promise((resolve, reject) => { + sendSocketRequest(request, response => { + if (response.status.code === 200) { + resolve(response.content); + } else { + reject(response); + } }); + }); } diff --git a/src/api/routes/datacenters.js b/src/api/routes/datacenters.js index df621a62..20cf4935 100644 --- a/src/api/routes/datacenters.js +++ b/src/api/routes/datacenters.js @@ -1,26 +1,26 @@ -import {sendRequest} from "../index"; -import {getById} from "./util"; +import { sendRequest } from "../index"; +import { getById } from "./util"; export function getDatacenter(datacenterId) { - return getById("/datacenters/{datacenterId}", {datacenterId}); + return getById("/datacenters/{datacenterId}", { datacenterId }); } export function getRoomsOfDatacenter(datacenterId) { - return getById("/datacenters/{datacenterId}/rooms", {datacenterId}); + return getById("/datacenters/{datacenterId}/rooms", { datacenterId }); } export function addRoomToDatacenter(room) { - return sendRequest({ - path: "/datacenters/{datacenterId}/rooms", - method: "POST", - parameters: { - body: { - room - }, - path: { - datacenterId: room.datacenterId - }, - query: {} - } - }); + return sendRequest({ + path: "/datacenters/{datacenterId}/rooms", + method: "POST", + parameters: { + body: { + room + }, + path: { + datacenterId: room.datacenterId + }, + query: {} + } + }); } diff --git a/src/api/routes/experiments.js b/src/api/routes/experiments.js index 84edae2f..f61698c5 100644 --- a/src/api/routes/experiments.js +++ b/src/api/routes/experiments.js @@ -1,29 +1,33 @@ -import {deleteById, getById} from "./util"; +import { deleteById, getById } from "./util"; export function getExperiment(experimentId) { - return getById("/experiments/{experimentId}", {experimentId}); + return getById("/experiments/{experimentId}", { experimentId }); } export function deleteExperiment(experimentId) { - return deleteById("/experiments/{experimentId}", {experimentId}); + return deleteById("/experiments/{experimentId}", { experimentId }); } export function getLastSimulatedTick(experimentId) { - return getById("/experiments/{experimentId}/last-simulated-tick", {experimentId}); + return getById("/experiments/{experimentId}/last-simulated-tick", { + experimentId + }); } export function getAllMachineStates(experimentId) { - return getById("/experiments/{experimentId}/machine-states", {experimentId}); + return getById("/experiments/{experimentId}/machine-states", { + experimentId + }); } export function getAllRackStates(experimentId) { - return getById("/experiments/{experimentId}/rack-states", {experimentId}); + return getById("/experiments/{experimentId}/rack-states", { experimentId }); } export function getAllRoomStates(experimentId) { - return getById("/experiments/{experimentId}/room-states", {experimentId}); + return getById("/experiments/{experimentId}/room-states", { experimentId }); } export function getAllTaskStates(experimentId) { - return getById("/experiments/{experimentId}/task-states", {experimentId}); + return getById("/experiments/{experimentId}/task-states", { experimentId }); } diff --git a/src/api/routes/jobs.js b/src/api/routes/jobs.js index e96c12ba..355acc32 100644 --- a/src/api/routes/jobs.js +++ b/src/api/routes/jobs.js @@ -1,5 +1,5 @@ -import {getById} from "./util"; +import { getById } from "./util"; export function getTasksOfJob(jobId) { - return getById("/jobs/{jobId}/tasks", {jobId}); + return getById("/jobs/{jobId}/tasks", { jobId }); } diff --git a/src/api/routes/paths.js b/src/api/routes/paths.js index 073cbe7e..78ef7d6e 100644 --- a/src/api/routes/paths.js +++ b/src/api/routes/paths.js @@ -1,30 +1,30 @@ -import {sendRequest} from "../index"; -import {getById} from "./util"; +import { sendRequest } from "../index"; +import { getById } from "./util"; export function getPath(pathId) { - return getById("/paths/{pathId}", {pathId}); + return getById("/paths/{pathId}", { pathId }); } export function getBranchesOfPath(pathId) { - return getById("/paths/{pathId}/branches", {pathId}); + return getById("/paths/{pathId}/branches", { pathId }); } export function branchFromPath(pathId, section) { - return sendRequest({ - path: "/paths/{pathId}/branches", - method: "POST", - parameters: { - body: { - section - }, - path: { - pathId - }, - query: {} - } - }); + return sendRequest({ + path: "/paths/{pathId}/branches", + method: "POST", + parameters: { + body: { + section + }, + path: { + pathId + }, + query: {} + } + }); } export function getSectionsOfPath(pathId) { - return getById("/paths/{pathId}/sections", {pathId}); + return getById("/paths/{pathId}/sections", { pathId }); } diff --git a/src/api/routes/room-types.js b/src/api/routes/room-types.js index 339896d2..8a3eac58 100644 --- a/src/api/routes/room-types.js +++ b/src/api/routes/room-types.js @@ -1,9 +1,9 @@ -import {getAll, getById} from "./util"; +import { getAll, getById } from "./util"; export function getAvailableRoomTypes() { - return getAll("/room-types"); + return getAll("/room-types"); } export function getAllowedObjectsOfRoomType(name) { - return getById("/room-types/{name}/allowed-objects", {name}); + return getById("/room-types/{name}/allowed-objects", { name }); } diff --git a/src/api/routes/rooms.js b/src/api/routes/rooms.js index 1a7a7453..56395d7f 100644 --- a/src/api/routes/rooms.js +++ b/src/api/routes/rooms.js @@ -1,46 +1,46 @@ -import {sendRequest} from "../index"; -import {deleteById, getById} from "./util"; +import { sendRequest } from "../index"; +import { deleteById, getById } from "./util"; export function getRoom(roomId) { - return getById("/rooms/{roomId}", {roomId}); + return getById("/rooms/{roomId}", { roomId }); } export function updateRoom(room) { - return sendRequest({ - path: "/rooms/{roomId}", - method: "PUT", - parameters: { - body: { - room - }, - path: { - roomId: room.id - }, - query: {} - } - }); + return sendRequest({ + path: "/rooms/{roomId}", + method: "PUT", + parameters: { + body: { + room + }, + path: { + roomId: room.id + }, + query: {} + } + }); } export function deleteRoom(roomId) { - return deleteById("/rooms/{roomId}", {roomId}); + return deleteById("/rooms/{roomId}", { roomId }); } export function getTilesOfRoom(roomId) { - return getById("/rooms/{roomId}/tiles", {roomId}); + return getById("/rooms/{roomId}/tiles", { roomId }); } export function addTileToRoom(tile) { - return sendRequest({ - path: "/rooms/{roomId}/tiles", - method: "POST", - parameters: { - body: { - tile - }, - path: { - roomId: tile.roomId - }, - query: {} - } - }); + return sendRequest({ + path: "/rooms/{roomId}/tiles", + method: "POST", + parameters: { + body: { + tile + }, + path: { + roomId: tile.roomId + }, + query: {} + } + }); } diff --git a/src/api/routes/schedulers.js b/src/api/routes/schedulers.js index 246abf32..ea360967 100644 --- a/src/api/routes/schedulers.js +++ b/src/api/routes/schedulers.js @@ -1,5 +1,5 @@ -import {getAll} from "./util"; +import { getAll } from "./util"; export function getAllSchedulers() { - return getAll("/schedulers"); + return getAll("/schedulers"); } diff --git a/src/api/routes/sections.js b/src/api/routes/sections.js index 8d71d768..5e1a077d 100644 --- a/src/api/routes/sections.js +++ b/src/api/routes/sections.js @@ -1,5 +1,5 @@ -import {getById} from "./util"; +import { getById } from "./util"; export function getSection(sectionId) { - return getById("/sections/{sectionId}", {sectionId}); + return getById("/sections/{sectionId}", { sectionId }); } diff --git a/src/api/routes/simulations.js b/src/api/routes/simulations.js index 09f4b6d7..dcb9ac5f 100644 --- a/src/api/routes/simulations.js +++ b/src/api/routes/simulations.js @@ -1,68 +1,70 @@ -import {sendRequest} from "../index"; -import {deleteById, getById} from "./util"; +import { sendRequest } from "../index"; +import { deleteById, getById } from "./util"; export function getSimulation(simulationId) { - return getById("/simulations/{simulationId}", {simulationId}); + return getById("/simulations/{simulationId}", { simulationId }); } export function addSimulation(simulation) { - return sendRequest({ - path: "/simulations", - method: "POST", - parameters: { - body: { - simulation - }, - path: {}, - query: {} - } - }); + return sendRequest({ + path: "/simulations", + method: "POST", + parameters: { + body: { + simulation + }, + path: {}, + query: {} + } + }); } export function updateSimulation(simulation) { - return sendRequest({ - path: "/simulations/{simulationId}", - method: "PUT", - parameters: { - body: { - simulation - }, - path: { - simulationId: simulation.id - }, - query: {} - } - }); + return sendRequest({ + path: "/simulations/{simulationId}", + method: "PUT", + parameters: { + body: { + simulation + }, + path: { + simulationId: simulation.id + }, + query: {} + } + }); } export function deleteSimulation(simulationId) { - return deleteById("/simulations/{simulationId}", {simulationId}); + return deleteById("/simulations/{simulationId}", { simulationId }); } export function getAuthorizationsBySimulation(simulationId) { - return getById("/simulations/{simulationId}/authorizations", {simulationId}); + return getById("/simulations/{simulationId}/authorizations", { + simulationId + }); } export function getPathsOfSimulation(simulationId) { - return getById("/simulations/{simulationId}/paths", {simulationId}); + return getById("/simulations/{simulationId}/paths", { simulationId }); } export function getExperimentsOfSimulation(simulationId) { - return getById("/simulations/{simulationId}/experiments", {simulationId}); + return getById("/simulations/{simulationId}/experiments", { simulationId }); } export function addExperiment(simulationId, experiment) { - return sendRequest({ - path: "/simulations/{simulationId}/experiments", - method: "POST", - parameters: { - body: { - experiment - }, - path: { - simulationId - }, - query: {} - } - }); + return sendRequest({ + path: "/simulations/{simulationId}/experiments", + method: "POST", + parameters: { + body: { + experiment + }, + path: { + simulationId + }, + query: {} + } + }); } diff --git a/src/api/routes/specifications.js b/src/api/routes/specifications.js index 676d9441..0f60b571 100644 --- a/src/api/routes/specifications.js +++ b/src/api/routes/specifications.js @@ -1,57 +1,57 @@ -import {getAll, getById} from "./util"; +import { getAll, getById } from "./util"; export function getAllCoolingItems() { - return getAll("/specifications/cooling-items"); + return getAll("/specifications/cooling-items"); } export function getCoolingItem(id) { - return getById("/specifications/cooling-items/{id}", {id}); + return getById("/specifications/cooling-items/{id}", { id }); } export function getAllCPUs() { - return getAll("/specifications/cpus"); + return getAll("/specifications/cpus"); } export function getCPU(id) { - return getById("/specifications/cpus/{id}", {id}); + return getById("/specifications/cpus/{id}", { id }); } export function getAllFailureModels() { - return getAll("/specifications/failure-models"); + return getAll("/specifications/failure-models"); } export function getFailureModel(id) { - return getById("/specifications/failure-models/{id}", {id}); + return getById("/specifications/failure-models/{id}", { id }); } export function getAllGPUs() { - return getAll("/specifications/gpus"); + return getAll("/specifications/gpus"); } export function getGPU(id) { - return getById("/specifications/gpus/{id}", {id}); + return getById("/specifications/gpus/{id}", { id }); } export function getAllMemories() { - return getAll("/specifications/memories"); + return getAll("/specifications/memories"); } export function getMemory(id) { - return getById("/specifications/memories/{id}", {id}); + return getById("/specifications/memories/{id}", { id }); } export function getAllPSUs() { - return getAll("/specifications/psus"); + return getAll("/specifications/psus"); } export function getPSU(id) { - return getById("/specifications/psus/{id}", {id}); + return getById("/specifications/psus/{id}", { id }); } export function getAllStorages() { - return getAll("/specifications/storages"); + return getAll("/specifications/storages"); } export function getStorage(id) { - return getById("/specifications/storages/{id}", {id}); + return getById("/specifications/storages/{id}", { id }); } diff --git a/src/api/routes/tiles.js b/src/api/routes/tiles.js index b1c594d5..08481ef4 100644 --- a/src/api/routes/tiles.js +++ b/src/api/routes/tiles.js @@ -1,146 +1,146 @@ -import {sendRequest} from "../index"; -import {deleteById, getById} from "./util"; +import { sendRequest } from "../index"; +import { deleteById, getById } from "./util"; export function getTile(tileId) { - return getById("/tiles/{tileId}", {tileId}); + return getById("/tiles/{tileId}", { tileId }); } export function deleteTile(tileId) { - return deleteById("/tiles/{tileId}", {tileId}); + return deleteById("/tiles/{tileId}", { tileId }); } export function getRackByTile(tileId) { - return getTileObject(tileId, "/rack"); + return getTileObject(tileId, "/rack"); } export function addRackToTile(tileId, rack) { - return addTileObject(tileId, {rack}, "/rack"); + return addTileObject(tileId, { rack }, "/rack"); } export function updateRackOnTile(tileId, rack) { - return updateTileObject(tileId, {rack}, "/rack"); + return updateTileObject(tileId, { rack }, "/rack"); } export function deleteRackFromTile(tileId) { - return deleteTileObject(tileId, "/rack"); + return deleteTileObject(tileId, "/rack"); } export function getMachinesOfRackByTile(tileId) { - return getById("/tiles/{tileId}/rack/machines", {tileId}); + return getById("/tiles/{tileId}/rack/machines", { tileId }); } export function addMachineToRackOnTile(tileId, machine) { - return sendRequest({ - path: "/tiles/{tileId}/rack/machines", - method: "POST", - parameters: { - body: { - machine - }, - path: { - tileId - }, - query: {} - } - }); + return sendRequest({ + path: "/tiles/{tileId}/rack/machines", + method: "POST", + parameters: { + body: { + machine + }, + path: { + tileId + }, + query: {} + } + }); } export function updateMachineInRackOnTile(tileId, position, machine) { - return sendRequest({ - path: "/tiles/{tileId}/rack/machines/{position}", - method: "PUT", - parameters: { - body: { - machine - }, - path: { - tileId, - position - }, - query: {} - } - }); + return sendRequest({ + path: "/tiles/{tileId}/rack/machines/{position}", + method: "PUT", + parameters: { + body: { + machine + }, + path: { + tileId, + position + }, + query: {} + } + }); } export function deleteMachineInRackOnTile(tileId, position) { - return sendRequest({ - path: "/tiles/{tileId}/rack/machines/{position}", - method: "DELETE", - parameters: { - body: {}, - path: { - tileId, - position - }, - query: {} - } - }); + return sendRequest({ + path: "/tiles/{tileId}/rack/machines/{position}", + method: "DELETE", + parameters: { + body: {}, + path: { + tileId, + position + }, + query: {} + } + }); } export function getCoolingItemByTile(tileId) { - return getTileObject(tileId, "/cooling-item"); + return getTileObject(tileId, "/cooling-item"); } export function addCoolingItemToTile(tileId, coolingItemId) { - return addTileObject(tileId, {coolingItemId}, "/cooling-item"); + return addTileObject(tileId, { coolingItemId }, "/cooling-item"); } export function updateCoolingItemOnTile(tileId, coolingItemId) { - return updateTileObject(tileId, {coolingItemId}, "/cooling-item"); + return updateTileObject(tileId, { coolingItemId }, "/cooling-item"); } export function deleteCoolingItemFromTile(tileId) { - return deleteTileObject(tileId, "/cooling-item"); + return deleteTileObject(tileId, "/cooling-item"); } export function getPSUByTile(tileId) { - return getTileObject(tileId, "/psu"); + return getTileObject(tileId, "/psu"); } export function addPSUToTile(tileId, psuId) { - return addTileObject(tileId, {psuId}, "/psu"); + return addTileObject(tileId, { psuId }, "/psu"); } export function updatePSUOnTile(tileId, psuId) { - return updateTileObject(tileId, {psuId}, "/psu"); + return updateTileObject(tileId, { psuId }, "/psu"); } export function deletePSUFromTile(tileId) { - return deleteTileObject(tileId, "/psu"); + return deleteTileObject(tileId, "/psu"); } function getTileObject(tileId, endpoint) { - return getById("/tiles/{tileId}" + endpoint, {tileId}); + return getById("/tiles/{tileId}" + endpoint, { tileId }); } function addTileObject(tileId, objectBody, endpoint) { - return sendRequest({ - path: "/tiles/{tileId}" + endpoint, - method: "POST", - parameters: { - body: objectBody, - path: { - tileId - }, - query: {} - } - }); + return sendRequest({ + path: "/tiles/{tileId}" + endpoint, + method: "POST", + parameters: { + body: objectBody, + path: { + tileId + }, + query: {} + } + }); } function updateTileObject(tileId, objectBody, endpoint) { - return sendRequest({ - path: "/tiles/{tileId}" + endpoint, - method: "PUT", - parameters: { - body: objectBody, - path: { - tileId - }, - query: {} - } - }); + return sendRequest({ + path: "/tiles/{tileId}" + endpoint, + method: "PUT", + parameters: { + body: objectBody, + path: { + tileId + }, + query: {} + } + }); } function deleteTileObject(tileId, endpoint) { - return deleteById("/tiles/{tileId}" + endpoint, {tileId}); + return deleteById("/tiles/{tileId}" + endpoint, { tileId }); } diff --git a/src/api/routes/token-signin.js b/src/api/routes/token-signin.js index dbf70869..26875606 100644 --- a/src/api/routes/token-signin.js +++ b/src/api/routes/token-signin.js @@ -1,9 +1,7 @@ export function performTokenSignIn(token) { - return new Promise(resolve => { - window["jQuery"].post( - "/tokensignin", - {idtoken: token}, - data => resolve(data) - ) - }); + return new Promise(resolve => { + window["jQuery"].post("/tokensignin", { idtoken: token }, data => + resolve(data) + ); + }); } diff --git a/src/api/routes/traces.js b/src/api/routes/traces.js index 6a34ca7c..a9ee4fae 100644 --- a/src/api/routes/traces.js +++ b/src/api/routes/traces.js @@ -1,9 +1,9 @@ -import {getAll, getById} from "./util"; +import { getAll, getById } from "./util"; export function getAllTraces() { - return getAll("/traces"); + return getAll("/traces"); } export function getJobsOfTrace(traceId) { - return getById("/traces/{traceId}/jobs", {traceId}); + return getById("/traces/{traceId}/jobs", { traceId }); } diff --git a/src/api/routes/users.js b/src/api/routes/users.js index 7b931d66..f8d8039c 100644 --- a/src/api/routes/users.js +++ b/src/api/routes/users.js @@ -1,71 +1,71 @@ -import {sendRequest} from "../index"; -import {deleteById, getById} from "./util"; +import { sendRequest } from "../index"; +import { deleteById, getById } from "./util"; export function getUserByEmail(email) { - return sendRequest({ - path: "/users", - method: "GET", - parameters: { - body: {}, - path: {}, - query: { - email - } - } - }); + return sendRequest({ + path: "/users", + method: "GET", + parameters: { + body: {}, + path: {}, + query: { + email + } + } + }); } export function addUser(user) { - return sendRequest({ - path: "/users", - method: "POST", - parameters: { - body: { - user: user - }, - path: {}, - query: {} - } - }); + return sendRequest({ + path: "/users", + method: "POST", + parameters: { + body: { + user: user + }, + path: {}, + query: {} + } + }); } export function getUser(userId) { - return sendRequest({ - path: "/users/{userId}", - method: "GET", - parameters: { - body: {}, - path: { - userId - }, - query: {} - } - }); + return sendRequest({ + path: "/users/{userId}", + method: "GET", + parameters: { + body: {}, + path: { + userId + }, + query: {} + } + }); } export function updateUser(userId, user) { - return sendRequest({ - path: "/users/{userId}", - method: "PUT", - parameters: { - body: { - user: { - givenName: user.givenName, - familyName: user.familyName - } - }, - path: { - userId - }, - query: {} + return sendRequest({ + path: "/users/{userId}", + method: "PUT", + parameters: { + body: { + user: { + givenName: user.givenName, + familyName: user.familyName } - }); + }, + path: { + userId + }, + query: {} + } + }); } export function deleteUser(userId) { - return deleteById("/users/{userId}", {userId}); + return deleteById("/users/{userId}", { userId }); } export function getAuthorizationsByUser(userId) { - return getById("/users/{userId}/authorizations", {userId}); + return getById("/users/{userId}/authorizations", { userId }); } diff --git a/src/api/routes/util.js b/src/api/routes/util.js index ff21d4f4..35a40333 100644 --- a/src/api/routes/util.js +++ b/src/api/routes/util.js @@ -1,37 +1,37 @@ -import {sendRequest} from "../index"; +import { sendRequest } from "../index"; export function getAll(path) { - return sendRequest({ - path, - method: "GET", - parameters: { - body: {}, - path: {}, - query: {} - } - }); + return sendRequest({ + path, + method: "GET", + parameters: { + body: {}, + path: {}, + query: {} + } + }); } export function getById(path, pathObject) { - return sendRequest({ - path, - method: "GET", - parameters: { - body: {}, - path: pathObject, - query: {} - } - }); + return sendRequest({ + path, + method: "GET", + parameters: { + body: {}, + path: pathObject, + query: {} + } + }); } export function deleteById(path, pathObject) { - return sendRequest({ - path, - method: "DELETE", - parameters: { - body: {}, - path: pathObject, - query: {} - } - }); + return sendRequest({ + path, + method: "DELETE", + parameters: { + body: {}, + path: pathObject, + query: {} + } + }); } diff --git a/src/api/socket.js b/src/api/socket.js index 283e02e7..cba60288 100644 --- a/src/api/socket.js +++ b/src/api/socket.js @@ -1,50 +1,52 @@ import io from "socket.io-client"; -import {getAuthToken} from "../auth/index"; +import { getAuthToken } from "../auth/index"; let socket; let requestIdCounter = 0; const callbacks = {}; export function setupSocketConnection(onConnect) { - let port = window.location.port; - if (process.env.NODE_ENV !== 'production') { - port = 8081 - } - socket = io.connect(window.location.protocol + "//" + window.location.hostname + ":" + port); - socket.on("connect", onConnect); - socket.on("response", onSocketResponse); + let port = window.location.port; + if (process.env.NODE_ENV !== "production") { + port = 8081; + } + socket = io.connect( + window.location.protocol + "//" + window.location.hostname + ":" + port + ); + socket.on("connect", onConnect); + socket.on("response", onSocketResponse); } export function sendSocketRequest(request, callback) { - if (!socket.connected) { - console.error("Attempted to send request over unconnected socket"); - return; - } + if (!socket.connected) { + console.error("Attempted to send request over unconnected socket"); + return; + } - const newId = requestIdCounter++; - callbacks[newId] = callback; + const newId = requestIdCounter++; + callbacks[newId] = callback; - request.id = newId; - request.token = getAuthToken(); + request.id = newId; + request.token = getAuthToken(); - if (!request.isRootRoute) { - request.path = "/v1" + request.path; - } + if (!request.isRootRoute) { + request.path = "/v1" + request.path; + } - socket.emit("request", request); + socket.emit("request", request); - if (process.env.NODE_ENV !== 'production') { - console.log("Sent socket request:", request); - } + if (process.env.NODE_ENV !== "production") { + console.log("Sent socket request:", request); + } } function onSocketResponse(json) { - const response = JSON.parse(json); + const response = JSON.parse(json); - if (process.env.NODE_ENV !== 'production') { - console.log("Received socket response:", response); - } + if (process.env.NODE_ENV !== "production") { + console.log("Received socket response:", response); + } - callbacks[response.id](response); - delete callbacks[response.id]; + callbacks[response.id](response); + delete callbacks[response.id]; } diff --git a/src/auth/index.js b/src/auth/index.js index 418d816c..83c27b27 100644 --- a/src/auth/index.js +++ b/src/auth/index.js @@ -1,57 +1,57 @@ -import {LOG_IN_SUCCEEDED, LOG_OUT} from "../actions/auth"; -import {DELETE_CURRENT_USER_SUCCEEDED} from "../actions/users"; +import { LOG_IN_SUCCEEDED, LOG_OUT } from "../actions/auth"; +import { DELETE_CURRENT_USER_SUCCEEDED } from "../actions/users"; const getAuthObject = () => { - const authItem = localStorage.getItem("auth"); - if (!authItem || authItem === "{}") { - return undefined; - } - return JSON.parse(authItem); + const authItem = localStorage.getItem("auth"); + if (!authItem || authItem === "{}") { + return undefined; + } + return JSON.parse(authItem); }; export const userIsLoggedIn = () => { - const authObj = getAuthObject(); + const authObj = getAuthObject(); - if (!authObj || !authObj.googleId) { - return false; - } + if (!authObj || !authObj.googleId) { + return false; + } - const currentTime = (new Date()).getTime(); - return parseInt(authObj.expiresAt, 10) - currentTime > 0; + const currentTime = new Date().getTime(); + return parseInt(authObj.expiresAt, 10) - currentTime > 0; }; export const getAuthToken = () => { - const authObj = getAuthObject(); - if (!authObj) { - return undefined; - } + const authObj = getAuthObject(); + if (!authObj) { + return undefined; + } - return authObj.authToken; + return authObj.authToken; }; -export const saveAuthLocalStorage = (payload) => { - localStorage.setItem("auth", JSON.stringify(payload)); +export const saveAuthLocalStorage = payload => { + localStorage.setItem("auth", JSON.stringify(payload)); }; export const clearAuthLocalStorage = () => { - localStorage.setItem("auth", ""); + localStorage.setItem("auth", ""); }; export const authRedirectMiddleware = store => next => action => { - switch (action.type) { - case LOG_IN_SUCCEEDED: - saveAuthLocalStorage(action.payload); - window.location.href = "/simulations"; - break; - case LOG_OUT: - case DELETE_CURRENT_USER_SUCCEEDED: - clearAuthLocalStorage(); - window.location.href = "/"; - break; - default: - next(action); - return; - } - - next(action); + switch (action.type) { + case LOG_IN_SUCCEEDED: + saveAuthLocalStorage(action.payload); + window.location.href = "/simulations"; + break; + case LOG_OUT: + case DELETE_CURRENT_USER_SUCCEEDED: + clearAuthLocalStorage(); + window.location.href = "/"; + break; + default: + next(action); + return; + } + + next(action); }; diff --git a/src/components/app/map/LoadingScreen.js b/src/components/app/map/LoadingScreen.js index 3d5753e2..9f379e0b 100644 --- a/src/components/app/map/LoadingScreen.js +++ b/src/components/app/map/LoadingScreen.js @@ -1,11 +1,11 @@ -import React from 'react'; +import React from "react"; import FontAwesome from "react-fontawesome"; const LoadingScreen = () => ( - <div className="display-4"> - <FontAwesome name="refresh" className="mr-4" spin/> - Loading your datacenter... - </div> + <div className="display-4"> + <FontAwesome name="refresh" className="mr-4" spin /> + Loading your datacenter... + </div> ); export default LoadingScreen; diff --git a/src/components/app/map/MapConstants.js b/src/components/app/map/MapConstants.js index a0166d15..32438b5e 100644 --- a/src/components/app/map/MapConstants.js +++ b/src/components/app/map/MapConstants.js @@ -5,7 +5,8 @@ export const MAP_SIZE_IN_PIXELS = MAP_SIZE * TILE_SIZE_IN_PIXELS; export const OBJECT_MARGIN_IN_PIXELS = TILE_SIZE_IN_PIXELS / 5; export const TILE_PLUS_MARGIN_IN_PIXELS = TILE_SIZE_IN_PIXELS / 3; -export const OBJECT_SIZE_IN_PIXELS = TILE_SIZE_IN_PIXELS - OBJECT_MARGIN_IN_PIXELS * 2; +export const OBJECT_SIZE_IN_PIXELS = + TILE_SIZE_IN_PIXELS - OBJECT_MARGIN_IN_PIXELS * 2; export const GRID_LINE_WIDTH_IN_PIXELS = 2; export const WALL_WIDTH_IN_PIXELS = TILE_SIZE_IN_PIXELS / 8; diff --git a/src/components/app/map/MapStageComponent.js b/src/components/app/map/MapStageComponent.js index c5b31e0f..ce6a60f6 100644 --- a/src/components/app/map/MapStageComponent.js +++ b/src/components/app/map/MapStageComponent.js @@ -1,108 +1,122 @@ import React from "react"; -import {Stage} from "react-konva"; -import {Shortcuts} from "react-shortcuts"; +import { Stage } from "react-konva"; +import { Shortcuts } from "react-shortcuts"; import MapLayer from "../../../containers/app/map/layers/MapLayer"; import ObjectHoverLayer from "../../../containers/app/map/layers/ObjectHoverLayer"; import RoomHoverLayer from "../../../containers/app/map/layers/RoomHoverLayer"; import jQuery from "../../../util/jquery"; -import {NAVBAR_HEIGHT} from "../../navigation/Navbar"; -import {MAP_MOVE_PIXELS_PER_EVENT} from "./MapConstants"; +import { NAVBAR_HEIGHT } from "../../navigation/Navbar"; +import { MAP_MOVE_PIXELS_PER_EVENT } from "./MapConstants"; class MapStageComponent extends React.Component { - state = { - mouseX: 0, - mouseY: 0 - }; + state = { + mouseX: 0, + mouseY: 0 + }; - constructor() { - super(); + constructor() { + super(); - this.updateDimensions = this.updateDimensions.bind(this); - this.updateScale = this.updateScale.bind(this); - } + this.updateDimensions = this.updateDimensions.bind(this); + this.updateScale = this.updateScale.bind(this); + } - componentWillMount() { - this.updateDimensions(); - } + componentWillMount() { + this.updateDimensions(); + } - componentDidMount() { - window.addEventListener("resize", this.updateDimensions); - window.addEventListener("wheel", this.updateScale); + componentDidMount() { + window.addEventListener("resize", this.updateDimensions); + window.addEventListener("wheel", this.updateScale); - window["exportCanvasToImage"] = () => { - const download = document.createElement("a"); - download.href = this.stage.getStage().toDataURL(); - download.download = "opendc-canvas-export-" + Date.now() + ".png"; - download.click(); - } - } + window["exportCanvasToImage"] = () => { + const download = document.createElement("a"); + download.href = this.stage.getStage().toDataURL(); + download.download = "opendc-canvas-export-" + Date.now() + ".png"; + download.click(); + }; + } - componentWillUnmount() { - window.removeEventListener("resize", this.updateDimensions); - window.removeEventListener("wheel", this.updateScale); - } + componentWillUnmount() { + window.removeEventListener("resize", this.updateDimensions); + window.removeEventListener("wheel", this.updateScale); + } - updateDimensions() { - this.props.setMapDimensions(jQuery(window).width(), jQuery(window).height() - NAVBAR_HEIGHT); - } + updateDimensions() { + this.props.setMapDimensions( + jQuery(window).width(), + jQuery(window).height() - NAVBAR_HEIGHT + ); + } - updateScale(e) { - e.preventDefault(); - this.props.zoomInOnPosition(e.deltaY < 0, this.state.mouseX, this.state.mouseY); - } + updateScale(e) { + e.preventDefault(); + this.props.zoomInOnPosition( + e.deltaY < 0, + this.state.mouseX, + this.state.mouseY + ); + } - updateMousePosition() { - const mousePos = this.stage.getStage().getPointerPosition(); - this.setState({mouseX: mousePos.x, mouseY: mousePos.y}); - } + updateMousePosition() { + const mousePos = this.stage.getStage().getPointerPosition(); + this.setState({ mouseX: mousePos.x, mouseY: mousePos.y }); + } - handleShortcuts(action) { - switch (action) { - case "MOVE_LEFT": - this.moveWithDelta(MAP_MOVE_PIXELS_PER_EVENT, 0); - break; - case "MOVE_RIGHT": - this.moveWithDelta(-MAP_MOVE_PIXELS_PER_EVENT, 0); - break; - case "MOVE_UP": - this.moveWithDelta(0, MAP_MOVE_PIXELS_PER_EVENT); - break; - case "MOVE_DOWN": - this.moveWithDelta(0, -MAP_MOVE_PIXELS_PER_EVENT); - break; - default: - break; - } + handleShortcuts(action) { + switch (action) { + case "MOVE_LEFT": + this.moveWithDelta(MAP_MOVE_PIXELS_PER_EVENT, 0); + break; + case "MOVE_RIGHT": + this.moveWithDelta(-MAP_MOVE_PIXELS_PER_EVENT, 0); + break; + case "MOVE_UP": + this.moveWithDelta(0, MAP_MOVE_PIXELS_PER_EVENT); + break; + case "MOVE_DOWN": + this.moveWithDelta(0, -MAP_MOVE_PIXELS_PER_EVENT); + break; + default: + break; } + } - moveWithDelta(deltaX, deltaY) { - this.props.setMapPositionWithBoundsCheck(this.props.mapPosition.x + deltaX, this.props.mapPosition.y + deltaY); - } + moveWithDelta(deltaX, deltaY) { + this.props.setMapPositionWithBoundsCheck( + this.props.mapPosition.x + deltaX, + this.props.mapPosition.y + deltaY + ); + } - render() { - return ( - <Shortcuts name="MAP" handler={this.handleShortcuts.bind(this)} targetNodeSelector="body"> - <Stage - ref={(stage) => { - this.stage = stage; - }} - width={this.props.mapDimensions.width} - height={this.props.mapDimensions.height} - onMouseMove={this.updateMousePosition.bind(this)} - > - <MapLayer/> - <RoomHoverLayer - mouseX={this.state.mouseX} - mouseY={this.state.mouseY} - /> - <ObjectHoverLayer - mouseX={this.state.mouseX} - mouseY={this.state.mouseY} - /> - </Stage> - </Shortcuts> - ) - } + render() { + return ( + <Shortcuts + name="MAP" + handler={this.handleShortcuts.bind(this)} + targetNodeSelector="body" + > + <Stage + ref={stage => { + this.stage = stage; + }} + width={this.props.mapDimensions.width} + height={this.props.mapDimensions.height} + onMouseMove={this.updateMousePosition.bind(this)} + > + <MapLayer /> + <RoomHoverLayer + mouseX={this.state.mouseX} + mouseY={this.state.mouseY} + /> + <ObjectHoverLayer + mouseX={this.state.mouseX} + mouseY={this.state.mouseY} + /> + </Stage> + </Shortcuts> + ); + } } export default MapStageComponent; diff --git a/src/components/app/map/controls/ExportCanvasComponent.js b/src/components/app/map/controls/ExportCanvasComponent.js index 2f044ffe..ee934f21 100644 --- a/src/components/app/map/controls/ExportCanvasComponent.js +++ b/src/components/app/map/controls/ExportCanvasComponent.js @@ -1,13 +1,13 @@ import React from "react"; const ExportCanvasComponent = () => ( - <button - className="btn btn-success btn-circle btn-sm" - title="Export Canvas to PNG Image" - onClick={() => window["exportCanvasToImage"]()} - > - <span className="fa fa-camera"/> - </button> + <button + className="btn btn-success btn-circle btn-sm" + title="Export Canvas to PNG Image" + onClick={() => window["exportCanvasToImage"]()} + > + <span className="fa fa-camera" /> + </button> ); export default ExportCanvasComponent; diff --git a/src/components/app/map/controls/ScaleIndicatorComponent.js b/src/components/app/map/controls/ScaleIndicatorComponent.js index fd9483b5..b7b5cc36 100644 --- a/src/components/app/map/controls/ScaleIndicatorComponent.js +++ b/src/components/app/map/controls/ScaleIndicatorComponent.js @@ -1,14 +1,14 @@ import React from "react"; -import {TILE_SIZE_IN_METERS, TILE_SIZE_IN_PIXELS} from "../MapConstants"; +import { TILE_SIZE_IN_METERS, TILE_SIZE_IN_PIXELS } from "../MapConstants"; import "./ScaleIndicatorComponent.css"; -const ScaleIndicatorComponent = ({scale}) => ( - <div - className="scale-indicator" - style={{width: TILE_SIZE_IN_PIXELS * scale}} - > - {TILE_SIZE_IN_METERS}m - </div> +const ScaleIndicatorComponent = ({ scale }) => ( + <div + className="scale-indicator" + style={{ width: TILE_SIZE_IN_PIXELS * scale }} + > + {TILE_SIZE_IN_METERS}m + </div> ); export default ScaleIndicatorComponent; diff --git a/src/components/app/map/controls/ToolPanelComponent.js b/src/components/app/map/controls/ToolPanelComponent.js index a065358a..605e9887 100644 --- a/src/components/app/map/controls/ToolPanelComponent.js +++ b/src/components/app/map/controls/ToolPanelComponent.js @@ -4,10 +4,10 @@ import ExportCanvasComponent from "./ExportCanvasComponent"; import "./ToolPanelComponent.css"; const ToolPanelComponent = () => ( - <div className="tool-panel"> - <ZoomControlContainer/> - <ExportCanvasComponent/> - </div> + <div className="tool-panel"> + <ZoomControlContainer /> + <ExportCanvasComponent /> + </div> ); export default ToolPanelComponent; diff --git a/src/components/app/map/controls/ZoomControlComponent.js b/src/components/app/map/controls/ZoomControlComponent.js index 8406e8c1..e1b7491e 100644 --- a/src/components/app/map/controls/ZoomControlComponent.js +++ b/src/components/app/map/controls/ZoomControlComponent.js @@ -1,24 +1,24 @@ import React from "react"; -const ZoomControlComponent = ({zoomInOnCenter}) => { - return ( - <span> - <button - className="btn btn-default btn-circle btn-sm mr-1" - title="Zoom in" - onClick={() => zoomInOnCenter(true)} - > - <span className="fa fa-plus"/> - </button> - <button - className="btn btn-default btn-circle btn-sm mr-1" - title="Zoom out" - onClick={() => zoomInOnCenter(false)} - > - <span className="fa fa-minus"/> - </button> - </span> - ); +const ZoomControlComponent = ({ zoomInOnCenter }) => { + return ( + <span> + <button + className="btn btn-default btn-circle btn-sm mr-1" + title="Zoom in" + onClick={() => zoomInOnCenter(true)} + > + <span className="fa fa-plus" /> + </button> + <button + className="btn btn-default btn-circle btn-sm mr-1" + title="Zoom out" + onClick={() => zoomInOnCenter(false)} + > + <span className="fa fa-minus" /> + </button> + </span> + ); }; export default ZoomControlComponent; diff --git a/src/components/app/map/elements/Backdrop.js b/src/components/app/map/elements/Backdrop.js index 9c01df63..57414463 100644 --- a/src/components/app/map/elements/Backdrop.js +++ b/src/components/app/map/elements/Backdrop.js @@ -1,16 +1,16 @@ import React from "react"; -import {Rect} from "react-konva"; -import {BACKDROP_COLOR} from "../../../../util/colors"; -import {MAP_SIZE_IN_PIXELS} from "../MapConstants"; +import { Rect } from "react-konva"; +import { BACKDROP_COLOR } from "../../../../util/colors"; +import { MAP_SIZE_IN_PIXELS } from "../MapConstants"; const Backdrop = () => ( - <Rect - x={0} - y={0} - width={MAP_SIZE_IN_PIXELS} - height={MAP_SIZE_IN_PIXELS} - fill={BACKDROP_COLOR} - /> + <Rect + x={0} + y={0} + width={MAP_SIZE_IN_PIXELS} + height={MAP_SIZE_IN_PIXELS} + fill={BACKDROP_COLOR} + /> ); export default Backdrop; diff --git a/src/components/app/map/elements/GrayLayer.js b/src/components/app/map/elements/GrayLayer.js index c5994d06..28fadd8a 100644 --- a/src/components/app/map/elements/GrayLayer.js +++ b/src/components/app/map/elements/GrayLayer.js @@ -1,17 +1,17 @@ import React from "react"; -import {Rect} from "react-konva"; -import {GRAYED_OUT_AREA_COLOR} from "../../../../util/colors"; -import {MAP_SIZE_IN_PIXELS} from "../MapConstants"; +import { Rect } from "react-konva"; +import { GRAYED_OUT_AREA_COLOR } from "../../../../util/colors"; +import { MAP_SIZE_IN_PIXELS } from "../MapConstants"; -const GrayLayer = ({onClick}) => ( - <Rect - x={0} - y={0} - width={MAP_SIZE_IN_PIXELS} - height={MAP_SIZE_IN_PIXELS} - fill={GRAYED_OUT_AREA_COLOR} - onClick={onClick} - /> +const GrayLayer = ({ onClick }) => ( + <Rect + x={0} + y={0} + width={MAP_SIZE_IN_PIXELS} + height={MAP_SIZE_IN_PIXELS} + fill={GRAYED_OUT_AREA_COLOR} + onClick={onClick} + /> ); export default GrayLayer; diff --git a/src/components/app/map/elements/HoverTile.js b/src/components/app/map/elements/HoverTile.js index fc12cbdd..42e6547c 100644 --- a/src/components/app/map/elements/HoverTile.js +++ b/src/components/app/map/elements/HoverTile.js @@ -1,27 +1,30 @@ import PropTypes from "prop-types"; import React from "react"; -import {Rect} from "react-konva"; -import {ROOM_HOVER_INVALID_COLOR, ROOM_HOVER_VALID_COLOR} from "../../../../util/colors"; -import {TILE_SIZE_IN_PIXELS} from "../MapConstants"; +import { Rect } from "react-konva"; +import { + ROOM_HOVER_INVALID_COLOR, + ROOM_HOVER_VALID_COLOR +} from "../../../../util/colors"; +import { TILE_SIZE_IN_PIXELS } from "../MapConstants"; -const HoverTile = ({pixelX, pixelY, isValid, scale, onClick}) => ( - <Rect - x={pixelX} - y={pixelY} - scaleX={scale} - scaleY={scale} - width={TILE_SIZE_IN_PIXELS} - height={TILE_SIZE_IN_PIXELS} - fill={isValid ? ROOM_HOVER_VALID_COLOR : ROOM_HOVER_INVALID_COLOR} - onClick={onClick} - /> +const HoverTile = ({ pixelX, pixelY, isValid, scale, onClick }) => ( + <Rect + x={pixelX} + y={pixelY} + scaleX={scale} + scaleY={scale} + width={TILE_SIZE_IN_PIXELS} + height={TILE_SIZE_IN_PIXELS} + fill={isValid ? ROOM_HOVER_VALID_COLOR : ROOM_HOVER_INVALID_COLOR} + onClick={onClick} + /> ); HoverTile.propTypes = { - pixelX: PropTypes.number.isRequired, - pixelY: PropTypes.number.isRequired, - isValid: PropTypes.bool.isRequired, - onClick: PropTypes.func.isRequired, + pixelX: PropTypes.number.isRequired, + pixelY: PropTypes.number.isRequired, + isValid: PropTypes.bool.isRequired, + onClick: PropTypes.func.isRequired }; export default HoverTile; diff --git a/src/components/app/map/elements/ImageComponent.js b/src/components/app/map/elements/ImageComponent.js index 486296ea..cf41ddfe 100644 --- a/src/components/app/map/elements/ImageComponent.js +++ b/src/components/app/map/elements/ImageComponent.js @@ -1,48 +1,48 @@ import PropTypes from "prop-types"; import React from "react"; -import {Image} from "react-konva"; +import { Image } from "react-konva"; class ImageComponent extends React.Component { - static imageCaches = {}; - static propTypes = { - src: PropTypes.string.isRequired, - x: PropTypes.number.isRequired, - y: PropTypes.number.isRequired, - width: PropTypes.number.isRequired, - height: PropTypes.number.isRequired, - opacity: PropTypes.number.isRequired, - }; - - state = { - image: null - }; + static imageCaches = {}; + static propTypes = { + src: PropTypes.string.isRequired, + x: PropTypes.number.isRequired, + y: PropTypes.number.isRequired, + width: PropTypes.number.isRequired, + height: PropTypes.number.isRequired, + opacity: PropTypes.number.isRequired + }; - componentDidMount() { - if (ImageComponent.imageCaches[this.props.src]) { - this.setState({image: ImageComponent.imageCaches[this.props.src]}); - return; - } + state = { + image: null + }; - const image = new window.Image(); - image.src = this.props.src; - image.onload = () => { - this.setState({image}); - ImageComponent.imageCaches[this.props.src] = image; - } + componentDidMount() { + if (ImageComponent.imageCaches[this.props.src]) { + this.setState({ image: ImageComponent.imageCaches[this.props.src] }); + return; } - render() { - return ( - <Image - image={this.state.image} - x={this.props.x} - y={this.props.y} - width={this.props.width} - height={this.props.height} - opacity={this.props.opacity} - /> - ) - } + const image = new window.Image(); + image.src = this.props.src; + image.onload = () => { + this.setState({ image }); + ImageComponent.imageCaches[this.props.src] = image; + }; + } + + render() { + return ( + <Image + image={this.state.image} + x={this.props.x} + y={this.props.y} + width={this.props.width} + height={this.props.height} + opacity={this.props.opacity} + /> + ); + } } export default ImageComponent; diff --git a/src/components/app/map/elements/RackFillBar.js b/src/components/app/map/elements/RackFillBar.js index 3a8a1137..43701d97 100644 --- a/src/components/app/map/elements/RackFillBar.js +++ b/src/components/app/map/elements/RackFillBar.js @@ -1,67 +1,89 @@ import PropTypes from "prop-types"; import React from "react"; -import {Group, Rect} from "react-konva"; +import { Group, Rect } from "react-konva"; import { - RACK_ENERGY_BAR_BACKGROUND_COLOR, - RACK_ENERGY_BAR_FILL_COLOR, - RACK_SPACE_BAR_BACKGROUND_COLOR, - RACK_SPACE_BAR_FILL_COLOR + RACK_ENERGY_BAR_BACKGROUND_COLOR, + RACK_ENERGY_BAR_FILL_COLOR, + RACK_SPACE_BAR_BACKGROUND_COLOR, + RACK_SPACE_BAR_FILL_COLOR } from "../../../../util/colors"; import { - OBJECT_BORDER_WIDTH_IN_PIXELS, - OBJECT_MARGIN_IN_PIXELS, - RACK_FILL_ICON_OPACITY, - RACK_FILL_ICON_WIDTH, - TILE_SIZE_IN_PIXELS + OBJECT_BORDER_WIDTH_IN_PIXELS, + OBJECT_MARGIN_IN_PIXELS, + RACK_FILL_ICON_OPACITY, + RACK_FILL_ICON_WIDTH, + TILE_SIZE_IN_PIXELS } from "../MapConstants"; import ImageComponent from "./ImageComponent"; -const RackFillBar = ({positionX, positionY, type, fillFraction}) => { - const halfOfObjectBorderWidth = OBJECT_BORDER_WIDTH_IN_PIXELS / 2; - const x = positionX * TILE_SIZE_IN_PIXELS + OBJECT_MARGIN_IN_PIXELS - + (type === "space" ? halfOfObjectBorderWidth : - 0.5 * (TILE_SIZE_IN_PIXELS - 2 * OBJECT_MARGIN_IN_PIXELS)); - const startY = positionY * TILE_SIZE_IN_PIXELS + OBJECT_MARGIN_IN_PIXELS + halfOfObjectBorderWidth; - const width = 0.5 * (TILE_SIZE_IN_PIXELS - OBJECT_MARGIN_IN_PIXELS * 2) - halfOfObjectBorderWidth; - const fullHeight = TILE_SIZE_IN_PIXELS - OBJECT_MARGIN_IN_PIXELS * 2 - OBJECT_BORDER_WIDTH_IN_PIXELS; +const RackFillBar = ({ positionX, positionY, type, fillFraction }) => { + const halfOfObjectBorderWidth = OBJECT_BORDER_WIDTH_IN_PIXELS / 2; + const x = + positionX * TILE_SIZE_IN_PIXELS + + OBJECT_MARGIN_IN_PIXELS + + (type === "space" + ? halfOfObjectBorderWidth + : 0.5 * (TILE_SIZE_IN_PIXELS - 2 * OBJECT_MARGIN_IN_PIXELS)); + const startY = + positionY * TILE_SIZE_IN_PIXELS + + OBJECT_MARGIN_IN_PIXELS + + halfOfObjectBorderWidth; + const width = + 0.5 * (TILE_SIZE_IN_PIXELS - OBJECT_MARGIN_IN_PIXELS * 2) - + halfOfObjectBorderWidth; + const fullHeight = + TILE_SIZE_IN_PIXELS - + OBJECT_MARGIN_IN_PIXELS * 2 - + OBJECT_BORDER_WIDTH_IN_PIXELS; - const fractionHeight = fillFraction * fullHeight; - const fractionY = (positionY + 1) * TILE_SIZE_IN_PIXELS - OBJECT_MARGIN_IN_PIXELS - halfOfObjectBorderWidth - - fractionHeight; + const fractionHeight = fillFraction * fullHeight; + const fractionY = + (positionY + 1) * TILE_SIZE_IN_PIXELS - + OBJECT_MARGIN_IN_PIXELS - + halfOfObjectBorderWidth - + fractionHeight; - return ( - <Group> - <Rect - x={x} - y={startY} - width={width} - height={fullHeight} - fill={type === "space" ? RACK_SPACE_BAR_BACKGROUND_COLOR : RACK_ENERGY_BAR_BACKGROUND_COLOR} - /> - <Rect - x={x} - y={fractionY} - width={width} - height={fractionHeight} - fill={type === "space" ? RACK_SPACE_BAR_FILL_COLOR : RACK_ENERGY_BAR_FILL_COLOR} - /> - <ImageComponent - src={"/img/topology/rack-" + type + "-icon.png"} - x={x + width * 0.5 - RACK_FILL_ICON_WIDTH * 0.5} - y={startY + fullHeight * 0.5 - RACK_FILL_ICON_WIDTH * 0.5} - width={RACK_FILL_ICON_WIDTH} - height={RACK_FILL_ICON_WIDTH} - opacity={RACK_FILL_ICON_OPACITY} - /> - </Group> - ); + return ( + <Group> + <Rect + x={x} + y={startY} + width={width} + height={fullHeight} + fill={ + type === "space" + ? RACK_SPACE_BAR_BACKGROUND_COLOR + : RACK_ENERGY_BAR_BACKGROUND_COLOR + } + /> + <Rect + x={x} + y={fractionY} + width={width} + height={fractionHeight} + fill={ + type === "space" + ? RACK_SPACE_BAR_FILL_COLOR + : RACK_ENERGY_BAR_FILL_COLOR + } + /> + <ImageComponent + src={"/img/topology/rack-" + type + "-icon.png"} + x={x + width * 0.5 - RACK_FILL_ICON_WIDTH * 0.5} + y={startY + fullHeight * 0.5 - RACK_FILL_ICON_WIDTH * 0.5} + width={RACK_FILL_ICON_WIDTH} + height={RACK_FILL_ICON_WIDTH} + opacity={RACK_FILL_ICON_OPACITY} + /> + </Group> + ); }; RackFillBar.propTypes = { - positionX: PropTypes.number.isRequired, - positionY: PropTypes.number.isRequired, - type: PropTypes.string.isRequired, - fillFraction: PropTypes.number.isRequired, + positionX: PropTypes.number.isRequired, + positionY: PropTypes.number.isRequired, + type: PropTypes.string.isRequired, + fillFraction: PropTypes.number.isRequired }; export default RackFillBar; diff --git a/src/components/app/map/elements/RoomTile.js b/src/components/app/map/elements/RoomTile.js index 11948a7a..71c3bf15 100644 --- a/src/components/app/map/elements/RoomTile.js +++ b/src/components/app/map/elements/RoomTile.js @@ -1,20 +1,20 @@ import React from "react"; -import {Rect} from "react-konva"; +import { Rect } from "react-konva"; import Shapes from "../../../../shapes/index"; -import {TILE_SIZE_IN_PIXELS} from "../MapConstants"; +import { TILE_SIZE_IN_PIXELS } from "../MapConstants"; -const RoomTile = ({tile, color}) => ( - <Rect - x={tile.positionX * TILE_SIZE_IN_PIXELS} - y={tile.positionY * TILE_SIZE_IN_PIXELS} - width={TILE_SIZE_IN_PIXELS} - height={TILE_SIZE_IN_PIXELS} - fill={color} - /> +const RoomTile = ({ tile, color }) => ( + <Rect + x={tile.positionX * TILE_SIZE_IN_PIXELS} + y={tile.positionY * TILE_SIZE_IN_PIXELS} + width={TILE_SIZE_IN_PIXELS} + height={TILE_SIZE_IN_PIXELS} + fill={color} + /> ); RoomTile.propTypes = { - tile: Shapes.Tile, + tile: Shapes.Tile }; export default RoomTile; diff --git a/src/components/app/map/elements/TileObject.js b/src/components/app/map/elements/TileObject.js index 73bfddba..c1b631db 100644 --- a/src/components/app/map/elements/TileObject.js +++ b/src/components/app/map/elements/TileObject.js @@ -1,25 +1,29 @@ import PropTypes from "prop-types"; import React from "react"; -import {Rect} from "react-konva"; -import {OBJECT_BORDER_COLOR} from "../../../../util/colors"; -import {OBJECT_BORDER_WIDTH_IN_PIXELS, OBJECT_MARGIN_IN_PIXELS, TILE_SIZE_IN_PIXELS} from "../MapConstants"; +import { Rect } from "react-konva"; +import { OBJECT_BORDER_COLOR } from "../../../../util/colors"; +import { + OBJECT_BORDER_WIDTH_IN_PIXELS, + OBJECT_MARGIN_IN_PIXELS, + TILE_SIZE_IN_PIXELS +} from "../MapConstants"; -const TileObject = ({positionX, positionY, color}) => ( - <Rect - x={positionX * TILE_SIZE_IN_PIXELS + OBJECT_MARGIN_IN_PIXELS} - y={positionY * TILE_SIZE_IN_PIXELS + OBJECT_MARGIN_IN_PIXELS} - width={TILE_SIZE_IN_PIXELS - OBJECT_MARGIN_IN_PIXELS * 2} - height={TILE_SIZE_IN_PIXELS - OBJECT_MARGIN_IN_PIXELS * 2} - fill={color} - stroke={OBJECT_BORDER_COLOR} - strokeWidth={OBJECT_BORDER_WIDTH_IN_PIXELS} - /> +const TileObject = ({ positionX, positionY, color }) => ( + <Rect + x={positionX * TILE_SIZE_IN_PIXELS + OBJECT_MARGIN_IN_PIXELS} + y={positionY * TILE_SIZE_IN_PIXELS + OBJECT_MARGIN_IN_PIXELS} + width={TILE_SIZE_IN_PIXELS - OBJECT_MARGIN_IN_PIXELS * 2} + height={TILE_SIZE_IN_PIXELS - OBJECT_MARGIN_IN_PIXELS * 2} + fill={color} + stroke={OBJECT_BORDER_COLOR} + strokeWidth={OBJECT_BORDER_WIDTH_IN_PIXELS} + /> ); TileObject.propTypes = { - positionX: PropTypes.number.isRequired, - positionY: PropTypes.number.isRequired, - color: PropTypes.string.isRequired, + positionX: PropTypes.number.isRequired, + positionY: PropTypes.number.isRequired, + color: PropTypes.string.isRequired }; export default TileObject; diff --git a/src/components/app/map/elements/TilePlusIcon.js b/src/components/app/map/elements/TilePlusIcon.js index b96bf0f5..06377152 100644 --- a/src/components/app/map/elements/TilePlusIcon.js +++ b/src/components/app/map/elements/TilePlusIcon.js @@ -1,44 +1,52 @@ import PropTypes from "prop-types"; import React from "react"; -import {Group, Line} from "react-konva"; -import {TILE_PLUS_COLOR} from "../../../../util/colors"; -import {TILE_PLUS_MARGIN_IN_PIXELS, TILE_PLUS_WIDTH_IN_PIXELS, TILE_SIZE_IN_PIXELS} from "../MapConstants"; +import { Group, Line } from "react-konva"; +import { TILE_PLUS_COLOR } from "../../../../util/colors"; +import { + TILE_PLUS_MARGIN_IN_PIXELS, + TILE_PLUS_WIDTH_IN_PIXELS, + TILE_SIZE_IN_PIXELS +} from "../MapConstants"; -const TilePlusIcon = ({pixelX, pixelY, mapScale}) => { - const linePoints = [ - [ - pixelX + 0.5 * TILE_SIZE_IN_PIXELS * mapScale, - pixelY + TILE_PLUS_MARGIN_IN_PIXELS * mapScale, - pixelX + 0.5 * TILE_SIZE_IN_PIXELS * mapScale, - pixelY + TILE_SIZE_IN_PIXELS * mapScale - TILE_PLUS_MARGIN_IN_PIXELS * mapScale, - ], - [ - pixelX + TILE_PLUS_MARGIN_IN_PIXELS * mapScale, - pixelY + 0.5 * TILE_SIZE_IN_PIXELS * mapScale, - pixelX + TILE_SIZE_IN_PIXELS * mapScale - TILE_PLUS_MARGIN_IN_PIXELS * mapScale, - pixelY + 0.5 * TILE_SIZE_IN_PIXELS * mapScale, - ], - ]; - return ( - <Group> - {linePoints.map((points, index) => ( - <Line - key={index} - points={points} - lineCap="round" - stroke={TILE_PLUS_COLOR} - strokeWidth={TILE_PLUS_WIDTH_IN_PIXELS * mapScale} - listening={false} - /> - ))} - </Group> - ) +const TilePlusIcon = ({ pixelX, pixelY, mapScale }) => { + const linePoints = [ + [ + pixelX + 0.5 * TILE_SIZE_IN_PIXELS * mapScale, + pixelY + TILE_PLUS_MARGIN_IN_PIXELS * mapScale, + pixelX + 0.5 * TILE_SIZE_IN_PIXELS * mapScale, + pixelY + + TILE_SIZE_IN_PIXELS * mapScale - + TILE_PLUS_MARGIN_IN_PIXELS * mapScale + ], + [ + pixelX + TILE_PLUS_MARGIN_IN_PIXELS * mapScale, + pixelY + 0.5 * TILE_SIZE_IN_PIXELS * mapScale, + pixelX + + TILE_SIZE_IN_PIXELS * mapScale - + TILE_PLUS_MARGIN_IN_PIXELS * mapScale, + pixelY + 0.5 * TILE_SIZE_IN_PIXELS * mapScale + ] + ]; + return ( + <Group> + {linePoints.map((points, index) => ( + <Line + key={index} + points={points} + lineCap="round" + stroke={TILE_PLUS_COLOR} + strokeWidth={TILE_PLUS_WIDTH_IN_PIXELS * mapScale} + listening={false} + /> + ))} + </Group> + ); }; TilePlusIcon.propTypes = { - pixelX: PropTypes.number, - pixelY: PropTypes.number, - mapScale: PropTypes.number, + pixelX: PropTypes.number, + pixelY: PropTypes.number, + mapScale: PropTypes.number }; export default TilePlusIcon; diff --git a/src/components/app/map/elements/WallSegment.js b/src/components/app/map/elements/WallSegment.js index 14efd3fc..c5011656 100644 --- a/src/components/app/map/elements/WallSegment.js +++ b/src/components/app/map/elements/WallSegment.js @@ -1,39 +1,39 @@ import React from "react"; -import {Line} from "react-konva"; +import { Line } from "react-konva"; import Shapes from "../../../../shapes/index"; -import {WALL_COLOR} from "../../../../util/colors"; -import {TILE_SIZE_IN_PIXELS, WALL_WIDTH_IN_PIXELS} from "../MapConstants"; +import { WALL_COLOR } from "../../../../util/colors"; +import { TILE_SIZE_IN_PIXELS, WALL_WIDTH_IN_PIXELS } from "../MapConstants"; -const WallSegment = ({wallSegment}) => { - let points; - if (wallSegment.isHorizontal) { - points = [ - wallSegment.startPosX * TILE_SIZE_IN_PIXELS, - wallSegment.startPosY * TILE_SIZE_IN_PIXELS, - (wallSegment.startPosX + wallSegment.length) * TILE_SIZE_IN_PIXELS, - wallSegment.startPosY * TILE_SIZE_IN_PIXELS - ]; - } else { - points = [ - wallSegment.startPosX * TILE_SIZE_IN_PIXELS, - wallSegment.startPosY * TILE_SIZE_IN_PIXELS, - wallSegment.startPosX * TILE_SIZE_IN_PIXELS, - (wallSegment.startPosY + wallSegment.length) * TILE_SIZE_IN_PIXELS, - ]; - } +const WallSegment = ({ wallSegment }) => { + let points; + if (wallSegment.isHorizontal) { + points = [ + wallSegment.startPosX * TILE_SIZE_IN_PIXELS, + wallSegment.startPosY * TILE_SIZE_IN_PIXELS, + (wallSegment.startPosX + wallSegment.length) * TILE_SIZE_IN_PIXELS, + wallSegment.startPosY * TILE_SIZE_IN_PIXELS + ]; + } else { + points = [ + wallSegment.startPosX * TILE_SIZE_IN_PIXELS, + wallSegment.startPosY * TILE_SIZE_IN_PIXELS, + wallSegment.startPosX * TILE_SIZE_IN_PIXELS, + (wallSegment.startPosY + wallSegment.length) * TILE_SIZE_IN_PIXELS + ]; + } - return ( - <Line - points={points} - lineCap="round" - stroke={WALL_COLOR} - strokeWidth={WALL_WIDTH_IN_PIXELS} - /> - ) + return ( + <Line + points={points} + lineCap="round" + stroke={WALL_COLOR} + strokeWidth={WALL_WIDTH_IN_PIXELS} + /> + ); }; WallSegment.propTypes = { - wallSegment: Shapes.WallSegment, + wallSegment: Shapes.WallSegment }; export default WallSegment; diff --git a/src/components/app/map/groups/DatacenterGroup.js b/src/components/app/map/groups/DatacenterGroup.js index 1c978360..51e32db6 100644 --- a/src/components/app/map/groups/DatacenterGroup.js +++ b/src/components/app/map/groups/DatacenterGroup.js @@ -1,42 +1,40 @@ import React from "react"; -import {Group} from "react-konva"; +import { Group } from "react-konva"; import GrayContainer from "../../../../containers/app/map/GrayContainer"; import RoomContainer from "../../../../containers/app/map/RoomContainer"; import Shapes from "../../../../shapes/index"; -const DatacenterGroup = ({datacenter, interactionLevel}) => { - if (!datacenter) { - return <Group/>; - } - - if (interactionLevel.mode === "BUILDING") { - return ( - <Group> - {datacenter.roomIds.map(roomId => ( - <RoomContainer key={roomId} roomId={roomId}/> - ))} - </Group> - ); - } +const DatacenterGroup = ({ datacenter, interactionLevel }) => { + if (!datacenter) { + return <Group />; + } + if (interactionLevel.mode === "BUILDING") { return ( - <Group> - {datacenter.roomIds - .filter(roomId => roomId !== interactionLevel.roomId) - .map(roomId => <RoomContainer key={roomId} roomId={roomId}/>) - } - {interactionLevel.mode === "ROOM" ? <GrayContainer/> : null} - {datacenter.roomIds - .filter(roomId => roomId === interactionLevel.roomId) - .map(roomId => <RoomContainer key={roomId} roomId={roomId}/>) - } - </Group> + <Group> + {datacenter.roomIds.map(roomId => ( + <RoomContainer key={roomId} roomId={roomId} /> + ))} + </Group> ); + } + + return ( + <Group> + {datacenter.roomIds + .filter(roomId => roomId !== interactionLevel.roomId) + .map(roomId => <RoomContainer key={roomId} roomId={roomId} />)} + {interactionLevel.mode === "ROOM" ? <GrayContainer /> : null} + {datacenter.roomIds + .filter(roomId => roomId === interactionLevel.roomId) + .map(roomId => <RoomContainer key={roomId} roomId={roomId} />)} + </Group> + ); }; DatacenterGroup.propTypes = { - datacenter: Shapes.Datacenter, - interactionLevel: Shapes.InteractionLevel, + datacenter: Shapes.Datacenter, + interactionLevel: Shapes.InteractionLevel }; export default DatacenterGroup; diff --git a/src/components/app/map/groups/GridGroup.js b/src/components/app/map/groups/GridGroup.js index b3c6e1d5..bbb1eb68 100644 --- a/src/components/app/map/groups/GridGroup.js +++ b/src/components/app/map/groups/GridGroup.js @@ -1,30 +1,41 @@ import React from "react"; -import {Group, Line} from "react-konva"; -import {GRID_COLOR} from "../../../../util/colors"; -import {GRID_LINE_WIDTH_IN_PIXELS, MAP_SIZE, MAP_SIZE_IN_PIXELS, TILE_SIZE_IN_PIXELS} from "../MapConstants"; +import { Group, Line } from "react-konva"; +import { GRID_COLOR } from "../../../../util/colors"; +import { + GRID_LINE_WIDTH_IN_PIXELS, + MAP_SIZE, + MAP_SIZE_IN_PIXELS, + TILE_SIZE_IN_PIXELS +} from "../MapConstants"; const MAP_COORDINATE_ENTRIES = Array.from(new Array(MAP_SIZE), (x, i) => i); const HORIZONTAL_POINT_PAIRS = MAP_COORDINATE_ENTRIES.map(index => [ - 0, index * TILE_SIZE_IN_PIXELS, - MAP_SIZE_IN_PIXELS, index * TILE_SIZE_IN_PIXELS + 0, + index * TILE_SIZE_IN_PIXELS, + MAP_SIZE_IN_PIXELS, + index * TILE_SIZE_IN_PIXELS ]); const VERTICAL_POINT_PAIRS = MAP_COORDINATE_ENTRIES.map(index => [ - index * TILE_SIZE_IN_PIXELS, 0, - index * TILE_SIZE_IN_PIXELS, MAP_SIZE_IN_PIXELS + index * TILE_SIZE_IN_PIXELS, + 0, + index * TILE_SIZE_IN_PIXELS, + MAP_SIZE_IN_PIXELS ]); const GridGroup = () => ( - <Group> - {HORIZONTAL_POINT_PAIRS.concat(VERTICAL_POINT_PAIRS).map((points, index) => ( - <Line - key={index} - points={points} - stroke={GRID_COLOR} - strokeWidth={GRID_LINE_WIDTH_IN_PIXELS} - listening={false} - /> - ))} - </Group> + <Group> + {HORIZONTAL_POINT_PAIRS.concat( + VERTICAL_POINT_PAIRS + ).map((points, index) => ( + <Line + key={index} + points={points} + stroke={GRID_COLOR} + strokeWidth={GRID_LINE_WIDTH_IN_PIXELS} + listening={false} + /> + ))} + </Group> ); export default GridGroup; diff --git a/src/components/app/map/groups/RackGroup.js b/src/components/app/map/groups/RackGroup.js index 57062187..69d6ac10 100644 --- a/src/components/app/map/groups/RackGroup.js +++ b/src/components/app/map/groups/RackGroup.js @@ -1,31 +1,43 @@ import React from "react"; -import {Group} from "react-konva"; +import { Group } from "react-konva"; import RackEnergyFillContainer from "../../../../containers/app/map/RackEnergyFillContainer"; import RackSpaceFillContainer from "../../../../containers/app/map/RackSpaceFillContainer"; import Shapes from "../../../../shapes/index"; -import {RACK_BACKGROUND_COLOR} from "../../../../util/colors"; -import {convertLoadToSimulationColor} from "../../../../util/simulation-load"; +import { RACK_BACKGROUND_COLOR } from "../../../../util/colors"; +import { convertLoadToSimulationColor } from "../../../../util/simulation-load"; import TileObject from "../elements/TileObject"; -const RackGroup = ({tile, inSimulation, rackLoad}) => { - let color = RACK_BACKGROUND_COLOR; - if (inSimulation && rackLoad >= 0) { - color = convertLoadToSimulationColor(rackLoad); - } +const RackGroup = ({ tile, inSimulation, rackLoad }) => { + let color = RACK_BACKGROUND_COLOR; + if (inSimulation && rackLoad >= 0) { + color = convertLoadToSimulationColor(rackLoad); + } - return ( - <Group> - <TileObject positionX={tile.positionX} positionY={tile.positionY} color={color}/> - <Group opacity={inSimulation ? 0.3 : 1}> - <RackSpaceFillContainer tileId={tile.id} positionX={tile.positionX} positionY={tile.positionY}/> - <RackEnergyFillContainer tileId={tile.id} positionX={tile.positionX} positionY={tile.positionY}/> - </Group> - </Group> - ); + return ( + <Group> + <TileObject + positionX={tile.positionX} + positionY={tile.positionY} + color={color} + /> + <Group opacity={inSimulation ? 0.3 : 1}> + <RackSpaceFillContainer + tileId={tile.id} + positionX={tile.positionX} + positionY={tile.positionY} + /> + <RackEnergyFillContainer + tileId={tile.id} + positionX={tile.positionX} + positionY={tile.positionY} + /> + </Group> + </Group> + ); }; RackGroup.propTypes = { - tile: Shapes.Tile, + tile: Shapes.Tile }; export default RackGroup; diff --git a/src/components/app/map/groups/RoomGroup.js b/src/components/app/map/groups/RoomGroup.js index 18a6bd84..c8f0d3db 100644 --- a/src/components/app/map/groups/RoomGroup.js +++ b/src/components/app/map/groups/RoomGroup.js @@ -1,48 +1,56 @@ import React from "react"; -import {Group} from "react-konva"; +import { Group } from "react-konva"; import GrayContainer from "../../../../containers/app/map/GrayContainer"; import TileContainer from "../../../../containers/app/map/TileContainer"; import WallContainer from "../../../../containers/app/map/WallContainer"; import Shapes from "../../../../shapes/index"; -const RoomGroup = ({room, interactionLevel, currentRoomInConstruction, onClick}) => { - if (currentRoomInConstruction === room.id) { - return ( - <Group onClick={onClick}> - {room.tileIds.map(tileId => ( - <TileContainer key={tileId} tileId={tileId} newTile={true}/> - ))} - </Group> - ); - } - +const RoomGroup = ({ + room, + interactionLevel, + currentRoomInConstruction, + onClick +}) => { + if (currentRoomInConstruction === room.id) { return ( - <Group onClick={onClick}> - {(() => { - if ((interactionLevel.mode === "RACK" || interactionLevel.mode === "MACHINE") - && interactionLevel.roomId === room.id) { - return [ - room.tileIds - .filter(tileId => tileId !== interactionLevel.tileId) - .map(tileId => <TileContainer key={tileId} tileId={tileId}/>), - <GrayContainer key={-1}/>, - room.tileIds - .filter(tileId => tileId === interactionLevel.tileId) - .map(tileId => <TileContainer key={tileId} tileId={tileId}/>) - ]; - } else { - return room.tileIds.map(tileId => ( - <TileContainer key={tileId} tileId={tileId}/> - )); - } - })()} - <WallContainer roomId={room.id}/> - </Group> + <Group onClick={onClick}> + {room.tileIds.map(tileId => ( + <TileContainer key={tileId} tileId={tileId} newTile={true} /> + ))} + </Group> ); + } + + return ( + <Group onClick={onClick}> + {(() => { + if ( + (interactionLevel.mode === "RACK" || + interactionLevel.mode === "MACHINE") && + interactionLevel.roomId === room.id + ) { + return [ + room.tileIds + .filter(tileId => tileId !== interactionLevel.tileId) + .map(tileId => <TileContainer key={tileId} tileId={tileId} />), + <GrayContainer key={-1} />, + room.tileIds + .filter(tileId => tileId === interactionLevel.tileId) + .map(tileId => <TileContainer key={tileId} tileId={tileId} />) + ]; + } else { + return room.tileIds.map(tileId => ( + <TileContainer key={tileId} tileId={tileId} /> + )); + } + })()} + <WallContainer roomId={room.id} /> + </Group> + ); }; RoomGroup.propTypes = { - room: Shapes.Room, + room: Shapes.Room }; export default RoomGroup; diff --git a/src/components/app/map/groups/TileGroup.js b/src/components/app/map/groups/TileGroup.js index 0cd4ea59..8f3953d7 100644 --- a/src/components/app/map/groups/TileGroup.js +++ b/src/components/app/map/groups/TileGroup.js @@ -1,42 +1,43 @@ import PropTypes from "prop-types"; import React from "react"; -import {Group} from "react-konva"; +import { Group } from "react-konva"; import RackContainer from "../../../../containers/app/map/RackContainer"; import Shapes from "../../../../shapes/index"; -import {ROOM_DEFAULT_COLOR, ROOM_IN_CONSTRUCTION_COLOR} from "../../../../util/colors"; -import {convertLoadToSimulationColor} from "../../../../util/simulation-load"; +import { + ROOM_DEFAULT_COLOR, + ROOM_IN_CONSTRUCTION_COLOR +} from "../../../../util/colors"; +import { convertLoadToSimulationColor } from "../../../../util/simulation-load"; import RoomTile from "../elements/RoomTile"; -const TileGroup = ({tile, newTile, inSimulation, roomLoad, onClick}) => { - let tileObject; - switch (tile.objectType) { - case "RACK": - tileObject = <RackContainer tile={tile}/>; - break; - default: - tileObject = null; - } +const TileGroup = ({ tile, newTile, inSimulation, roomLoad, onClick }) => { + let tileObject; + switch (tile.objectType) { + case "RACK": + tileObject = <RackContainer tile={tile} />; + break; + default: + tileObject = null; + } - let color = ROOM_DEFAULT_COLOR; - if (newTile) { - color = ROOM_IN_CONSTRUCTION_COLOR; - } else if (inSimulation && roomLoad >= 0) { - color = convertLoadToSimulationColor(roomLoad); - } + let color = ROOM_DEFAULT_COLOR; + if (newTile) { + color = ROOM_IN_CONSTRUCTION_COLOR; + } else if (inSimulation && roomLoad >= 0) { + color = convertLoadToSimulationColor(roomLoad); + } - return ( - <Group - onClick={() => onClick(tile)} - > - <RoomTile tile={tile} color={color}/> - {tileObject} - </Group> - ); + return ( + <Group onClick={() => onClick(tile)}> + <RoomTile tile={tile} color={color} /> + {tileObject} + </Group> + ); }; TileGroup.propTypes = { - tile: Shapes.Tile, - newTile: PropTypes.bool, + tile: Shapes.Tile, + newTile: PropTypes.bool }; export default TileGroup; diff --git a/src/components/app/map/groups/WallGroup.js b/src/components/app/map/groups/WallGroup.js index 6de22523..43de66e8 100644 --- a/src/components/app/map/groups/WallGroup.js +++ b/src/components/app/map/groups/WallGroup.js @@ -1,22 +1,22 @@ import PropTypes from "prop-types"; import React from "react"; -import {Group} from "react-konva"; +import { Group } from "react-konva"; import Shapes from "../../../../shapes/index"; -import {deriveWallLocations} from "../../../../util/tile-calculations"; +import { deriveWallLocations } from "../../../../util/tile-calculations"; import WallSegment from "../elements/WallSegment"; -const WallGroup = ({tiles}) => { - return ( - <Group> - {deriveWallLocations(tiles).map((wallSegment, index) => ( - <WallSegment key={index} wallSegment={wallSegment}/> - ))} - </Group> - ); +const WallGroup = ({ tiles }) => { + return ( + <Group> + {deriveWallLocations(tiles).map((wallSegment, index) => ( + <WallSegment key={index} wallSegment={wallSegment} /> + ))} + </Group> + ); }; WallGroup.propTypes = { - tiles: PropTypes.arrayOf(Shapes.Tile).isRequired, + tiles: PropTypes.arrayOf(Shapes.Tile).isRequired }; export default WallGroup; diff --git a/src/components/app/map/layers/HoverLayerComponent.js b/src/components/app/map/layers/HoverLayerComponent.js index aa2e8313..c39532f1 100644 --- a/src/components/app/map/layers/HoverLayerComponent.js +++ b/src/components/app/map/layers/HoverLayerComponent.js @@ -1,63 +1,85 @@ import PropTypes from "prop-types"; -import React from 'react'; -import {Layer} from "react-konva"; +import React from "react"; +import { Layer } from "react-konva"; import HoverTile from "../elements/HoverTile"; -import {TILE_SIZE_IN_PIXELS} from "../MapConstants"; +import { TILE_SIZE_IN_PIXELS } from "../MapConstants"; class HoverLayerComponent extends React.Component { - static propTypes = { - mouseX: PropTypes.number.isRequired, - mouseY: PropTypes.number.isRequired, - mapPosition: PropTypes.object.isRequired, - mapScale: PropTypes.number.isRequired, - isEnabled: PropTypes.func.isRequired, - onClick: PropTypes.func.isRequired, - }; - - state = { - positionX: -1, - positionY: -1, - validity: false, - }; - - componentDidUpdate() { - if (!this.props.isEnabled()) { - return; - } - - const positionX = Math.floor((this.props.mouseX - this.props.mapPosition.x) / (this.props.mapScale * TILE_SIZE_IN_PIXELS)); - const positionY = Math.floor((this.props.mouseY - this.props.mapPosition.y) / (this.props.mapScale * TILE_SIZE_IN_PIXELS)); - - if (positionX !== this.state.positionX || positionY !== this.state.positionY) { - this.setState({positionX, positionY, validity: this.props.isValid(positionX, positionY)}); - } + static propTypes = { + mouseX: PropTypes.number.isRequired, + mouseY: PropTypes.number.isRequired, + mapPosition: PropTypes.object.isRequired, + mapScale: PropTypes.number.isRequired, + isEnabled: PropTypes.func.isRequired, + onClick: PropTypes.func.isRequired + }; + + state = { + positionX: -1, + positionY: -1, + validity: false + }; + + componentDidUpdate() { + if (!this.props.isEnabled()) { + return; } - render() { - if (!this.props.isEnabled()) { - return <Layer/>; - } - - const pixelX = this.props.mapScale * this.state.positionX * TILE_SIZE_IN_PIXELS + this.props.mapPosition.x; - const pixelY = this.props.mapScale * this.state.positionY * TILE_SIZE_IN_PIXELS + this.props.mapPosition.y; - - return ( - <Layer opacity={0.6}> - <HoverTile - pixelX={pixelX} - pixelY={pixelY} - scale={this.props.mapScale} - isValid={this.state.validity} - onClick={() => this.state.validity ? - this.props.onClick(this.state.positionX, this.state.positionY) : undefined} - /> - {this.props.children ? - React.cloneElement(this.props.children, {pixelX, pixelY, scale: this.props.mapScale}) : - undefined - } - </Layer> - ); + const positionX = Math.floor( + (this.props.mouseX - this.props.mapPosition.x) / + (this.props.mapScale * TILE_SIZE_IN_PIXELS) + ); + const positionY = Math.floor( + (this.props.mouseY - this.props.mapPosition.y) / + (this.props.mapScale * TILE_SIZE_IN_PIXELS) + ); + + if ( + positionX !== this.state.positionX || + positionY !== this.state.positionY + ) { + this.setState({ + positionX, + positionY, + validity: this.props.isValid(positionX, positionY) + }); } + } + + render() { + if (!this.props.isEnabled()) { + return <Layer />; + } + + const pixelX = + this.props.mapScale * this.state.positionX * TILE_SIZE_IN_PIXELS + + this.props.mapPosition.x; + const pixelY = + this.props.mapScale * this.state.positionY * TILE_SIZE_IN_PIXELS + + this.props.mapPosition.y; + + return ( + <Layer opacity={0.6}> + <HoverTile + pixelX={pixelX} + pixelY={pixelY} + scale={this.props.mapScale} + isValid={this.state.validity} + onClick={() => + this.state.validity + ? this.props.onClick(this.state.positionX, this.state.positionY) + : undefined} + /> + {this.props.children + ? React.cloneElement(this.props.children, { + pixelX, + pixelY, + scale: this.props.mapScale + }) + : undefined} + </Layer> + ); + } } export default HoverLayerComponent; diff --git a/src/components/app/map/layers/MapLayerComponent.js b/src/components/app/map/layers/MapLayerComponent.js index c969249c..6ad3cb88 100644 --- a/src/components/app/map/layers/MapLayerComponent.js +++ b/src/components/app/map/layers/MapLayerComponent.js @@ -1,17 +1,22 @@ -import React from 'react'; -import {Group, Layer} from "react-konva"; +import React from "react"; +import { Group, Layer } from "react-konva"; import DatacenterContainer from "../../../../containers/app/map/DatacenterContainer"; import Backdrop from "../elements/Backdrop"; import GridGroup from "../groups/GridGroup"; -const MapLayerComponent = ({mapPosition, mapScale}) => ( - <Layer> - <Group x={mapPosition.x} y={mapPosition.y} scaleX={mapScale} scaleY={mapScale}> - <Backdrop/> - <DatacenterContainer/> - <GridGroup/> - </Group> - </Layer> +const MapLayerComponent = ({ mapPosition, mapScale }) => ( + <Layer> + <Group + x={mapPosition.x} + y={mapPosition.y} + scaleX={mapScale} + scaleY={mapScale} + > + <Backdrop /> + <DatacenterContainer /> + <GridGroup /> + </Group> + </Layer> ); export default MapLayerComponent; diff --git a/src/components/app/map/layers/ObjectHoverLayerComponent.js b/src/components/app/map/layers/ObjectHoverLayerComponent.js index aa79f8c3..e7342d3c 100644 --- a/src/components/app/map/layers/ObjectHoverLayerComponent.js +++ b/src/components/app/map/layers/ObjectHoverLayerComponent.js @@ -1,11 +1,11 @@ -import React from 'react'; +import React from "react"; import TilePlusIcon from "../elements/TilePlusIcon"; import HoverLayerComponent from "./HoverLayerComponent"; -const ObjectHoverLayerComponent = (props) => ( - <HoverLayerComponent {...props}> - <TilePlusIcon {...props}/> - </HoverLayerComponent> +const ObjectHoverLayerComponent = props => ( + <HoverLayerComponent {...props}> + <TilePlusIcon {...props} /> + </HoverLayerComponent> ); export default ObjectHoverLayerComponent; diff --git a/src/components/app/map/layers/RoomHoverLayerComponent.js b/src/components/app/map/layers/RoomHoverLayerComponent.js index 2133c8d8..feea5ae5 100644 --- a/src/components/app/map/layers/RoomHoverLayerComponent.js +++ b/src/components/app/map/layers/RoomHoverLayerComponent.js @@ -1,8 +1,6 @@ -import React from 'react'; +import React from "react"; import HoverLayerComponent from "./HoverLayerComponent"; -const RoomHoverLayerComponent = (props) => ( - <HoverLayerComponent {...props}/> -); +const RoomHoverLayerComponent = props => <HoverLayerComponent {...props} />; export default RoomHoverLayerComponent; diff --git a/src/components/app/sidebars/Sidebar.js b/src/components/app/sidebars/Sidebar.js index 00e3607a..33dbe011 100644 --- a/src/components/app/sidebars/Sidebar.js +++ b/src/components/app/sidebars/Sidebar.js @@ -3,36 +3,48 @@ import React from "react"; import "./Sidebar.css"; class Sidebar extends React.Component { - state = { - collapsed: false - }; + state = { + collapsed: false + }; - render() { - const collapseButton = ( - <div - className={classNames("sidebar-collapse-button", {"sidebar-collapse-button-right": this.props.isRight})} - onClick={() => this.setState({collapsed: !this.state.collapsed})} - > - {(this.state.collapsed && this.props.isRight) || (!this.state.collapsed && !this.props.isRight) ? - <span className="fa fa-angle-left" title={this.props.isRight ? "Expand" : "Collapse"}/> : - <span className="fa fa-angle-right" title={this.props.isRight ? "Collapse" : "Expand"}/> - } - </div> - ); + render() { + const collapseButton = ( + <div + className={classNames("sidebar-collapse-button", { + "sidebar-collapse-button-right": this.props.isRight + })} + onClick={() => this.setState({ collapsed: !this.state.collapsed })} + > + {(this.state.collapsed && this.props.isRight) || + (!this.state.collapsed && !this.props.isRight) ? ( + <span + className="fa fa-angle-left" + title={this.props.isRight ? "Expand" : "Collapse"} + /> + ) : ( + <span + className="fa fa-angle-right" + title={this.props.isRight ? "Collapse" : "Expand"} + /> + )} + </div> + ); - if (this.state.collapsed) { - return collapseButton; - } - return ( - <div - className={classNames("sidebar p-3 h-100", {"sidebar-right": this.props.isRight})} - onWheel={e => e.stopPropagation()} - > - {this.props.children} - {collapseButton} - </div> - ); + if (this.state.collapsed) { + return collapseButton; } + return ( + <div + className={classNames("sidebar p-3 h-100", { + "sidebar-right": this.props.isRight + })} + onWheel={e => e.stopPropagation()} + > + {this.props.children} + {collapseButton} + </div> + ); + } } export default Sidebar; diff --git a/src/components/app/sidebars/elements/LoadBarComponent.js b/src/components/app/sidebars/elements/LoadBarComponent.js index 65f94b3d..8c9b164b 100644 --- a/src/components/app/sidebars/elements/LoadBarComponent.js +++ b/src/components/app/sidebars/elements/LoadBarComponent.js @@ -1,22 +1,22 @@ import classNames from "classnames"; import React from "react"; -const LoadBarComponent = ({percent, disabled}) => ( - <div className="mt-1"> - <strong>Current load</strong> - <div className={classNames("progress", {disabled})}> - <div - className="progress-bar" - role="progressbar" - aria-valuenow={percent} - aria-valuemin="0" - aria-valuemax="100" - style={{width: percent + "%"}} - > - {percent}% - </div> - </div> +const LoadBarComponent = ({ percent, disabled }) => ( + <div className="mt-1"> + <strong>Current load</strong> + <div className={classNames("progress", { disabled })}> + <div + className="progress-bar" + role="progressbar" + aria-valuenow={percent} + aria-valuemin="0" + aria-valuemax="100" + style={{ width: percent + "%" }} + > + {percent}% + </div> </div> + </div> ); export default LoadBarComponent; diff --git a/src/components/app/sidebars/elements/LoadChartComponent.js b/src/components/app/sidebars/elements/LoadChartComponent.js index 91d89287..6f66010e 100644 --- a/src/components/app/sidebars/elements/LoadChartComponent.js +++ b/src/components/app/sidebars/elements/LoadChartComponent.js @@ -1,73 +1,81 @@ import React from "react"; import ReactDOM from "react-dom/server"; import SvgSaver from "svgsaver"; -import {VictoryAxis, VictoryChart, VictoryLine, VictoryScatter} from "victory"; -import {convertSecondsToFormattedTime} from "../../../../util/date-time"; +import { + VictoryAxis, + VictoryChart, + VictoryLine, + VictoryScatter +} from "victory"; +import { convertSecondsToFormattedTime } from "../../../../util/date-time"; -const LoadChartComponent = ({data, currentTick}) => { - const onExport = () => { - const div = document.createElement("div"); - div.innerHTML = ReactDOM.renderToString( - <VictoryChartComponent data={data} currentTick={currentTick} showCurrentTick={false}/> - ); - div.firstChild.style = "font-family: Roboto, Arial, sans-serif; font-size: 10pt;"; - const svgSaver = new SvgSaver(); - svgSaver.asSvg(div.firstChild, "opendc-chart-export-" + Date.now() + ".svg"); - }; - - return ( - <div className="mt-1" style={{position: "relative"}}> - <strong>Load over time</strong> - <VictoryChartComponent data={data} currentTick={currentTick} showCurrentTick={true}/> - <ExportChartComponent onExport={onExport}/> - </div> +const LoadChartComponent = ({ data, currentTick }) => { + const onExport = () => { + const div = document.createElement("div"); + div.innerHTML = ReactDOM.renderToString( + <VictoryChartComponent + data={data} + currentTick={currentTick} + showCurrentTick={false} + /> + ); + div.firstChild.style = + "font-family: Roboto, Arial, sans-serif; font-size: 10pt;"; + const svgSaver = new SvgSaver(); + svgSaver.asSvg( + div.firstChild, + "opendc-chart-export-" + Date.now() + ".svg" ); + }; + + return ( + <div className="mt-1" style={{ position: "relative" }}> + <strong>Load over time</strong> + <VictoryChartComponent + data={data} + currentTick={currentTick} + showCurrentTick={true} + /> + <ExportChartComponent onExport={onExport} /> + </div> + ); }; -const VictoryChartComponent = ({data, currentTick, showCurrentTick}) => ( - <VictoryChart - height={250} - padding={{top: 10, bottom: 50, left: 50, right: 50}} - > - <VictoryAxis - tickFormat={tick => convertSecondsToFormattedTime(tick)} - fixLabelOverlap={true} - label="Simulated Time" - /> - <VictoryAxis - dependentAxis - label="Load" - /> - <VictoryLine - data={data} - /> - <VictoryScatter - data={data} - /> - {showCurrentTick ? - <VictoryLine - data={[ - {x: currentTick + 1, y: 0}, - {x: currentTick + 1, y: 1}, - ]} - style={{ - data: {stroke: "#00A6D6", strokeWidth: 3} - }} - /> : - undefined - } - </VictoryChart> +const VictoryChartComponent = ({ data, currentTick, showCurrentTick }) => ( + <VictoryChart + height={250} + padding={{ top: 10, bottom: 50, left: 50, right: 50 }} + > + <VictoryAxis + tickFormat={tick => convertSecondsToFormattedTime(tick)} + fixLabelOverlap={true} + label="Simulated Time" + /> + <VictoryAxis dependentAxis label="Load" /> + <VictoryLine data={data} /> + <VictoryScatter data={data} /> + {showCurrentTick ? ( + <VictoryLine + data={[{ x: currentTick + 1, y: 0 }, { x: currentTick + 1, y: 1 }]} + style={{ + data: { stroke: "#00A6D6", strokeWidth: 3 } + }} + /> + ) : ( + undefined + )} + </VictoryChart> ); -const ExportChartComponent = ({onExport}) => ( - <button - className="btn btn-success btn-circle btn-sm" - title="Export Chart to PNG Image" - onClick={onExport} - style={{position: "absolute", top: 0, right: 0}} - > - <span className="fa fa-camera"/> - </button> +const ExportChartComponent = ({ onExport }) => ( + <button + className="btn btn-success btn-circle btn-sm" + title="Export Chart to PNG Image" + onClick={onExport} + style={{ position: "absolute", top: 0, right: 0 }} + > + <span className="fa fa-camera" /> + </button> ); export default LoadChartComponent; diff --git a/src/components/app/sidebars/simulation/ExperimentMetadataComponent.js b/src/components/app/sidebars/simulation/ExperimentMetadataComponent.js index 3649045b..bc563dab 100644 --- a/src/components/app/sidebars/simulation/ExperimentMetadataComponent.js +++ b/src/components/app/sidebars/simulation/ExperimentMetadataComponent.js @@ -1,12 +1,23 @@ import React from "react"; -const ExperimentMetadataComponent = ({experimentName, pathName, traceName, schedulerName}) => ( - <div> - <h2>{experimentName}</h2> - <p>Path: <strong>{pathName}</strong></p> - <p>Trace: <strong>{traceName}</strong></p> - <p>Scheduler: <strong>{schedulerName}</strong></p> - </div> +const ExperimentMetadataComponent = ({ + experimentName, + pathName, + traceName, + schedulerName +}) => ( + <div> + <h2>{experimentName}</h2> + <p> + Path: <strong>{pathName}</strong> + </p> + <p> + Trace: <strong>{traceName}</strong> + </p> + <p> + Scheduler: <strong>{schedulerName}</strong> + </p> + </div> ); export default ExperimentMetadataComponent; diff --git a/src/components/app/sidebars/simulation/LoadMetricComponent.js b/src/components/app/sidebars/simulation/LoadMetricComponent.js index e72e6b67..3e4cf810 100644 --- a/src/components/app/sidebars/simulation/LoadMetricComponent.js +++ b/src/components/app/sidebars/simulation/LoadMetricComponent.js @@ -1,33 +1,40 @@ import React from "react"; -import {SIM_HIGH_COLOR, SIM_LOW_COLOR, SIM_MID_HIGH_COLOR, SIM_MID_LOW_COLOR} from "../../../../util/colors"; -import {LOAD_NAME_MAP} from "../../../../util/simulation-load"; +import { + SIM_HIGH_COLOR, + SIM_LOW_COLOR, + SIM_MID_HIGH_COLOR, + SIM_MID_LOW_COLOR +} from "../../../../util/colors"; +import { LOAD_NAME_MAP } from "../../../../util/simulation-load"; -const LoadMetricComponent = ({loadMetric}) => ( +const LoadMetricComponent = ({ loadMetric }) => ( + <div> <div> - <div>Colors represent <strong>{LOAD_NAME_MAP[loadMetric]}</strong></div> - <div className="btn-group mb-2" style={{display: "flex"}}> - <span - className="btn btn-secondary" - style={{backgroundColor: SIM_LOW_COLOR, flex: 1}} - title="0-25%" - /> - <span - className="btn btn-secondary" - style={{backgroundColor: SIM_MID_LOW_COLOR, flex: 1}} - title="25-50%" - /> - <span - className="btn btn-secondary" - style={{backgroundColor: SIM_MID_HIGH_COLOR, flex: 1}} - title="50-75%" - /> - <span - className="btn btn-secondary" - style={{backgroundColor: SIM_HIGH_COLOR, flex: 1}} - title="75-100%" - /> - </div> + Colors represent <strong>{LOAD_NAME_MAP[loadMetric]}</strong> </div> + <div className="btn-group mb-2" style={{ display: "flex" }}> + <span + className="btn btn-secondary" + style={{ backgroundColor: SIM_LOW_COLOR, flex: 1 }} + title="0-25%" + /> + <span + className="btn btn-secondary" + style={{ backgroundColor: SIM_MID_LOW_COLOR, flex: 1 }} + title="25-50%" + /> + <span + className="btn btn-secondary" + style={{ backgroundColor: SIM_MID_HIGH_COLOR, flex: 1 }} + title="50-75%" + /> + <span + className="btn btn-secondary" + style={{ backgroundColor: SIM_HIGH_COLOR, flex: 1 }} + title="75-100%" + /> + </div> + </div> ); export default LoadMetricComponent; diff --git a/src/components/app/sidebars/simulation/SimulationSidebarComponent.js b/src/components/app/sidebars/simulation/SimulationSidebarComponent.js index 92651dfc..08dbb29a 100644 --- a/src/components/app/sidebars/simulation/SimulationSidebarComponent.js +++ b/src/components/app/sidebars/simulation/SimulationSidebarComponent.js @@ -6,17 +6,17 @@ import Sidebar from "../Sidebar"; import "./SimulationSidebarComponent.css"; const SimulationSidebarComponent = () => { - return ( - <Sidebar isRight={false}> - <div className="simulation-sidebar-container flex-column"> - <ExperimentMetadataContainer/> - <LoadMetricContainer/> - <div className="trace-container"> - <TraceContainer/> - </div> - </div> - </Sidebar> - ); + return ( + <Sidebar isRight={false}> + <div className="simulation-sidebar-container flex-column"> + <ExperimentMetadataContainer /> + <LoadMetricContainer /> + <div className="trace-container"> + <TraceContainer /> + </div> + </div> + </Sidebar> + ); }; export default SimulationSidebarComponent; diff --git a/src/components/app/sidebars/simulation/TaskComponent.js b/src/components/app/sidebars/simulation/TaskComponent.js index baf6f9ce..bd917cc9 100644 --- a/src/components/app/sidebars/simulation/TaskComponent.js +++ b/src/components/app/sidebars/simulation/TaskComponent.js @@ -1,57 +1,58 @@ import approx from "approximate-number"; import classNames from "classnames"; import React from "react"; -import {convertSecondsToFormattedTime} from "../../../../util/date-time"; +import { convertSecondsToFormattedTime } from "../../../../util/date-time"; -const TaskComponent = ({task, flopsLeft}) => { - let icon; - let progressBarContent; - let percent; - let infoTitle; +const TaskComponent = ({ task, flopsLeft }) => { + let icon; + let progressBarContent; + let percent; + let infoTitle; - if (flopsLeft === task.totalFlopCount) { - icon = "hourglass-half"; - progressBarContent = ""; - percent = 0; - infoTitle = "Not submitted yet"; - } else if (flopsLeft > 0) { - icon = "refresh"; - progressBarContent = approx(task.totalFlopCount - flopsLeft) + " FLOP"; - percent = 100 * (task.totalFlopCount - flopsLeft) / task.totalFlopCount; - infoTitle = progressBarContent + " (" + Math.round(percent * 10) / 10 + "%)"; - } else { - icon = "check"; - progressBarContent = "Completed"; - percent = 100; - infoTitle = "Completed"; - } + if (flopsLeft === task.totalFlopCount) { + icon = "hourglass-half"; + progressBarContent = ""; + percent = 0; + infoTitle = "Not submitted yet"; + } else if (flopsLeft > 0) { + icon = "refresh"; + progressBarContent = approx(task.totalFlopCount - flopsLeft) + " FLOP"; + percent = 100 * (task.totalFlopCount - flopsLeft) / task.totalFlopCount; + infoTitle = + progressBarContent + " (" + Math.round(percent * 10) / 10 + "%)"; + } else { + icon = "check"; + progressBarContent = "Completed"; + percent = 100; + infoTitle = "Completed"; + } - return ( - <li className="list-group-item flex-column align-items-start"> - <div className="d-flex w-100 justify-content-between"> - <h5 className="mb-1">{approx(task.totalFlopCount)} FLOP</h5> - <small>Starts at {convertSecondsToFormattedTime(task.startTick)}</small> - </div> - <div title={infoTitle} style={{display: "flex"}}> - <span - className={classNames("fa", "fa-" + icon)} - style={{width: "20px"}} - /> - <div className="progress" style={{flexGrow: 1}}> - <div - className="progress-bar" - role="progressbar" - aria-valuenow={percent} - aria-valuemin="0" - aria-valuemax="100" - style={{width: percent + "%"}} - > - {progressBarContent} - </div> - </div> - </div> - </li> - ); + return ( + <li className="list-group-item flex-column align-items-start"> + <div className="d-flex w-100 justify-content-between"> + <h5 className="mb-1">{approx(task.totalFlopCount)} FLOP</h5> + <small>Starts at {convertSecondsToFormattedTime(task.startTick)}</small> + </div> + <div title={infoTitle} style={{ display: "flex" }}> + <span + className={classNames("fa", "fa-" + icon)} + style={{ width: "20px" }} + /> + <div className="progress" style={{ flexGrow: 1 }}> + <div + className="progress-bar" + role="progressbar" + aria-valuenow={percent} + aria-valuemin="0" + aria-valuemax="100" + style={{ width: percent + "%" }} + > + {progressBarContent} + </div> + </div> + </div> + </li> + ); }; export default TaskComponent; diff --git a/src/components/app/sidebars/simulation/TraceComponent.js b/src/components/app/sidebars/simulation/TraceComponent.js index b43a8cea..2b6559b4 100644 --- a/src/components/app/sidebars/simulation/TraceComponent.js +++ b/src/components/app/sidebars/simulation/TraceComponent.js @@ -1,20 +1,20 @@ import React from "react"; import TaskContainer from "../../../../containers/app/sidebars/simulation/TaskContainer"; -const TraceComponent = ({jobs}) => ( - <div> - <h3>Trace</h3> - {jobs.map(job => ( - <div key={job.id}> - <h4>Job: {job.name}</h4> - <ul className="list-group"> - {job.taskIds.map(taskId => ( - <TaskContainer taskId={taskId} key={taskId}/> - ))} - </ul> - </div> - ))} - </div> +const TraceComponent = ({ jobs }) => ( + <div> + <h3>Trace</h3> + {jobs.map(job => ( + <div key={job.id}> + <h4>Job: {job.name}</h4> + <ul className="list-group"> + {job.taskIds.map(taskId => ( + <TaskContainer taskId={taskId} key={taskId} /> + ))} + </ul> + </div> + ))} + </div> ); export default TraceComponent; diff --git a/src/components/app/sidebars/topology/NameComponent.js b/src/components/app/sidebars/topology/NameComponent.js index d663f4ae..805538b3 100644 --- a/src/components/app/sidebars/topology/NameComponent.js +++ b/src/components/app/sidebars/topology/NameComponent.js @@ -1,13 +1,13 @@ import React from "react"; import FontAwesome from "react-fontawesome"; -const NameComponent = ({name, onEdit}) => ( - <h2> - {name} - <button className="btn btn-outline-secondary float-right" onClick={onEdit}> - <FontAwesome name="pencil"/> - </button> - </h2> +const NameComponent = ({ name, onEdit }) => ( + <h2> + {name} + <button className="btn btn-outline-secondary float-right" onClick={onEdit}> + <FontAwesome name="pencil" /> + </button> + </h2> ); export default NameComponent; diff --git a/src/components/app/sidebars/topology/TopologySidebarComponent.js b/src/components/app/sidebars/topology/TopologySidebarComponent.js index ff4260a9..81e510a1 100644 --- a/src/components/app/sidebars/topology/TopologySidebarComponent.js +++ b/src/components/app/sidebars/topology/TopologySidebarComponent.js @@ -5,31 +5,27 @@ import RackSidebarContainer from "../../../../containers/app/sidebars/topology/r import RoomSidebarContainer from "../../../../containers/app/sidebars/topology/room/RoomSidebarContainer"; import Sidebar from "../Sidebar"; -const TopologySidebarComponent = ({interactionLevel}) => { - let sidebarContent; +const TopologySidebarComponent = ({ interactionLevel }) => { + let sidebarContent; - switch (interactionLevel.mode) { - case "BUILDING": - sidebarContent = <BuildingSidebarContainer/>; - break; - case "ROOM": - sidebarContent = <RoomSidebarContainer/>; - break; - case "RACK": - sidebarContent = <RackSidebarContainer/>; - break; - case "MACHINE": - sidebarContent = <MachineSidebarContainer/>; - break; - default: - sidebarContent = "Missing Content"; - } + switch (interactionLevel.mode) { + case "BUILDING": + sidebarContent = <BuildingSidebarContainer />; + break; + case "ROOM": + sidebarContent = <RoomSidebarContainer />; + break; + case "RACK": + sidebarContent = <RackSidebarContainer />; + break; + case "MACHINE": + sidebarContent = <MachineSidebarContainer />; + break; + default: + sidebarContent = "Missing Content"; + } - return ( - <Sidebar isRight={true}> - {sidebarContent} - </Sidebar> - ); + return <Sidebar isRight={true}>{sidebarContent}</Sidebar>; }; export default TopologySidebarComponent; diff --git a/src/components/app/sidebars/topology/building/BuildingSidebarComponent.js b/src/components/app/sidebars/topology/building/BuildingSidebarComponent.js index 2bf81a48..f16c19f0 100644 --- a/src/components/app/sidebars/topology/building/BuildingSidebarComponent.js +++ b/src/components/app/sidebars/topology/building/BuildingSidebarComponent.js @@ -1,19 +1,20 @@ import React from "react"; import NewRoomConstructionContainer from "../../../../../containers/app/sidebars/topology/building/NewRoomConstructionContainer"; -const BuildingSidebarComponent = ({inSimulation}) => { - return ( - <div> - <h2>Building</h2> - {inSimulation ? - <div className="alert alert-info"> - <span className="fa fa-info-circle mr-2"/> - <strong>Click on individual rooms</strong> to see their stats! - </div> : - <NewRoomConstructionContainer/> - } +const BuildingSidebarComponent = ({ inSimulation }) => { + return ( + <div> + <h2>Building</h2> + {inSimulation ? ( + <div className="alert alert-info"> + <span className="fa fa-info-circle mr-2" /> + <strong>Click on individual rooms</strong> to see their stats! </div> - ); + ) : ( + <NewRoomConstructionContainer /> + )} + </div> + ); }; export default BuildingSidebarComponent; diff --git a/src/components/app/sidebars/topology/building/NewRoomConstructionComponent.js b/src/components/app/sidebars/topology/building/NewRoomConstructionComponent.js index d89b0ac0..a559c8dd 100644 --- a/src/components/app/sidebars/topology/building/NewRoomConstructionComponent.js +++ b/src/components/app/sidebars/topology/building/NewRoomConstructionComponent.js @@ -1,27 +1,31 @@ import React from "react"; -const NewRoomConstructionComponent = ({onStart, onFinish, onCancel, currentRoomInConstruction}) => { - if (currentRoomInConstruction === -1) { - return ( - <div className="btn btn-primary btn-block" onClick={onStart}> - <span className="fa fa-plus mr-2"/> - Construct a new room - </div> - ); - } +const NewRoomConstructionComponent = ({ + onStart, + onFinish, + onCancel, + currentRoomInConstruction +}) => { + if (currentRoomInConstruction === -1) { return ( - <div> - <div className="btn btn-primary btn-block" onClick={onFinish}> - <span className="fa fa-check mr-2"/> - Finalize new room - </div> - <div className="btn btn-default btn-block" onClick={onCancel}> - <span className="fa fa-times mr-2"/> - Cancel construction - </div> - </div> + <div className="btn btn-primary btn-block" onClick={onStart}> + <span className="fa fa-plus mr-2" /> + Construct a new room + </div> ); - + } + return ( + <div> + <div className="btn btn-primary btn-block" onClick={onFinish}> + <span className="fa fa-check mr-2" /> + Finalize new room + </div> + <div className="btn btn-default btn-block" onClick={onCancel}> + <span className="fa fa-times mr-2" /> + Cancel construction + </div> + </div> + ); }; export default NewRoomConstructionComponent; diff --git a/src/components/app/sidebars/topology/machine/BackToRackComponent.js b/src/components/app/sidebars/topology/machine/BackToRackComponent.js index 19e33904..7f56aca0 100644 --- a/src/components/app/sidebars/topology/machine/BackToRackComponent.js +++ b/src/components/app/sidebars/topology/machine/BackToRackComponent.js @@ -1,10 +1,10 @@ import React from "react"; -const BackToRackComponent = ({onClick}) => ( - <div className="btn btn-secondary btn-block" onClick={onClick}> - <span className="fa fa-angle-left mr-2"/> - Back to rack - </div> +const BackToRackComponent = ({ onClick }) => ( + <div className="btn btn-secondary btn-block" onClick={onClick}> + <span className="fa fa-angle-left mr-2" /> + Back to rack + </div> ); export default BackToRackComponent; diff --git a/src/components/app/sidebars/topology/machine/DeleteMachineComponent.js b/src/components/app/sidebars/topology/machine/DeleteMachineComponent.js index 7ba08352..8da39b30 100644 --- a/src/components/app/sidebars/topology/machine/DeleteMachineComponent.js +++ b/src/components/app/sidebars/topology/machine/DeleteMachineComponent.js @@ -1,10 +1,10 @@ import React from "react"; -const DeleteMachineComponent = ({onClick}) => ( - <div className="btn btn-danger btn-block" onClick={onClick}> - <span className="fa fa-trash mr-2"/> - Delete this machine - </div> +const DeleteMachineComponent = ({ onClick }) => ( + <div className="btn btn-danger btn-block" onClick={onClick}> + <span className="fa fa-trash mr-2" /> + Delete this machine + </div> ); export default DeleteMachineComponent; diff --git a/src/components/app/sidebars/topology/machine/MachineNameComponent.js b/src/components/app/sidebars/topology/machine/MachineNameComponent.js index 321e350d..0ad8b79c 100644 --- a/src/components/app/sidebars/topology/machine/MachineNameComponent.js +++ b/src/components/app/sidebars/topology/machine/MachineNameComponent.js @@ -1,7 +1,7 @@ import React from "react"; -const MachineNameComponent = ({position}) => ( - <h2>Machine at slot {position}</h2> +const MachineNameComponent = ({ position }) => ( + <h2>Machine at slot {position}</h2> ); export default MachineNameComponent; diff --git a/src/components/app/sidebars/topology/machine/MachineSidebarComponent.js b/src/components/app/sidebars/topology/machine/MachineSidebarComponent.js index cf4db80e..5ccaf25c 100644 --- a/src/components/app/sidebars/topology/machine/MachineSidebarComponent.js +++ b/src/components/app/sidebars/topology/machine/MachineSidebarComponent.js @@ -6,21 +6,22 @@ import DeleteMachineContainer from "../../../../../containers/app/sidebars/topol import MachineNameContainer from "../../../../../containers/app/sidebars/topology/machine/MachineNameContainer"; import UnitTabsContainer from "../../../../../containers/app/sidebars/topology/machine/UnitTabsContainer"; -const MachineSidebarComponent = ({inSimulation, machineId}) => { - return ( +const MachineSidebarComponent = ({ inSimulation, machineId }) => { + return ( + <div> + <MachineNameContainer /> + <BackToRackContainer /> + {inSimulation ? ( <div> - <MachineNameContainer/> - <BackToRackContainer/> - {inSimulation ? - <div> - <LoadBarContainer objectType="machine" objectId={machineId}/> - <LoadChartContainer objectType="machine" objectId={machineId}/> - </div> : - <DeleteMachineContainer/> - } - <UnitTabsContainer/> + <LoadBarContainer objectType="machine" objectId={machineId} /> + <LoadChartContainer objectType="machine" objectId={machineId} /> </div> - ); + ) : ( + <DeleteMachineContainer /> + )} + <UnitTabsContainer /> + </div> + ); }; export default MachineSidebarComponent; diff --git a/src/components/app/sidebars/topology/machine/UnitAddComponent.js b/src/components/app/sidebars/topology/machine/UnitAddComponent.js index f16700df..d0082a72 100644 --- a/src/components/app/sidebars/topology/machine/UnitAddComponent.js +++ b/src/components/app/sidebars/topology/machine/UnitAddComponent.js @@ -2,37 +2,44 @@ import PropTypes from "prop-types"; import React from "react"; class UnitAddComponent extends React.Component { - static propTypes = { - units: PropTypes.array.isRequired, - onAdd: PropTypes.func.isRequired, - }; + static propTypes = { + units: PropTypes.array.isRequired, + onAdd: PropTypes.func.isRequired + }; - render() { - return ( - <div className="form-inline"> - <div className="form-group w-100"> - <select - className="form-control w-75 mr-1" - ref={unitSelect => this.unitSelect = unitSelect} - > - {this.props.units.map(unit => ( - <option value={unit.id} key={unit.id}> - {unit.manufacturer + " " + unit.family + " " + unit.model + " " + unit.generation} - </option> - ))} - </select> - <button - type="submit" - className="btn btn-primary" - onClick={() => this.props.onAdd(parseInt(this.unitSelect.value, 10))} - > - <span className="fa fa-plus mr-2"/> - Add - </button> - </div> - </div> - ); - } + render() { + return ( + <div className="form-inline"> + <div className="form-group w-100"> + <select + className="form-control w-75 mr-1" + ref={unitSelect => (this.unitSelect = unitSelect)} + > + {this.props.units.map(unit => ( + <option value={unit.id} key={unit.id}> + {unit.manufacturer + + " " + + unit.family + + " " + + unit.model + + " " + + unit.generation} + </option> + ))} + </select> + <button + type="submit" + className="btn btn-primary" + onClick={() => + this.props.onAdd(parseInt(this.unitSelect.value, 10))} + > + <span className="fa fa-plus mr-2" /> + Add + </button> + </div> + </div> + ); + } } export default UnitAddComponent; diff --git a/src/components/app/sidebars/topology/machine/UnitComponent.js b/src/components/app/sidebars/topology/machine/UnitComponent.js index a0435eab..10a310e8 100644 --- a/src/components/app/sidebars/topology/machine/UnitComponent.js +++ b/src/components/app/sidebars/topology/machine/UnitComponent.js @@ -2,61 +2,79 @@ import React from "react"; import jQuery from "../../../../../util/jquery"; class UnitComponent extends React.Component { - componentDidMount() { - jQuery(".unit-info-popover").popover({ - trigger: "focus" - }); - } - - render() { - let unitInfo; - if (this.props.unitType === "cpu" || this.props.unitType === "gpu") { - unitInfo = ( - "<strong>Clockrate:</strong> <code>" + this.props.unit.clockRateMhz + " MHz</code><br/>" + - "<strong>Num. Cores:</strong> <code>" + this.props.unit.numberOfCores + "</code><br/>" + - "<strong>Energy Cons.:</strong> <code>" + this.props.unit.energyConsumptionW + " W</code>" - ); - } else if (this.props.unitType === "memory" || this.props.unitType === "storage") { - unitInfo = ( - "<strong>Speed:</strong> <code>" + this.props.unit.speedMbPerS + " Mb/s</code><br/>" + - "<strong>Size:</strong> <code>" + this.props.unit.sizeMb + " MB</code><br/>" + - "<strong>Energy Cons.:</strong> <code> " + this.props.unit.energyConsumptionW + " W</code>" - ); - } + componentDidMount() { + jQuery(".unit-info-popover").popover({ + trigger: "focus" + }); + } - return ( - <li className="d-flex list-group-item justify-content-between align-items-center"> - <span style={{maxWidth: "60%"}}> - { - this.props.unit.manufacturer - + " " + this.props.unit.family - + " " + this.props.unit.model - + " " + this.props.unit.generation - } - </span> - <span> - <a - tabIndex="0" - className="unit-info-popover btn btn-outline-info mr-1" - role="button" - data-toggle="popover" - data-trigger="focus" - title="Unit information" - data-content={unitInfo} - data-html="true" - > - <span className="fa fa-info-circle"/> - </a> - {this.props.inSimulation ? - undefined : - <span className="btn btn-outline-danger" onClick={this.props.onDelete}> - <span className="fa fa-trash"/> - </span> - } - </span> - </li> - ); + render() { + let unitInfo; + if (this.props.unitType === "cpu" || this.props.unitType === "gpu") { + unitInfo = + "<strong>Clockrate:</strong> <code>" + + this.props.unit.clockRateMhz + + " MHz</code><br/>" + + "<strong>Num. Cores:</strong> <code>" + + this.props.unit.numberOfCores + + "</code><br/>" + + "<strong>Energy Cons.:</strong> <code>" + + this.props.unit.energyConsumptionW + + " W</code>"; + } else if ( + this.props.unitType === "memory" || + this.props.unitType === "storage" + ) { + unitInfo = + "<strong>Speed:</strong> <code>" + + this.props.unit.speedMbPerS + + " Mb/s</code><br/>" + + "<strong>Size:</strong> <code>" + + this.props.unit.sizeMb + + " MB</code><br/>" + + "<strong>Energy Cons.:</strong> <code> " + + this.props.unit.energyConsumptionW + + " W</code>"; } + + return ( + <li className="d-flex list-group-item justify-content-between align-items-center"> + <span style={{ maxWidth: "60%" }}> + {this.props.unit.manufacturer + + " " + + this.props.unit.family + + " " + + this.props.unit.model + + " " + + this.props.unit.generation} + </span> + <span> + <a + tabIndex="0" + className="unit-info-popover btn btn-outline-info mr-1" + role="button" + data-toggle="popover" + data-trigger="focus" + title="Unit information" + data-content={unitInfo} + data-html="true" + > + <span className="fa fa-info-circle" /> + </a> + {this.props.inSimulation ? ( + undefined + ) : ( + <span + className="btn btn-outline-danger" + onClick={this.props.onDelete} + > + <span className="fa fa-trash" /> + </span> + )} + </span> + </li> + ); + } } export default UnitComponent; diff --git a/src/components/app/sidebars/topology/machine/UnitListComponent.js b/src/components/app/sidebars/topology/machine/UnitListComponent.js index 683f6023..38df806b 100644 --- a/src/components/app/sidebars/topology/machine/UnitListComponent.js +++ b/src/components/app/sidebars/topology/machine/UnitListComponent.js @@ -1,20 +1,29 @@ import React from "react"; import UnitContainer from "../../../../../containers/app/sidebars/topology/machine/UnitContainer"; -const UnitListComponent = ({unitType, unitIds, inSimulation}) => ( - <ul className="list-group mt-1"> - {unitIds.length !== 0 ? - unitIds.map((unitId, index) => ( - <UnitContainer unitType={unitType} unitId={unitId} index={index} key={index}/> - )) : - <div className="alert alert-info"> - {inSimulation ? - <strong>No units of this type in this machine</strong> : - <span><strong>No units...</strong> Add some with the menu above!</span> - } - </div> - } - </ul> +const UnitListComponent = ({ unitType, unitIds, inSimulation }) => ( + <ul className="list-group mt-1"> + {unitIds.length !== 0 ? ( + unitIds.map((unitId, index) => ( + <UnitContainer + unitType={unitType} + unitId={unitId} + index={index} + key={index} + /> + )) + ) : ( + <div className="alert alert-info"> + {inSimulation ? ( + <strong>No units of this type in this machine</strong> + ) : ( + <span> + <strong>No units...</strong> Add some with the menu above! + </span> + )} + </div> + )} + </ul> ); export default UnitListComponent; diff --git a/src/components/app/sidebars/topology/machine/UnitTabsComponent.js b/src/components/app/sidebars/topology/machine/UnitTabsComponent.js index 2113d6d8..0683c796 100644 --- a/src/components/app/sidebars/topology/machine/UnitTabsComponent.js +++ b/src/components/app/sidebars/topology/machine/UnitTabsComponent.js @@ -2,53 +2,64 @@ import React from "react"; import UnitAddContainer from "../../../../../containers/app/sidebars/topology/machine/UnitAddContainer"; import UnitListContainer from "../../../../../containers/app/sidebars/topology/machine/UnitListContainer"; -const UnitTabsComponent = ({inSimulation}) => ( - <div> - <ul className="nav nav-tabs mt-2 mb-1" role="tablist"> - <li className="nav-item"> - <a className="nav-link active" data-toggle="tab" href="#cpu-units" role="tab">CPU</a> - </li> - <li className="nav-item"> - <a className="nav-link" data-toggle="tab" href="#gpu-units" role="tab">GPU</a> - </li> - <li className="nav-item"> - <a className="nav-link" data-toggle="tab" href="#memory-units" role="tab">Memory</a> - </li> - <li className="nav-item"> - <a className="nav-link" data-toggle="tab" href="#storage-units" role="tab">Storage</a> - </li> - </ul> - <div className="tab-content"> - <div className="tab-pane active" id="cpu-units" role="tabpanel"> - {inSimulation ? - undefined : - <UnitAddContainer unitType="cpu"/> - } - <UnitListContainer unitType="cpu"/> - </div> - <div className="tab-pane" id="gpu-units" role="tabpanel"> - {inSimulation ? - undefined : - <UnitAddContainer unitType="gpu"/> - } - <UnitListContainer unitType="gpu"/> - </div> - <div className="tab-pane" id="memory-units" role="tabpanel"> - {inSimulation ? - undefined : - <UnitAddContainer unitType="memory"/> - } - <UnitListContainer unitType="memory"/> - </div> - <div className="tab-pane" id="storage-units" role="tabpanel"> - {inSimulation ? - undefined : - <UnitAddContainer unitType="storage"/> - } - <UnitListContainer unitType="storage"/> - </div> - </div> +const UnitTabsComponent = ({ inSimulation }) => ( + <div> + <ul className="nav nav-tabs mt-2 mb-1" role="tablist"> + <li className="nav-item"> + <a + className="nav-link active" + data-toggle="tab" + href="#cpu-units" + role="tab" + > + CPU + </a> + </li> + <li className="nav-item"> + <a className="nav-link" data-toggle="tab" href="#gpu-units" role="tab"> + GPU + </a> + </li> + <li className="nav-item"> + <a + className="nav-link" + data-toggle="tab" + href="#memory-units" + role="tab" + > + Memory + </a> + </li> + <li className="nav-item"> + <a + className="nav-link" + data-toggle="tab" + href="#storage-units" + role="tab" + > + Storage + </a> + </li> + </ul> + <div className="tab-content"> + <div className="tab-pane active" id="cpu-units" role="tabpanel"> + {inSimulation ? undefined : <UnitAddContainer unitType="cpu" />} + <UnitListContainer unitType="cpu" /> + </div> + <div className="tab-pane" id="gpu-units" role="tabpanel"> + {inSimulation ? undefined : <UnitAddContainer unitType="gpu" />} + <UnitListContainer unitType="gpu" /> + </div> + <div className="tab-pane" id="memory-units" role="tabpanel"> + {inSimulation ? undefined : <UnitAddContainer unitType="memory" />} + <UnitListContainer unitType="memory" /> + </div> + <div className="tab-pane" id="storage-units" role="tabpanel"> + {inSimulation ? undefined : <UnitAddContainer unitType="storage" />} + <UnitListContainer unitType="storage" /> + </div> </div> + </div> ); export default UnitTabsComponent; diff --git a/src/components/app/sidebars/topology/rack/BackToRoomComponent.js b/src/components/app/sidebars/topology/rack/BackToRoomComponent.js index 267001c6..6bcf4088 100644 --- a/src/components/app/sidebars/topology/rack/BackToRoomComponent.js +++ b/src/components/app/sidebars/topology/rack/BackToRoomComponent.js @@ -1,10 +1,10 @@ import React from "react"; -const BackToRoomComponent = ({onClick}) => ( - <div className="btn btn-secondary btn-block mb-2" onClick={onClick}> - <span className="fa fa-angle-left mr-2"/> - Back to room - </div> +const BackToRoomComponent = ({ onClick }) => ( + <div className="btn btn-secondary btn-block mb-2" onClick={onClick}> + <span className="fa fa-angle-left mr-2" /> + Back to room + </div> ); export default BackToRoomComponent; diff --git a/src/components/app/sidebars/topology/rack/DeleteRackComponent.js b/src/components/app/sidebars/topology/rack/DeleteRackComponent.js index b268bd72..f0bad0ed 100644 --- a/src/components/app/sidebars/topology/rack/DeleteRackComponent.js +++ b/src/components/app/sidebars/topology/rack/DeleteRackComponent.js @@ -1,10 +1,10 @@ import React from "react"; -const DeleteRackComponent = ({onClick}) => ( - <div className="btn btn-danger btn-block" onClick={onClick}> - <span className="fa fa-trash mr-2"/> - Delete this rack - </div> +const DeleteRackComponent = ({ onClick }) => ( + <div className="btn btn-danger btn-block" onClick={onClick}> + <span className="fa fa-trash mr-2" /> + Delete this rack + </div> ); export default DeleteRackComponent; diff --git a/src/components/app/sidebars/topology/rack/EmptySlotComponent.js b/src/components/app/sidebars/topology/rack/EmptySlotComponent.js index 08665072..d86f9fee 100644 --- a/src/components/app/sidebars/topology/rack/EmptySlotComponent.js +++ b/src/components/app/sidebars/topology/rack/EmptySlotComponent.js @@ -1,20 +1,19 @@ import React from "react"; -const EmptySlotComponent = ({position, onAdd, inSimulation}) => ( - <li className="list-group-item d-flex justify-content-between align-items-center"> - <span className="badge badge-default badge-info mr-1 disabled"> - {position} - </span> - {inSimulation ? - <span className="badge badge-default badge-success"> - Empty Slot - </span> : - <button className="btn btn-outline-primary" onClick={onAdd}> - <span className="fa fa-plus mr-2"/> - Add machine - </button> - } - </li> +const EmptySlotComponent = ({ position, onAdd, inSimulation }) => ( + <li className="list-group-item d-flex justify-content-between align-items-center"> + <span className="badge badge-default badge-info mr-1 disabled"> + {position} + </span> + {inSimulation ? ( + <span className="badge badge-default badge-success">Empty Slot</span> + ) : ( + <button className="btn btn-outline-primary" onClick={onAdd}> + <span className="fa fa-plus mr-2" /> + Add machine + </button> + )} + </li> ); export default EmptySlotComponent; diff --git a/src/components/app/sidebars/topology/rack/MachineComponent.js b/src/components/app/sidebars/topology/rack/MachineComponent.js index 0ba4503d..2521f4a2 100644 --- a/src/components/app/sidebars/topology/rack/MachineComponent.js +++ b/src/components/app/sidebars/topology/rack/MachineComponent.js @@ -1,65 +1,78 @@ import React from "react"; import Shapes from "../../../../../shapes"; -import {convertLoadToSimulationColor} from "../../../../../util/simulation-load"; +import { convertLoadToSimulationColor } from "../../../../../util/simulation-load"; -const UnitIcon = ({id, type}) => ( - <div> - <img - src={"/img/topology/" + id + "-icon.png"} - alt={"Machine contains " + type + " units"} - className="img-fluid ml-1" - style={{maxHeight: "35px"}} - /> - </div> +const UnitIcon = ({ id, type }) => ( + <div> + <img + src={"/img/topology/" + id + "-icon.png"} + alt={"Machine contains " + type + " units"} + className="img-fluid ml-1" + style={{ maxHeight: "35px" }} + /> + </div> ); -const MachineComponent = ({position, machine, inSimulation, machineLoad, onClick}) => { - let color = "white"; - if (inSimulation && machineLoad >= 0) { - color = convertLoadToSimulationColor(machineLoad); - } - const hasNoUnits = machine.cpuIds.length + machine.gpuIds.length + machine.memoryIds.length - + machine.storageIds.length === 0; +const MachineComponent = ({ + position, + machine, + inSimulation, + machineLoad, + onClick +}) => { + let color = "white"; + if (inSimulation && machineLoad >= 0) { + color = convertLoadToSimulationColor(machineLoad); + } + const hasNoUnits = + machine.cpuIds.length + + machine.gpuIds.length + + machine.memoryIds.length + + machine.storageIds.length === + 0; - return ( - <li - className="d-flex list-group-item list-group-item-action justify-content-between align-items-center" - onClick={onClick} - style={{backgroundColor: color}} - > - <span className="badge badge-default badge-info mr-1"> - {position} - </span> - <div className="d-inline-flex"> - {machine.cpuIds.length > 0 ? - <UnitIcon id="cpu" type="CPU"/> : - undefined - } - {machine.gpuIds.length > 0 ? - <UnitIcon id="gpu" type="GPU"/> : - undefined - } - {machine.memoryIds.length > 0 ? - <UnitIcon id="memory" type="memory"/> : - undefined - } - {machine.storageIds.length > 0 ? - <UnitIcon id="storage" type="storage"/> : - undefined - } - {hasNoUnits ? - <span className="badge badge-default badge-warning"> - Machine with no units - </span> : - undefined - } - </div> - </li> - ); + return ( + <li + className="d-flex list-group-item list-group-item-action justify-content-between align-items-center" + onClick={onClick} + style={{ backgroundColor: color }} + > + <span className="badge badge-default badge-info mr-1">{position}</span> + <div className="d-inline-flex"> + {machine.cpuIds.length > 0 ? ( + <UnitIcon id="cpu" type="CPU" /> + ) : ( + undefined + )} + {machine.gpuIds.length > 0 ? ( + <UnitIcon id="gpu" type="GPU" /> + ) : ( + undefined + )} + {machine.memoryIds.length > 0 ? ( + <UnitIcon id="memory" type="memory" /> + ) : ( + undefined + )} + {machine.storageIds.length > 0 ? ( + <UnitIcon id="storage" type="storage" /> + ) : ( + undefined + )} + {hasNoUnits ? ( + <span className="badge badge-default badge-warning"> + Machine with no units + </span> + ) : ( + undefined + )} + </div> + </li> + ); }; MachineComponent.propTypes = { - machine: Shapes.Machine + machine: Shapes.Machine }; export default MachineComponent; diff --git a/src/components/app/sidebars/topology/rack/MachineListComponent.js b/src/components/app/sidebars/topology/rack/MachineListComponent.js index fcb90d66..d5521557 100644 --- a/src/components/app/sidebars/topology/rack/MachineListComponent.js +++ b/src/components/app/sidebars/topology/rack/MachineListComponent.js @@ -3,18 +3,24 @@ import EmptySlotContainer from "../../../../../containers/app/sidebars/topology/ import MachineContainer from "../../../../../containers/app/sidebars/topology/rack/MachineContainer"; import "./MachineListComponent.css"; -const MachineListComponent = ({machineIds}) => { - return ( - <ul className="list-group machine-list"> - {machineIds.map((machineId, index) => { - if (machineId === null) { - return <EmptySlotContainer key={index} position={index + 1}/>; - } else { - return <MachineContainer key={index} position={index + 1} machineId={machineId}/>; - } - })} - </ul> - ); +const MachineListComponent = ({ machineIds }) => { + return ( + <ul className="list-group machine-list"> + {machineIds.map((machineId, index) => { + if (machineId === null) { + return <EmptySlotContainer key={index} position={index + 1} />; + } else { + return ( + <MachineContainer + key={index} + position={index + 1} + machineId={machineId} + /> + ); + } + })} + </ul> + ); }; export default MachineListComponent; diff --git a/src/components/app/sidebars/topology/rack/RackNameComponent.js b/src/components/app/sidebars/topology/rack/RackNameComponent.js index ee8d194b..5e095823 100644 --- a/src/components/app/sidebars/topology/rack/RackNameComponent.js +++ b/src/components/app/sidebars/topology/rack/RackNameComponent.js @@ -1,8 +1,8 @@ import React from "react"; import NameComponent from "../NameComponent"; -const RackNameComponent = ({rackName, onEdit}) => ( - <NameComponent name={rackName} onEdit={onEdit}/> +const RackNameComponent = ({ rackName, onEdit }) => ( + <NameComponent name={rackName} onEdit={onEdit} /> ); export default RackNameComponent; diff --git a/src/components/app/sidebars/topology/rack/RackSidebarComponent.js b/src/components/app/sidebars/topology/rack/RackSidebarComponent.js index f563a52f..f832b9b9 100644 --- a/src/components/app/sidebars/topology/rack/RackSidebarComponent.js +++ b/src/components/app/sidebars/topology/rack/RackSidebarComponent.js @@ -7,27 +7,28 @@ import MachineListContainer from "../../../../../containers/app/sidebars/topolog import RackNameContainer from "../../../../../containers/app/sidebars/topology/rack/RackNameContainer"; import "./RackSidebarComponent.css"; -const RackSidebarComponent = ({inSimulation, rackId}) => { - return ( - <div className="rack-sidebar-container flex-column"> - <div className="rack-sidebar-header-container"> - <RackNameContainer/> - <BackToRoomContainer/> - {inSimulation ? - <div> - <LoadBarContainer objectType="rack" objectId={rackId}/> - <LoadChartContainer objectType="rack" objectId={rackId}/> - </div> : - <div> - <DeleteRackContainer/> - </div> - } - </div> - <div className="machine-list-container mt-2"> - <MachineListContainer/> - </div> - </div> - ); +const RackSidebarComponent = ({ inSimulation, rackId }) => { + return ( + <div className="rack-sidebar-container flex-column"> + <div className="rack-sidebar-header-container"> + <RackNameContainer /> + <BackToRoomContainer /> + {inSimulation ? ( + <div> + <LoadBarContainer objectType="rack" objectId={rackId} /> + <LoadChartContainer objectType="rack" objectId={rackId} /> + </div> + ) : ( + <div> + <DeleteRackContainer /> + </div> + )} + </div> + <div className="machine-list-container mt-2"> + <MachineListContainer /> + </div> + </div> + ); }; export default RackSidebarComponent; diff --git a/src/components/app/sidebars/topology/room/BackToBuildingComponent.js b/src/components/app/sidebars/topology/room/BackToBuildingComponent.js index 81384ba5..0409dbdd 100644 --- a/src/components/app/sidebars/topology/room/BackToBuildingComponent.js +++ b/src/components/app/sidebars/topology/room/BackToBuildingComponent.js @@ -1,10 +1,10 @@ import React from "react"; -const BackToBuildingComponent = ({onClick}) => ( - <div className="btn btn-secondary btn-block mb-2" onClick={onClick}> - <span className="fa fa-angle-left mr-2"/> - Back to building - </div> +const BackToBuildingComponent = ({ onClick }) => ( + <div className="btn btn-secondary btn-block mb-2" onClick={onClick}> + <span className="fa fa-angle-left mr-2" /> + Back to building + </div> ); export default BackToBuildingComponent; diff --git a/src/components/app/sidebars/topology/room/DeleteRoomComponent.js b/src/components/app/sidebars/topology/room/DeleteRoomComponent.js index 3f41eac0..5df484b5 100644 --- a/src/components/app/sidebars/topology/room/DeleteRoomComponent.js +++ b/src/components/app/sidebars/topology/room/DeleteRoomComponent.js @@ -1,10 +1,10 @@ import React from "react"; -const DeleteRoomComponent = ({onClick}) => ( - <div className="btn btn-danger btn-block" onClick={onClick}> - <span className="fa fa-trash mr-2"/> - Delete this room - </div> +const DeleteRoomComponent = ({ onClick }) => ( + <div className="btn btn-danger btn-block" onClick={onClick}> + <span className="fa fa-trash mr-2" /> + Delete this room + </div> ); export default DeleteRoomComponent; diff --git a/src/components/app/sidebars/topology/room/RackConstructionComponent.js b/src/components/app/sidebars/topology/room/RackConstructionComponent.js index 9bfe28ce..0982e403 100644 --- a/src/components/app/sidebars/topology/room/RackConstructionComponent.js +++ b/src/components/app/sidebars/topology/room/RackConstructionComponent.js @@ -1,21 +1,25 @@ import React from "react"; -const RackConstructionComponent = ({inRackConstructionMode, onStart, onStop}) => { - if (inRackConstructionMode) { - return ( - <div className="btn btn-primary btn-block" onClick={onStop}> - <span className="fa fa-times mr-2"/> - Stop rack construction - </div> - ); - } - +const RackConstructionComponent = ({ + inRackConstructionMode, + onStart, + onStop +}) => { + if (inRackConstructionMode) { return ( - <div className="btn btn-primary btn-block" onClick={onStart}> - <span className="fa fa-plus mr-2"/> - Start rack construction - </div> + <div className="btn btn-primary btn-block" onClick={onStop}> + <span className="fa fa-times mr-2" /> + Stop rack construction + </div> ); + } + + return ( + <div className="btn btn-primary btn-block" onClick={onStart}> + <span className="fa fa-plus mr-2" /> + Start rack construction + </div> + ); }; export default RackConstructionComponent; diff --git a/src/components/app/sidebars/topology/room/RoomNameComponent.js b/src/components/app/sidebars/topology/room/RoomNameComponent.js index 4d3e41cc..11b88edd 100644 --- a/src/components/app/sidebars/topology/room/RoomNameComponent.js +++ b/src/components/app/sidebars/topology/room/RoomNameComponent.js @@ -1,8 +1,8 @@ import React from "react"; import NameComponent from "../NameComponent"; -const RoomNameComponent = ({roomName, onEdit}) => ( - <NameComponent name={roomName} onEdit={onEdit}/> +const RoomNameComponent = ({ roomName, onEdit }) => ( + <NameComponent name={roomName} onEdit={onEdit} /> ); export default RoomNameComponent; diff --git a/src/components/app/sidebars/topology/room/RoomSidebarComponent.js b/src/components/app/sidebars/topology/room/RoomSidebarComponent.js index 53857408..727c3f43 100644 --- a/src/components/app/sidebars/topology/room/RoomSidebarComponent.js +++ b/src/components/app/sidebars/topology/room/RoomSidebarComponent.js @@ -7,29 +7,30 @@ import RackConstructionContainer from "../../../../../containers/app/sidebars/to import RoomNameContainer from "../../../../../containers/app/sidebars/topology/room/RoomNameContainer"; import RoomTypeContainer from "../../../../../containers/app/sidebars/topology/room/RoomTypeContainer"; -const RoomSidebarComponent = ({roomId, roomType, inSimulation}) => { - let allowedObjects; - if (!inSimulation && roomType === "SERVER") { - allowedObjects = <RackConstructionContainer/>; - } +const RoomSidebarComponent = ({ roomId, roomType, inSimulation }) => { + let allowedObjects; + if (!inSimulation && roomType === "SERVER") { + allowedObjects = <RackConstructionContainer />; + } - return ( + return ( + <div> + <RoomNameContainer /> + <RoomTypeContainer /> + <BackToBuildingContainer /> + {inSimulation ? ( <div> - <RoomNameContainer/> - <RoomTypeContainer/> - <BackToBuildingContainer/> - {inSimulation ? - <div> - <LoadBarContainer objectType="room" objectId={roomId}/> - <LoadChartContainer objectType="room" objectId={roomId}/> - </div> : - <div> - {allowedObjects} - <DeleteRoomContainer/> - </div> - } + <LoadBarContainer objectType="room" objectId={roomId} /> + <LoadChartContainer objectType="room" objectId={roomId} /> </div> - ); + ) : ( + <div> + {allowedObjects} + <DeleteRoomContainer /> + </div> + )} + </div> + ); }; export default RoomSidebarComponent; diff --git a/src/components/app/sidebars/topology/room/RoomTypeComponent.js b/src/components/app/sidebars/topology/room/RoomTypeComponent.js index d42eefb6..46d91c2c 100644 --- a/src/components/app/sidebars/topology/room/RoomTypeComponent.js +++ b/src/components/app/sidebars/topology/room/RoomTypeComponent.js @@ -1,10 +1,8 @@ import React from "react"; -import {ROOM_TYPE_TO_NAME_MAP} from "../../../../../util/room-types"; +import { ROOM_TYPE_TO_NAME_MAP } from "../../../../../util/room-types"; -const RoomTypeComponent = ({roomType}) => ( - <p className="lead"> - {ROOM_TYPE_TO_NAME_MAP[roomType]} - </p> +const RoomTypeComponent = ({ roomType }) => ( + <p className="lead">{ROOM_TYPE_TO_NAME_MAP[roomType]}</p> ); export default RoomTypeComponent; diff --git a/src/components/app/timeline/PlayButtonComponent.js b/src/components/app/timeline/PlayButtonComponent.js index 2b8e5328..1a9b0ced 100644 --- a/src/components/app/timeline/PlayButtonComponent.js +++ b/src/components/app/timeline/PlayButtonComponent.js @@ -1,20 +1,30 @@ import React from "react"; -const PlayButtonComponent = ({isPlaying, currentTick, lastSimulatedTick, onPlay, onPause}) => ( - <div className="play-btn" onClick={() => { - if (isPlaying) { - onPause(); - } else { - if (currentTick !== lastSimulatedTick) { - onPlay(); - } +const PlayButtonComponent = ({ + isPlaying, + currentTick, + lastSimulatedTick, + onPlay, + onPause +}) => ( + <div + className="play-btn" + onClick={() => { + if (isPlaying) { + onPause(); + } else { + if (currentTick !== lastSimulatedTick) { + onPlay(); } - }}> - {isPlaying ? - <span className="fa fa-pause"/> : - <span className="fa fa-play"/> - } - </div> + } + }} + > + {isPlaying ? ( + <span className="fa fa-pause" /> + ) : ( + <span className="fa fa-play" /> + )} + </div> ); export default PlayButtonComponent; diff --git a/src/components/app/timeline/TimelineComponent.js b/src/components/app/timeline/TimelineComponent.js index 950a25bd..0f88b8f4 100644 --- a/src/components/app/timeline/TimelineComponent.js +++ b/src/components/app/timeline/TimelineComponent.js @@ -4,34 +4,34 @@ import TimelineLabelsContainer from "../../../containers/app/timeline/TimelineLa import "./Timeline.css"; class TimelineComponent extends React.Component { - componentDidMount() { - this.interval = setInterval(() => { - if (!this.props.isPlaying) { - return; - } + componentDidMount() { + this.interval = setInterval(() => { + if (!this.props.isPlaying) { + return; + } - if (this.props.currentTick < this.props.lastSimulatedTick) { - this.props.incrementTick(); - } else { - this.props.pauseSimulation(); - } - }, 1000); - } + if (this.props.currentTick < this.props.lastSimulatedTick) { + this.props.incrementTick(); + } else { + this.props.pauseSimulation(); + } + }, 1000); + } - componentWillUnmount() { - clearInterval(this.interval); - } + componentWillUnmount() { + clearInterval(this.interval); + } - render() { - return ( - <div className="timeline-bar"> - <div className="timeline-container"> - <TimelineLabelsContainer/> - <TimelineControlsContainer/> - </div> - </div> - ); - } + render() { + return ( + <div className="timeline-bar"> + <div className="timeline-container"> + <TimelineLabelsContainer /> + <TimelineControlsContainer /> + </div> + </div> + ); + } } export default TimelineComponent; diff --git a/src/components/app/timeline/TimelineControlsComponent.js b/src/components/app/timeline/TimelineControlsComponent.js index 72fc4a60..f3d55154 100644 --- a/src/components/app/timeline/TimelineControlsComponent.js +++ b/src/components/app/timeline/TimelineControlsComponent.js @@ -1,39 +1,49 @@ import React from "react"; import PlayButtonContainer from "../../../containers/app/timeline/PlayButtonContainer"; -import {convertTickToPercentage} from "../../../util/timeline"; +import { convertTickToPercentage } from "../../../util/timeline"; class TimelineControlsComponent extends React.Component { - onTimelineClick(e) { - const percentage = e.nativeEvent.offsetX / this.timeline.clientWidth; - const tick = Math.floor(percentage * (this.props.lastSimulatedTick + 1)); - this.props.goToTick(tick); - } + onTimelineClick(e) { + const percentage = e.nativeEvent.offsetX / this.timeline.clientWidth; + const tick = Math.floor(percentage * (this.props.lastSimulatedTick + 1)); + this.props.goToTick(tick); + } - render() { - return ( - <div className="timeline-controls"> - <PlayButtonContainer/> - <div - className="timeline" - ref={timeline => this.timeline = timeline} - onClick={this.onTimelineClick.bind(this)} - > - <div - className="time-marker" - style={{left: convertTickToPercentage(this.props.currentTick, this.props.lastSimulatedTick)}} - /> - {this.props.sectionTicks.map(sectionTick => ( - <div - key={sectionTick} - className="section-marker" - style={{left: convertTickToPercentage(sectionTick, this.props.lastSimulatedTick)}} - title="Topology changes at this tick" - /> - ))} - </div> - </div> - ); - } + render() { + return ( + <div className="timeline-controls"> + <PlayButtonContainer /> + <div + className="timeline" + ref={timeline => (this.timeline = timeline)} + onClick={this.onTimelineClick.bind(this)} + > + <div + className="time-marker" + style={{ + left: convertTickToPercentage( + this.props.currentTick, + this.props.lastSimulatedTick + ) + }} + /> + {this.props.sectionTicks.map(sectionTick => ( + <div + key={sectionTick} + className="section-marker" + style={{ + left: convertTickToPercentage( + sectionTick, + this.props.lastSimulatedTick + ) + }} + title="Topology changes at this tick" + /> + ))} + </div> + </div> + ); + } } export default TimelineControlsComponent; diff --git a/src/components/app/timeline/TimelineLabelsComponent.js b/src/components/app/timeline/TimelineLabelsComponent.js index e795691f..6943a86f 100644 --- a/src/components/app/timeline/TimelineLabelsComponent.js +++ b/src/components/app/timeline/TimelineLabelsComponent.js @@ -1,11 +1,15 @@ import React from "react"; -import {convertSecondsToFormattedTime} from "../../../util/date-time"; +import { convertSecondsToFormattedTime } from "../../../util/date-time"; -const TimelineLabelsComponent = ({currentTick, lastSimulatedTick}) => ( - <div className="timeline-labels"> - <div className="start-time-label">{convertSecondsToFormattedTime(currentTick)}</div> - <div className="end-time-label">{convertSecondsToFormattedTime(lastSimulatedTick)}</div> +const TimelineLabelsComponent = ({ currentTick, lastSimulatedTick }) => ( + <div className="timeline-labels"> + <div className="start-time-label"> + {convertSecondsToFormattedTime(currentTick)} </div> + <div className="end-time-label"> + {convertSecondsToFormattedTime(lastSimulatedTick)} + </div> + </div> ); export default TimelineLabelsComponent; diff --git a/src/components/experiments/ExperimentListComponent.js b/src/components/experiments/ExperimentListComponent.js index f315ebbf..28c06f29 100644 --- a/src/components/experiments/ExperimentListComponent.js +++ b/src/components/experiments/ExperimentListComponent.js @@ -2,37 +2,42 @@ import PropTypes from "prop-types"; import React from "react"; import ExperimentRowContainer from "../../containers/experiments/ExperimentRowContainer"; -const ExperimentListComponent = ({experimentIds}) => { - return ( - <div className="vertically-expanding-container"> - {experimentIds.length === 0 ? - <div className="alert alert-info"> - <span className="info-icon fa fa-question-circle mr-2"/> - <strong>No experiments here yet...</strong> Add some with the button below! - </div> : - <table className="table table-striped"> - <thead> - <tr> - <th>Name</th> - <th>Path</th> - <th>Trace</th> - <th>Scheduler</th> - <th/> - </tr> - </thead> - <tbody> - {experimentIds.map(experimentId => ( - <ExperimentRowContainer experimentId={experimentId} key={experimentId}/> - ))} - </tbody> - </table> - } +const ExperimentListComponent = ({ experimentIds }) => { + return ( + <div className="vertically-expanding-container"> + {experimentIds.length === 0 ? ( + <div className="alert alert-info"> + <span className="info-icon fa fa-question-circle mr-2" /> + <strong>No experiments here yet...</strong> Add some with the button + below! </div> - ); + ) : ( + <table className="table table-striped"> + <thead> + <tr> + <th>Name</th> + <th>Path</th> + <th>Trace</th> + <th>Scheduler</th> + <th /> + </tr> + </thead> + <tbody> + {experimentIds.map(experimentId => ( + <ExperimentRowContainer + experimentId={experimentId} + key={experimentId} + /> + ))} + </tbody> + </table> + )} + </div> + ); }; ExperimentListComponent.propTypes = { - experimentIds: PropTypes.arrayOf(PropTypes.number).isRequired, + experimentIds: PropTypes.arrayOf(PropTypes.number).isRequired }; export default ExperimentListComponent; diff --git a/src/components/experiments/ExperimentRowComponent.js b/src/components/experiments/ExperimentRowComponent.js index eb9cbacf..e71c6a00 100644 --- a/src/components/experiments/ExperimentRowComponent.js +++ b/src/components/experiments/ExperimentRowComponent.js @@ -1,44 +1,40 @@ import PropTypes from "prop-types"; import React from "react"; -import {Link} from "react-router-dom"; +import { Link } from "react-router-dom"; import Shapes from "../../shapes/index"; -const ExperimentRowComponent = ({experiment, simulationId, onDelete}) => ( - <tr> - <td className="pt-3"> - {experiment.name} - </td> - <td className="pt-3"> - {experiment.path.name ? experiment.path.name : "Path " + experiment.path.id} - </td> - <td className="pt-3"> - {experiment.trace.name} - </td> - <td className="pt-3"> - {experiment.scheduler.name} - </td> - <td className="text-right"> - <Link - to={"/simulations/" + simulationId + "/experiments/" + experiment.id} - className="btn btn-outline-primary btn-sm mr-2" - title="Open this experiment" - > - <span className="fa fa-play"/> - </Link> - <div - className="btn btn-outline-danger btn-sm" - title="Delete this experiment" - onClick={() => onDelete(experiment.id)} - > - <span className="fa fa-trash"/> - </div> - </td> - </tr> +const ExperimentRowComponent = ({ experiment, simulationId, onDelete }) => ( + <tr> + <td className="pt-3">{experiment.name}</td> + <td className="pt-3"> + {experiment.path.name + ? experiment.path.name + : "Path " + experiment.path.id} + </td> + <td className="pt-3">{experiment.trace.name}</td> + <td className="pt-3">{experiment.scheduler.name}</td> + <td className="text-right"> + <Link + to={"/simulations/" + simulationId + "/experiments/" + experiment.id} + className="btn btn-outline-primary btn-sm mr-2" + title="Open this experiment" + > + <span className="fa fa-play" /> + </Link> + <div + className="btn btn-outline-danger btn-sm" + title="Delete this experiment" + onClick={() => onDelete(experiment.id)} + > + <span className="fa fa-trash" /> + </div> + </td> + </tr> ); ExperimentRowComponent.propTypes = { - experiment: Shapes.Experiment.isRequired, - simulationId: PropTypes.number.isRequired, + experiment: Shapes.Experiment.isRequired, + simulationId: PropTypes.number.isRequired }; export default ExperimentRowComponent; diff --git a/src/components/experiments/NewExperimentButtonComponent.js b/src/components/experiments/NewExperimentButtonComponent.js index 559a7218..651172e3 100644 --- a/src/components/experiments/NewExperimentButtonComponent.js +++ b/src/components/experiments/NewExperimentButtonComponent.js @@ -1,17 +1,17 @@ -import PropTypes from 'prop-types'; -import React from 'react'; +import PropTypes from "prop-types"; +import React from "react"; -const NewExperimentButtonComponent = ({onClick}) => ( - <div className="bottom-btn-container"> - <div className="btn btn-primary float-right" onClick={onClick}> - <span className="fa fa-plus mr-2"/> - New Experiment - </div> +const NewExperimentButtonComponent = ({ onClick }) => ( + <div className="bottom-btn-container"> + <div className="btn btn-primary float-right" onClick={onClick}> + <span className="fa fa-plus mr-2" /> + New Experiment </div> + </div> ); NewExperimentButtonComponent.propTypes = { - onClick: PropTypes.func.isRequired, + onClick: PropTypes.func.isRequired }; export default NewExperimentButtonComponent; diff --git a/src/components/home/ContactSection.js b/src/components/home/ContactSection.js index fd65b31c..d957297a 100644 --- a/src/components/home/ContactSection.js +++ b/src/components/home/ContactSection.js @@ -5,48 +5,61 @@ import "./ContactSection.css"; import ContentSection from "./ContentSection"; const ContactSection = () => ( - <ContentSection name="contact" title="Contact"> - <div className="row justify-content-center"> - <div className="col-4"> - <a href="https://github.com/atlarge-research/opendc"> - <FontAwesome name="github" size="3x" className="mb-2"/> - <div className="w-100"/> - atlarge-research/opendc - </a> - </div> - <div className="col-4"> - <Mailto title="Contact us" email="opendc@atlarge-research.com"> - <FontAwesome name="envelope" size="3x" className="mb-2"/> - <div className="w-100"/> - opendc@atlarge-research.com - </Mailto> - </div> - </div> - <div className="row"> - <div className="col text-center"> - <img src="img/tudelft-icon.png" className="img-fluid tudelft-icon" alt="TU Delft"/> - </div> - </div> - <div className="row"> - <div className="col text-center"> - A project by the - <a href="http://atlarge.science" target="_blank" rel="noopener noreferrer"> - <strong>@Large Research Group</strong> - </a>. - </div> - </div> - <div className="row"> - <div className="col text-center disclaimer mt-5 small"> - <FontAwesome name="exclamation-triangle" size="2x" className="mr-2"/> - <br/> - OpenDC is an experimental tool. Your data may get lost, overwritten, or otherwise become unavailable. - <br/> - The OpenDC authors should in no way be liable in the event this happens (see our <strong><a - href="https://github.com/atlarge-research/opendc/blob/master/LICENSE.md">license</a></strong>). Sorry - for the inconvenience. - </div> - </div> - </ContentSection> + <ContentSection name="contact" title="Contact"> + <div className="row justify-content-center"> + <div className="col-4"> + <a href="https://github.com/atlarge-research/opendc"> + <FontAwesome name="github" size="3x" className="mb-2" /> + <div className="w-100" /> + atlarge-research/opendc + </a> + </div> + <div className="col-4"> + <Mailto title="Contact us" email="opendc@atlarge-research.com"> + <FontAwesome name="envelope" size="3x" className="mb-2" /> + <div className="w-100" /> + opendc@atlarge-research.com + </Mailto> + </div> + </div> + <div className="row"> + <div className="col text-center"> + <img + src="img/tudelft-icon.png" + className="img-fluid tudelft-icon" + alt="TU Delft" + /> + </div> + </div> + <div className="row"> + <div className="col text-center"> + A project by the + <a + href="http://atlarge.science" + target="_blank" + rel="noopener noreferrer" + > + <strong>@Large Research Group</strong> + </a>. + </div> + </div> + <div className="row"> + <div className="col text-center disclaimer mt-5 small"> + <FontAwesome name="exclamation-triangle" size="2x" className="mr-2" /> + <br /> + OpenDC is an experimental tool. Your data may get lost, overwritten, or + otherwise become unavailable. + <br /> + The OpenDC authors should in no way be liable in the event this happens + (see our{" "} + <strong> + <a href="https://github.com/atlarge-research/opendc/blob/master/LICENSE.md"> + license + </a> + </strong>). Sorry for the inconvenience. + </div> + </div> + </ContentSection> ); export default ContactSection; diff --git a/src/components/home/ContentSection.js b/src/components/home/ContentSection.js index 6b4cbca4..2e24ee10 100644 --- a/src/components/home/ContentSection.js +++ b/src/components/home/ContentSection.js @@ -3,17 +3,17 @@ import PropTypes from "prop-types"; import React from "react"; import "./ContentSection.css"; -const ContentSection = ({name, title, children}) => ( - <div id={name} className={classNames(name + "-section", "content-section")}> - <div className="container"> - <h1>{title}</h1> - {children} - </div> +const ContentSection = ({ name, title, children }) => ( + <div id={name} className={classNames(name + "-section", "content-section")}> + <div className="container"> + <h1>{title}</h1> + {children} </div> + </div> ); ContentSection.propTypes = { - name: PropTypes.string.isRequired, + name: PropTypes.string.isRequired }; export default ContentSection; diff --git a/src/components/home/IntroSection.js b/src/components/home/IntroSection.js index 246786f2..59f5face 100644 --- a/src/components/home/IntroSection.js +++ b/src/components/home/IntroSection.js @@ -1,38 +1,40 @@ import React from "react"; const IntroSection = () => ( - <section id="intro" className="intro-section"> - <div className="container pt-5 pb-3"> - <div className="row justify-content-center"> - <div className="col-xl-4 col-lg-4 col-md-4 col-sm-8 col-8"> - <h4>The datacenter (DC) industry...</h4> - <ul> - <li>Is worth over $15 bn, and growing</li> - <li>Has many hard-to-grasp concepts</li> - <li>Needs to become accessible to many</li> - </ul> - </div> - <div className="col-xl-4 col-lg-4 col-md-4 col-sm-8 col-8"> - <img src="img/datacenter-drawing.png" - className="col-12 img-fluid" - alt="Schematic top-down view of a datacenter"/> - <p className="col-12 figure-caption text-center"> - <a href="http://www.dolphinhosts.co.uk/wp-content/uploads/2013/07/data-centers.gif"> - Image source - </a> - </p> - </div> - <div className="col-xl-4 col-lg-4 col-md-4 col-sm-8 col-8"> - <h4>OpenDC provides...</h4> - <ul> - <li>Collaborative online DC modeling</li> - <li>Diverse and effective DC simulation</li> - <li>Exploratory DC performance feedback</li> - </ul> - </div> - </div> + <section id="intro" className="intro-section"> + <div className="container pt-5 pb-3"> + <div className="row justify-content-center"> + <div className="col-xl-4 col-lg-4 col-md-4 col-sm-8 col-8"> + <h4>The datacenter (DC) industry...</h4> + <ul> + <li>Is worth over $15 bn, and growing</li> + <li>Has many hard-to-grasp concepts</li> + <li>Needs to become accessible to many</li> + </ul> </div> - </section> + <div className="col-xl-4 col-lg-4 col-md-4 col-sm-8 col-8"> + <img + src="img/datacenter-drawing.png" + className="col-12 img-fluid" + alt="Schematic top-down view of a datacenter" + /> + <p className="col-12 figure-caption text-center"> + <a href="http://www.dolphinhosts.co.uk/wp-content/uploads/2013/07/data-centers.gif"> + Image source + </a> + </p> + </div> + <div className="col-xl-4 col-lg-4 col-md-4 col-sm-8 col-8"> + <h4>OpenDC provides...</h4> + <ul> + <li>Collaborative online DC modeling</li> + <li>Diverse and effective DC simulation</li> + <li>Exploratory DC performance feedback</li> + </ul> + </div> + </div> + </div> + </section> ); export default IntroSection; diff --git a/src/components/home/JumbotronHeader.js b/src/components/home/JumbotronHeader.js index ba504c18..8a5312b3 100644 --- a/src/components/home/JumbotronHeader.js +++ b/src/components/home/JumbotronHeader.js @@ -2,17 +2,19 @@ import React from "react"; import "./JumbotronHeader.css"; const JumbotronHeader = () => ( - <section className="jumbotron-header"> - <div className="container"> - <div className="jumbotron text-center"> - <h1>Open<span className="dc">DC</span></h1> - <p className="lead"> - Collaborative Datacenter Simulation and Exploration for Everybody - </p> - <img src="img/logo.png" className="img-responsive mt-3" alt="OpenDC"/> - </div> - </div> - </section> + <section className="jumbotron-header"> + <div className="container"> + <div className="jumbotron text-center"> + <h1> + Open<span className="dc">DC</span> + </h1> + <p className="lead"> + Collaborative Datacenter Simulation and Exploration for Everybody + </p> + <img src="img/logo.png" className="img-responsive mt-3" alt="OpenDC" /> + </div> + </div> + </section> ); export default JumbotronHeader; diff --git a/src/components/home/ModelingSection.js b/src/components/home/ModelingSection.js index d3252b9b..17834b0b 100644 --- a/src/components/home/ModelingSection.js +++ b/src/components/home/ModelingSection.js @@ -2,18 +2,23 @@ import React from "react"; import ScreenshotSection from "./ScreenshotSection"; const ModelingSection = () => ( - <ScreenshotSection name="modeling" title="Datacenter Modeling" - imageUrl="https://github.com/atlarge-research/opendc/raw/master/images/opendc-frontend-construction.PNG" - caption="Building a datacenter in OpenDC" - imageIsRight={true}> - <h3>Collaboratively...</h3> - <ul> - <li>Model DC layout, and room locations and types</li> - <li>Place racks in rooms and nodes in racks</li> - <li>Add real-world CPU, GPU, memory, storage and network units to each node</li> - <li>Select from diverse scheduling policies</li> - </ul> - </ScreenshotSection> + <ScreenshotSection + name="modeling" + title="Datacenter Modeling" + imageUrl="https://github.com/atlarge-research/opendc/raw/master/images/opendc-frontend-construction.PNG" + caption="Building a datacenter in OpenDC" + imageIsRight={true} + > + <h3>Collaboratively...</h3> + <ul> + <li>Model DC layout, and room locations and types</li> + <li>Place racks in rooms and nodes in racks</li> + <li> + Add real-world CPU, GPU, memory, storage and network units to each node + </li> + <li>Select from diverse scheduling policies</li> + </ul> + </ScreenshotSection> ); export default ModelingSection; diff --git a/src/components/home/ScreenshotSection.js b/src/components/home/ScreenshotSection.js index 74394dcb..42b8ac77 100644 --- a/src/components/home/ScreenshotSection.js +++ b/src/components/home/ScreenshotSection.js @@ -3,21 +3,30 @@ import React from "react"; import ContentSection from "./ContentSection"; import "./ScreenshotSection.css"; -const ScreenshotSection = ({name, title, imageUrl, caption, imageIsRight, children}) => ( - <ContentSection name={name} title={title}> - <div className="row"> - <div className={classNames("col-xl-5 col-lg-5 col-md-5 col-sm-12 col-12 text-left", - {"order-1": !imageIsRight})}> - {children} - </div> - <div className="col-xl-7 col-lg-7 col-md-7 col-sm-12 col-12"> - <img src={imageUrl} className="col-12 screenshot" alt={caption}/> - <div className="row text-muted justify-content-center"> - {caption} - </div> - </div> - </div> - </ContentSection> +const ScreenshotSection = ({ + name, + title, + imageUrl, + caption, + imageIsRight, + children +}) => ( + <ContentSection name={name} title={title}> + <div className="row"> + <div + className={classNames( + "col-xl-5 col-lg-5 col-md-5 col-sm-12 col-12 text-left", + { "order-1": !imageIsRight } + )} + > + {children} + </div> + <div className="col-xl-7 col-lg-7 col-md-7 col-sm-12 col-12"> + <img src={imageUrl} className="col-12 screenshot" alt={caption} /> + <div className="row text-muted justify-content-center">{caption}</div> + </div> + </div> + </ContentSection> ); export default ScreenshotSection; diff --git a/src/components/home/SimulationSection.js b/src/components/home/SimulationSection.js index eb1f7787..3961e549 100644 --- a/src/components/home/SimulationSection.js +++ b/src/components/home/SimulationSection.js @@ -2,18 +2,24 @@ import React from "react"; import ScreenshotSection from "./ScreenshotSection"; const ModelingSection = () => ( - <ScreenshotSection name="simulation" title="Datacenter Simulation" - imageUrl="https://github.com/atlarge-research/opendc/raw/master/images/opendc-frontend-simulation-zoom.PNG" - caption="Running an experiment in OpenDC" - imageIsRight={false}> - <h3>Working with OpenDC:</h3> - <ul> - <li>Seamlessly switch between construction and simulation modes</li> - <li>Choose one of several predefined workloads (Big Data, Bag of Tasks, Hadoop, etc.)</li> - <li>Play, pause, and skip around the informative simulation timeline</li> - <li>Visualize and demo live</li> - </ul> - </ScreenshotSection> + <ScreenshotSection + name="simulation" + title="Datacenter Simulation" + imageUrl="https://github.com/atlarge-research/opendc/raw/master/images/opendc-frontend-simulation-zoom.PNG" + caption="Running an experiment in OpenDC" + imageIsRight={false} + > + <h3>Working with OpenDC:</h3> + <ul> + <li>Seamlessly switch between construction and simulation modes</li> + <li> + Choose one of several predefined workloads (Big Data, Bag of Tasks, + Hadoop, etc.) + </li> + <li>Play, pause, and skip around the informative simulation timeline</li> + <li>Visualize and demo live</li> + </ul> + </ScreenshotSection> ); export default ModelingSection; diff --git a/src/components/home/StakeholderSection.js b/src/components/home/StakeholderSection.js index ddfe4f7c..6d25fd86 100644 --- a/src/components/home/StakeholderSection.js +++ b/src/components/home/StakeholderSection.js @@ -1,27 +1,42 @@ import React from "react"; import ContentSection from "./ContentSection"; -const Stakeholder = ({name, title, subtitle}) => ( - <div className="col-xl-4 col-lg-4 col-md-4 col-sm-6 col-6"> - <img src={"img/stakeholders/" + name + ".png"} - className="col-xl-3 col-lg-4 col-md-4 col-sm-4 col-4 img-fluid" alt={title}/> - <div className="text-center mt-2"> - <h4>{title}</h4> - <p>{subtitle}</p> - </div> +const Stakeholder = ({ name, title, subtitle }) => ( + <div className="col-xl-4 col-lg-4 col-md-4 col-sm-6 col-6"> + <img + src={"img/stakeholders/" + name + ".png"} + className="col-xl-3 col-lg-4 col-md-4 col-sm-4 col-4 img-fluid" + alt={title} + /> + <div className="text-center mt-2"> + <h4>{title}</h4> + <p>{subtitle}</p> </div> + </div> ); const StakeholderSection = () => ( - <ContentSection name="stakeholders" title="Stakeholders"> - <div className="row justify-content-center"> - <Stakeholder name="Manager" title="Managers" subtitle="Seeing is deciding"/> - <Stakeholder name="Sales" title="Sales" subtitle="Demo concepts"/> - <Stakeholder name="Developer" title="DevOps" subtitle="Develop & tune"/> - <Stakeholder name="Researcher" title="Researchers" subtitle="Understand & design"/> - <Stakeholder name="Student" title="Students" subtitle="Grasp complex concepts"/> - </div> - </ContentSection> + <ContentSection name="stakeholders" title="Stakeholders"> + <div className="row justify-content-center"> + <Stakeholder + name="Manager" + title="Managers" + subtitle="Seeing is deciding" + /> + <Stakeholder name="Sales" title="Sales" subtitle="Demo concepts" /> + <Stakeholder name="Developer" title="DevOps" subtitle="Develop & tune" /> + <Stakeholder + name="Researcher" + title="Researchers" + subtitle="Understand & design" + /> + <Stakeholder + name="Student" + title="Students" + subtitle="Grasp complex concepts" + /> + </div> + </ContentSection> ); export default StakeholderSection; diff --git a/src/components/home/TeamSection.js b/src/components/home/TeamSection.js index f9ca3105..f29003f7 100644 --- a/src/components/home/TeamSection.js +++ b/src/components/home/TeamSection.js @@ -1,43 +1,57 @@ import React from "react"; import ContentSection from "./ContentSection"; -const TeamMember = ({photoId, name, description}) => ( - <div className="col-xl-3 col-lg-3 col-md-5 col-sm-6 col-12 justify-content-center"> - <img src={"img/portraits/" + photoId + ".png"} - className="col-xl-10 col-lg-10 col-md-10 col-sm-8 col-5 mb-2 mt-2" - alt={name}/> - <div className="col-12"> - <h4>{name}</h4> - <div className="team-member-description"> - {description} - </div> - </div> +const TeamMember = ({ photoId, name, description }) => ( + <div className="col-xl-3 col-lg-3 col-md-5 col-sm-6 col-12 justify-content-center"> + <img + src={"img/portraits/" + photoId + ".png"} + className="col-xl-10 col-lg-10 col-md-10 col-sm-8 col-5 mb-2 mt-2" + alt={name} + /> + <div className="col-12"> + <h4>{name}</h4> + <div className="team-member-description">{description}</div> </div> + </div> ); const TeamSection = () => ( - <ContentSection name="team" title="Core Team"> - <div className="row justify-content-center"> - <TeamMember photoId="aiosup" name="Prof. dr. ir. Alexandru Iosup" - description="Project Lead"/> - <TeamMember photoId="loverweel" name="Leon Overweel" - description="Product Lead and Software Engineer responsible for the web server, database, and - API specification"/> - <TeamMember photoId="gandreadis" name="Georgios Andreadis" - description="Software Engineer responsible for the frontend web application"/> - <TeamMember photoId="fmastenbroek" name="Fabian Mastenbroek" - description="Software Engineer responsible for the datacenter simulator"/> - </div> - <div className="text-center lead mt-3"> - See - {" "} - <a target="_blank" href="http://atlarge.science/opendc#team" rel="noopener noreferrer"> - atlarge.science/opendc - </a> - {" "} - for the full team! - </div> - </ContentSection> + <ContentSection name="team" title="Core Team"> + <div className="row justify-content-center"> + <TeamMember + photoId="aiosup" + name="Prof. dr. ir. Alexandru Iosup" + description="Project Lead" + /> + <TeamMember + photoId="loverweel" + name="Leon Overweel" + description="Product Lead and Software Engineer responsible for the web server, database, and + API specification" + /> + <TeamMember + photoId="gandreadis" + name="Georgios Andreadis" + description="Software Engineer responsible for the frontend web application" + /> + <TeamMember + photoId="fmastenbroek" + name="Fabian Mastenbroek" + description="Software Engineer responsible for the datacenter simulator" + /> + </div> + <div className="text-center lead mt-3"> + See{" "} + <a + target="_blank" + href="http://atlarge.science/opendc#team" + rel="noopener noreferrer" + > + atlarge.science/opendc + </a>{" "} + for the full team! + </div> + </ContentSection> ); export default TeamSection; diff --git a/src/components/home/TechnologiesSection.js b/src/components/home/TechnologiesSection.js index 5e2ec2fc..fdcfc522 100644 --- a/src/components/home/TechnologiesSection.js +++ b/src/components/home/TechnologiesSection.js @@ -3,46 +3,40 @@ import FontAwesome from "react-fontawesome"; import ContentSection from "./ContentSection"; const TechnologiesSection = () => ( - <ContentSection name="technologies" title="Technologies"> - <ul className="list-group text-left"> - <li className="d-flex list-group-item justify-content-between align-items-center list-group-item-primary"> - <span style={{minWidth: 100}}> - <FontAwesome name="window-maximize" className="mr-2"/> - <strong className="">Browser</strong> - </span> - <span className="text-right"> - JavaScript, React, Redux, Konva - </span> - </li> - <li className="d-flex list-group-item justify-content-between align-items-center list-group-item-warning"> - <span style={{minWidth: 100}}> - <FontAwesome name="television" className="mr-2"/> - <strong>Server</strong> - </span> - <span className="text-right"> - Python, Flask, FlaskSocketIO, OpenAPI - </span> - </li> - <li className="d-flex list-group-item justify-content-between align-items-center list-group-item-success"> - <span style={{minWidth: 100}}> - <FontAwesome name="database" className="mr-2"/> - <strong>Database</strong> - </span> - <span className="text-right"> - MariaDB - </span> - </li> - <li className="d-flex list-group-item justify-content-between align-items-center list-group-item-danger"> - <span style={{minWidth: 100}}> - <FontAwesome name="cogs" className="mr-2"/> - <strong>Simulator</strong> - </span> - <span className="text-right"> - Kotlin - </span> - </li> - </ul> - </ContentSection> + <ContentSection name="technologies" title="Technologies"> + <ul className="list-group text-left"> + <li className="d-flex list-group-item justify-content-between align-items-center list-group-item-primary"> + <span style={{ minWidth: 100 }}> + <FontAwesome name="window-maximize" className="mr-2" /> + <strong className="">Browser</strong> + </span> + <span className="text-right">JavaScript, React, Redux, Konva</span> + </li> + <li className="d-flex list-group-item justify-content-between align-items-center list-group-item-warning"> + <span style={{ minWidth: 100 }}> + <FontAwesome name="television" className="mr-2" /> + <strong>Server</strong> + </span> + <span className="text-right"> + Python, Flask, FlaskSocketIO, OpenAPI + </span> + </li> + <li className="d-flex list-group-item justify-content-between align-items-center list-group-item-success"> + <span style={{ minWidth: 100 }}> + <FontAwesome name="database" className="mr-2" /> + <strong>Database</strong> + </span> + <span className="text-right">MariaDB</span> + </li> + <li className="d-flex list-group-item justify-content-between align-items-center list-group-item-danger"> + <span style={{ minWidth: 100 }}> + <FontAwesome name="cogs" className="mr-2" /> + <strong>Simulator</strong> + </span> + <span className="text-right">Kotlin</span> + </li> + </ul> + </ContentSection> ); export default TechnologiesSection; diff --git a/src/components/modals/ConfirmationModal.js b/src/components/modals/ConfirmationModal.js index 4543cfd4..abdce5ac 100644 --- a/src/components/modals/ConfirmationModal.js +++ b/src/components/modals/ConfirmationModal.js @@ -3,33 +3,35 @@ import React from "react"; import Modal from "./Modal"; class ConfirmationModal extends React.Component { - static propTypes = { - title: PropTypes.string.isRequired, - message: PropTypes.string.isRequired, - show: PropTypes.bool.isRequired, - callback: PropTypes.func.isRequired, - }; + static propTypes = { + title: PropTypes.string.isRequired, + message: PropTypes.string.isRequired, + show: PropTypes.bool.isRequired, + callback: PropTypes.func.isRequired + }; - onConfirm() { - this.props.callback(true); - } + onConfirm() { + this.props.callback(true); + } - onCancel() { - this.props.callback(false); - } + onCancel() { + this.props.callback(false); + } - render() { - return ( - <Modal title={this.props.title} - show={this.props.show} - onSubmit={this.onConfirm.bind(this)} - onCancel={this.onCancel.bind(this)} - submitButtonType="danger" - submitButtonText="Confirm"> - {this.props.message} - </Modal> - ); - } + render() { + return ( + <Modal + title={this.props.title} + show={this.props.show} + onSubmit={this.onConfirm.bind(this)} + onCancel={this.onCancel.bind(this)} + submitButtonType="danger" + submitButtonText="Confirm" + > + {this.props.message} + </Modal> + ); + } } export default ConfirmationModal; diff --git a/src/components/modals/Modal.js b/src/components/modals/Modal.js index 1de17455..367cf2da 100644 --- a/src/components/modals/Modal.js +++ b/src/components/modals/Modal.js @@ -4,116 +4,129 @@ import React from "react"; import jQuery from "../../util/jquery"; class Modal extends React.Component { - static propTypes = { - title: PropTypes.string.isRequired, - show: PropTypes.bool.isRequired, - onSubmit: PropTypes.func.isRequired, - onCancel: PropTypes.func.isRequired, - submitButtonType: PropTypes.string, - submitButtonText: PropTypes.string, - }; - static defaultProps = { - submitButtonType: "primary", - submitButtonText: "Save", - }; - static idCounter = 0; + static propTypes = { + title: PropTypes.string.isRequired, + show: PropTypes.bool.isRequired, + onSubmit: PropTypes.func.isRequired, + onCancel: PropTypes.func.isRequired, + submitButtonType: PropTypes.string, + submitButtonText: PropTypes.string + }; + static defaultProps = { + submitButtonType: "primary", + submitButtonText: "Save" + }; + static idCounter = 0; - /** - * Local, up-to-date copy of modal visibility for time between close event and a props update (to prevent duplicate - * close triggers). - */ - visible = false; + // Local, up-to-date copy of modal visibility for time between close event and a props update (to prevent duplicate + // 'close' triggers) + visible = false; - constructor() { - super(); - this.id = "modal-" + Modal.idCounter++; - } - - componentDidMount() { - this.visible = this.props.show; - this.openOrCloseModal(); - - // Trigger auto-focus - jQuery("#" + this.id) - .on("shown.bs.modal", function () { - jQuery(this).find("input").first().focus(); - }) - .on("hide.bs.modal", () => { - if (this.visible) { - this.props.onCancel(); - } - }) - .on("keydown", e => { - e.stopPropagation(); - }); - } + constructor() { + super(); + this.id = "modal-" + Modal.idCounter++; + } - componentDidUpdate() { - this.visible = this.props.show; - this.openOrCloseModal(); - } + componentDidMount() { + this.visible = this.props.show; + this.openOrCloseModal(); - onSubmit() { + // Trigger auto-focus + jQuery("#" + this.id) + .on("shown.bs.modal", function() { + jQuery(this) + .find("input") + .first() + .focus(); + }) + .on("hide.bs.modal", () => { if (this.visible) { - this.props.onSubmit(); - this.visible = false; - this.closeModal(); + this.props.onCancel(); } - } + }) + .on("keydown", e => { + e.stopPropagation(); + }); + } - onCancel() { - if (this.visible) { - this.props.onCancel(); - this.visible = false; - this.closeModal(); - } - } + componentDidUpdate() { + this.visible = this.props.show; + this.openOrCloseModal(); + } - openModal() { - jQuery("#" + this.id).modal("show"); + onSubmit() { + if (this.visible) { + this.props.onSubmit(); + this.visible = false; + this.closeModal(); } + } - closeModal() { - jQuery("#" + this.id).modal("hide"); + onCancel() { + if (this.visible) { + this.props.onCancel(); + this.visible = false; + this.closeModal(); } + } - openOrCloseModal() { - if (this.visible) { - this.openModal(); - } else { - this.closeModal(); - } + openModal() { + jQuery("#" + this.id).modal("show"); + } + + closeModal() { + jQuery("#" + this.id).modal("hide"); + } + + openOrCloseModal() { + if (this.visible) { + this.openModal(); + } else { + this.closeModal(); } + } - render() { - return ( - <div className="modal fade" id={this.id} role="dialog"> - <div className="modal-dialog" role="document"> - <div className="modal-content"> - <div className="modal-header"> - <h5 className="modal-title">{this.props.title}</h5> - <button type="button" className="close" onClick={this.onCancel.bind(this)} - aria-label="Close"> - <span>×</span> - </button> - </div> - <div className="modal-body"> - {this.props.children} - </div> - <div className="modal-footer"> - <button type="button" className="btn btn-secondary" onClick={this.onCancel.bind(this)}> - Close - </button> - <button type="button" className={classNames("btn", "btn-" + this.props.submitButtonType)} - onClick={this.onSubmit.bind(this)}> - {this.props.submitButtonText} - </button> - </div> - </div> - </div> + render() { + return ( + <div className="modal fade" id={this.id} role="dialog"> + <div className="modal-dialog" role="document"> + <div className="modal-content"> + <div className="modal-header"> + <h5 className="modal-title">{this.props.title}</h5> + <button + type="button" + className="close" + onClick={this.onCancel.bind(this)} + aria-label="Close" + > + <span>×</span> + </button> </div> - ); - } + <div className="modal-body">{this.props.children}</div> + <div className="modal-footer"> + <button + type="button" + className="btn btn-secondary" + onClick={this.onCancel.bind(this)} + > + Close + </button> + <button + type="button" + className={classNames( + "btn", + "btn-" + this.props.submitButtonType + )} + onClick={this.onSubmit.bind(this)} + > + {this.props.submitButtonText} + </button> + </div> + </div> + </div> + </div> + ); + } } export default Modal; diff --git a/src/components/modals/TextInputModal.js b/src/components/modals/TextInputModal.js index 132df9fe..cc16f8e1 100644 --- a/src/components/modals/TextInputModal.js +++ b/src/components/modals/TextInputModal.js @@ -3,49 +3,56 @@ import React from "react"; import Modal from "./Modal"; class TextInputModal extends React.Component { - static propTypes = { - title: PropTypes.string.isRequired, - label: PropTypes.string.isRequired, - show: PropTypes.bool.isRequired, - callback: PropTypes.func.isRequired, - initialValue: PropTypes.string, - }; + static propTypes = { + title: PropTypes.string.isRequired, + label: PropTypes.string.isRequired, + show: PropTypes.bool.isRequired, + callback: PropTypes.func.isRequired, + initialValue: PropTypes.string + }; - componentDidUpdate() { - if (this.props.initialValue) { - this.textInput.value = this.props.initialValue; - } + componentDidUpdate() { + if (this.props.initialValue) { + this.textInput.value = this.props.initialValue; } + } - onSubmit() { - this.props.callback(this.textInput.value); - this.textInput.value = ""; - } + onSubmit() { + this.props.callback(this.textInput.value); + this.textInput.value = ""; + } - onCancel() { - this.props.callback(undefined); - this.textInput.value = ""; - } + onCancel() { + this.props.callback(undefined); + this.textInput.value = ""; + } - render() { - return ( - <Modal title={this.props.title} - show={this.props.show} - onSubmit={this.onSubmit.bind(this)} - onCancel={this.onCancel.bind(this)}> - <form onSubmit={e => { - e.preventDefault(); - this.onSubmit(); - }}> - <div className="form-group"> - <label className="form-control-label">{this.props.label}</label> - <input type="text" className="form-control" - ref={textInput => this.textInput = textInput}/> - </div> - </form> - </Modal> - ); - } + render() { + return ( + <Modal + title={this.props.title} + show={this.props.show} + onSubmit={this.onSubmit.bind(this)} + onCancel={this.onCancel.bind(this)} + > + <form + onSubmit={e => { + e.preventDefault(); + this.onSubmit(); + }} + > + <div className="form-group"> + <label className="form-control-label">{this.props.label}</label> + <input + type="text" + className="form-control" + ref={textInput => (this.textInput = textInput)} + /> + </div> + </form> + </Modal> + ); + } } export default TextInputModal; diff --git a/src/components/modals/custom-components/NewExperimentModalComponent.js b/src/components/modals/custom-components/NewExperimentModalComponent.js index d56d2316..e356fe96 100644 --- a/src/components/modals/custom-components/NewExperimentModalComponent.js +++ b/src/components/modals/custom-components/NewExperimentModalComponent.js @@ -4,88 +4,101 @@ import Shapes from "../../../shapes"; import Modal from "../Modal"; class NewExperimentModalComponent extends React.Component { - static propTypes = { - show: PropTypes.bool.isRequired, - paths: PropTypes.arrayOf(Shapes.Path), - schedulers: PropTypes.arrayOf(Shapes.Scheduler), - traces: PropTypes.arrayOf(Shapes.Trace), - callback: PropTypes.func.isRequired, - }; + static propTypes = { + show: PropTypes.bool.isRequired, + paths: PropTypes.arrayOf(Shapes.Path), + schedulers: PropTypes.arrayOf(Shapes.Scheduler), + traces: PropTypes.arrayOf(Shapes.Trace), + callback: PropTypes.func.isRequired + }; - reset() { - this.textInput.value = ""; - this.pathSelect.selectedIndex = 0; - this.traceSelect.selectedIndex = 0; - this.schedulerSelect.selectedIndex = 0; - } + reset() { + this.textInput.value = ""; + this.pathSelect.selectedIndex = 0; + this.traceSelect.selectedIndex = 0; + this.schedulerSelect.selectedIndex = 0; + } - onSubmit() { - this.props.callback( - this.textInput.value, - parseInt(this.pathSelect.value, 10), - parseInt(this.traceSelect.value, 10), - this.schedulerSelect.value - ); - this.reset(); - } + onSubmit() { + this.props.callback( + this.textInput.value, + parseInt(this.pathSelect.value, 10), + parseInt(this.traceSelect.value, 10), + this.schedulerSelect.value + ); + this.reset(); + } - onCancel() { - this.props.callback(undefined); - this.reset(); - } + onCancel() { + this.props.callback(undefined); + this.reset(); + } - render() { - return ( - <Modal title="New Experiment" - show={this.props.show} - onSubmit={this.onSubmit.bind(this)} - onCancel={this.onCancel.bind(this)}> - <form onSubmit={e => { - e.preventDefault(); - this.onSubmit(); - }}> - <div className="form-group"> - <label className="form-control-label">Name</label> - <input type="text" className="form-control" - ref={textInput => this.textInput = textInput}/> - </div> - <div className="form-group"> - <label className="form-control-label">Path</label> - <select className="form-control" - ref={pathSelect => this.pathSelect = pathSelect}> - {this.props.paths.map(path => ( - <option value={path.id} key={path.id}> - {path.name ? path.name : "Path " + path.id} - </option> - ))} - </select> - </div> - <div className="form-group"> - <label className="form-control-label">Trace</label> - <select className="form-control" - ref={traceSelect => this.traceSelect = traceSelect}> - {this.props.traces.map(trace => ( - <option value={trace.id} key={trace.id}> - {trace.name} - </option> - ))} - </select> - </div> - <div className="form-group"> - <label className="form-control-label">Scheduler</label> - <select className="form-control" - ref={schedulerSelect => this.schedulerSelect = schedulerSelect}> - {this.props.schedulers.map(scheduler => ( - <option value={scheduler.name} key={scheduler.name}> - {scheduler.name} - </option> - ))} - </select> - </div> - </form> - </Modal> - ); - } + render() { + return ( + <Modal + title="New Experiment" + show={this.props.show} + onSubmit={this.onSubmit.bind(this)} + onCancel={this.onCancel.bind(this)} + > + <form + onSubmit={e => { + e.preventDefault(); + this.onSubmit(); + }} + > + <div className="form-group"> + <label className="form-control-label">Name</label> + <input + type="text" + className="form-control" + ref={textInput => (this.textInput = textInput)} + /> + </div> + <div className="form-group"> + <label className="form-control-label">Path</label> + <select + className="form-control" + ref={pathSelect => (this.pathSelect = pathSelect)} + > + {this.props.paths.map(path => ( + <option value={path.id} key={path.id}> + {path.name ? path.name : "Path " + path.id} + </option> + ))} + </select> + </div> + <div className="form-group"> + <label className="form-control-label">Trace</label> + <select + className="form-control" + ref={traceSelect => (this.traceSelect = traceSelect)} + > + {this.props.traces.map(trace => ( + <option value={trace.id} key={trace.id}> + {trace.name} + </option> + ))} + </select> + </div> + <div className="form-group"> + <label className="form-control-label">Scheduler</label> + <select + className="form-control" + ref={schedulerSelect => (this.schedulerSelect = schedulerSelect)} + > + {this.props.schedulers.map(scheduler => ( + <option value={scheduler.name} key={scheduler.name}> + {scheduler.name} + </option> + ))} + </select> + </div> + </form> + </Modal> + ); + } } export default NewExperimentModalComponent; diff --git a/src/components/navigation/AppNavbar.js b/src/components/navigation/AppNavbar.js index 90724a3e..ab4b8412 100644 --- a/src/components/navigation/AppNavbar.js +++ b/src/components/navigation/AppNavbar.js @@ -1,53 +1,58 @@ -import React from 'react'; +import React from "react"; import FontAwesome from "react-fontawesome"; import Mailto from "react-mailto"; -import {Link} from "react-router-dom"; -import Navbar, {NavItem} from "./Navbar"; +import { Link } from "react-router-dom"; +import Navbar, { NavItem } from "./Navbar"; import "./Navbar.css"; -const AppNavbar = ({simulationId, inSimulation, fullWidth}) => ( - <Navbar fullWidth={fullWidth}> - {inSimulation ? - <NavItem route={"/simulations/" + simulationId}> - <Link - className="nav-link" - title="Construction" - to={"/simulations/" + simulationId}> - <FontAwesome name="industry" className="mr-2"/> - Construction - </Link> - </NavItem> : - undefined - } - {inSimulation ? - <NavItem route={"/simulations/" + simulationId + "/experiments"}> - <Link - className="nav-link" - title="Experiments" - to={"/simulations/" + simulationId + "/experiments"}> - <FontAwesome name="play" className="mr-2"/> - Experiments - </Link> - </NavItem> : - undefined - } - <NavItem route="/simulations"> - <Link - className="nav-link" - title="My Simulations" - to="/simulations"> - <FontAwesome name="list" className="mr-2"/> - My Simulations - </Link> - </NavItem> - <NavItem route="email"> - <Mailto className="nav-link" title="Support" email="opendc@atlarge-research.com" - headers={{subject: "[support]"}}> - <FontAwesome name="envelope" className="mr-2"/> - Support - </Mailto> - </NavItem> - </Navbar> +const AppNavbar = ({ simulationId, inSimulation, fullWidth }) => ( + <Navbar fullWidth={fullWidth}> + {inSimulation ? ( + <NavItem route={"/simulations/" + simulationId}> + <Link + className="nav-link" + title="Construction" + to={"/simulations/" + simulationId} + > + <FontAwesome name="industry" className="mr-2" /> + Construction + </Link> + </NavItem> + ) : ( + undefined + )} + {inSimulation ? ( + <NavItem route={"/simulations/" + simulationId + "/experiments"}> + <Link + className="nav-link" + title="Experiments" + to={"/simulations/" + simulationId + "/experiments"} + > + <FontAwesome name="play" className="mr-2" /> + Experiments + </Link> + </NavItem> + ) : ( + undefined + )} + <NavItem route="/simulations"> + <Link className="nav-link" title="My Simulations" to="/simulations"> + <FontAwesome name="list" className="mr-2" /> + My Simulations + </Link> + </NavItem> + <NavItem route="email"> + <Mailto + className="nav-link" + title="Support" + email="opendc@atlarge-research.com" + headers={{ subject: "[support]" }} + > + <FontAwesome name="envelope" className="mr-2" /> + Support + </Mailto> + </NavItem> + </Navbar> ); export default AppNavbar; diff --git a/src/components/navigation/HomeNavbar.js b/src/components/navigation/HomeNavbar.js index 4d821325..5d08bf3c 100644 --- a/src/components/navigation/HomeNavbar.js +++ b/src/components/navigation/HomeNavbar.js @@ -1,22 +1,24 @@ -import React from 'react'; +import React from "react"; import Navbar from "./Navbar"; import "./Navbar.css"; -const ScrollNavItem = ({id, name}) => ( - <li className="nav-item"> - <a className="nav-link" href={id}>{name}</a> - </li> +const ScrollNavItem = ({ id, name }) => ( + <li className="nav-item"> + <a className="nav-link" href={id}> + {name} + </a> + </li> ); const HomeNavbar = () => ( - <Navbar fullWidth={false}> - <ScrollNavItem id="#stakeholders" name="Stakeholders"/> - <ScrollNavItem id="#modeling" name="Modeling"/> - <ScrollNavItem id="#simulation" name="Simulation"/> - <ScrollNavItem id="#technologies" name="Technologies"/> - <ScrollNavItem id="#team" name="Team"/> - <ScrollNavItem id="#contact" name="Contact"/> - </Navbar> + <Navbar fullWidth={false}> + <ScrollNavItem id="#stakeholders" name="Stakeholders" /> + <ScrollNavItem id="#modeling" name="Modeling" /> + <ScrollNavItem id="#simulation" name="Simulation" /> + <ScrollNavItem id="#technologies" name="Technologies" /> + <ScrollNavItem id="#team" name="Team" /> + <ScrollNavItem id="#contact" name="Contact" /> + </Navbar> ); export default HomeNavbar; diff --git a/src/components/navigation/LogoutButton.js b/src/components/navigation/LogoutButton.js index d58776dc..800a3da8 100644 --- a/src/components/navigation/LogoutButton.js +++ b/src/components/navigation/LogoutButton.js @@ -1,16 +1,16 @@ import PropTypes from "prop-types"; import React from "react"; import FontAwesome from "react-fontawesome"; -import {Link} from "react-router-dom"; +import { Link } from "react-router-dom"; -const LogoutButton = ({onLogout}) => ( - <Link className="logout nav-link" title="Sign out" to="#" onClick={onLogout}> - <FontAwesome name="power-off" size="lg"/> - </Link> +const LogoutButton = ({ onLogout }) => ( + <Link className="logout nav-link" title="Sign out" to="#" onClick={onLogout}> + <FontAwesome name="power-off" size="lg" /> + </Link> ); LogoutButton.propTypes = { - onLogout: PropTypes.func.isRequired, + onLogout: PropTypes.func.isRequired }; export default LogoutButton; diff --git a/src/components/navigation/Navbar.js b/src/components/navigation/Navbar.js index 4981bb53..fa2516f5 100644 --- a/src/components/navigation/Navbar.js +++ b/src/components/navigation/Navbar.js @@ -1,7 +1,7 @@ import classNames from "classnames"; -import React from 'react'; -import {Link, withRouter} from "react-router-dom"; -import {userIsLoggedIn} from "../../auth/index"; +import React from "react"; +import { Link, withRouter } from "react-router-dom"; +import { userIsLoggedIn } from "../../auth/index"; import Login from "../../containers/auth/Login"; import Logout from "../../containers/auth/Logout"; import ProfileName from "../../containers/auth/ProfileName"; @@ -9,73 +9,83 @@ import "./Navbar.css"; export const NAVBAR_HEIGHT = 60; -export const NavItem = withRouter(props => <NavItemWithoutRoute {...props}/>); -export const LoggedInSection = withRouter(props => <LoggedInSectionWithoutRoute {...props}/>); +export const NavItem = withRouter(props => <NavItemWithoutRoute {...props} />); +export const LoggedInSection = withRouter(props => ( + <LoggedInSectionWithoutRoute {...props} /> +)); -const NavItemWithoutRoute = ({route, location, children}) => ( - <li className={classNames("nav-item", location.pathname === route ? "active" : undefined)}> - {children} - </li> +const NavItemWithoutRoute = ({ route, location, children }) => ( + <li + className={classNames( + "nav-item", + location.pathname === route ? "active" : undefined + )} + > + {children} + </li> ); -const LoggedInSectionWithoutRoute = ({location}) => ( - <ul className="navbar-nav auth-links"> - {userIsLoggedIn() ? - [ - location.pathname === "/" ? - <NavItem route="/simulations" key="simulations"> - <Link className="nav-link" title="My Simulations" to="/simulations"> - My Simulations - </Link> - </NavItem> : - <NavItem route="/profile" key="profile"> - <Link className="nav-link" title="My Profile" to="/profile"> - <ProfileName/> - </Link> - </NavItem>, - <NavItem route="logout" key="logout"> - <Logout/> - </NavItem> - ] : - <NavItem route="login"> - <Login visible={true}/> - </NavItem> - } - </ul> - ) -; - -const Navbar = ({fullWidth, children}) => ( - <nav className="navbar fixed-top navbar-expand-lg navbar-light bg-faded" id="navbar"> - <div className={fullWidth ? "container-fluid" : "container"}> - <button - className="navbar-toggler navbar-toggler-right" - type="button" - data-toggle="collapse" - data-target="#navbarSupportedContent" - aria-controls="navbarSupportedContent" - aria-expanded="false" - aria-label="Toggle navigation" - > - <span className="navbar-toggler-icon"/> - </button> - <Link - className="navbar-brand opendc-brand" - to="/" - title="OpenDC" - onClick={() => window.scrollTo(0, 0)} - > - <img src="/img/logo.png" alt="OpenDC"/> +const LoggedInSectionWithoutRoute = ({ location }) => ( + <ul className="navbar-nav auth-links"> + {userIsLoggedIn() ? ( + [ + location.pathname === "/" ? ( + <NavItem route="/simulations" key="simulations"> + <Link className="nav-link" title="My Simulations" to="/simulations"> + My Simulations + </Link> + </NavItem> + ) : ( + <NavItem route="/profile" key="profile"> + <Link className="nav-link" title="My Profile" to="/profile"> + <ProfileName /> </Link> + </NavItem> + ), + <NavItem route="logout" key="logout"> + <Logout /> + </NavItem> + ] + ) : ( + <NavItem route="login"> + <Login visible={true} /> + </NavItem> + )} + </ul> +); + +const Navbar = ({ fullWidth, children }) => ( + <nav + className="navbar fixed-top navbar-expand-lg navbar-light bg-faded" + id="navbar" + > + <div className={fullWidth ? "container-fluid" : "container"}> + <button + className="navbar-toggler navbar-toggler-right" + type="button" + data-toggle="collapse" + data-target="#navbarSupportedContent" + aria-controls="navbarSupportedContent" + aria-expanded="false" + aria-label="Toggle navigation" + > + <span className="navbar-toggler-icon" /> + </button> + <Link + className="navbar-brand opendc-brand" + to="/" + title="OpenDC" + onClick={() => window.scrollTo(0, 0)} + > + <img src="/img/logo.png" alt="OpenDC" /> + </Link> - <div className="collapse navbar-collapse" id="navbarSupportedContent"> - <ul className="navbar-nav mr-auto"> - {children} - </ul> - <LoggedInSection/> - </div> - </div> - </nav> + <div className="collapse navbar-collapse" id="navbarSupportedContent"> + <ul className="navbar-nav mr-auto">{children}</ul> + <LoggedInSection /> + </div> + </div> + </nav> ); export default Navbar; diff --git a/src/components/not-found/BlinkingCursor.js b/src/components/not-found/BlinkingCursor.js index f6c9768c..eea89e7b 100644 --- a/src/components/not-found/BlinkingCursor.js +++ b/src/components/not-found/BlinkingCursor.js @@ -1,8 +1,6 @@ import React from "react"; import "./BlinkingCursor.css"; -const BlinkingCursor = () => ( - <span className="blinking-cursor">_</span> -); +const BlinkingCursor = () => <span className="blinking-cursor">_</span>; export default BlinkingCursor; diff --git a/src/components/not-found/CodeBlock.js b/src/components/not-found/CodeBlock.js index 24d100cc..46dc4402 100644 --- a/src/components/not-found/CodeBlock.js +++ b/src/components/not-found/CodeBlock.js @@ -2,29 +2,33 @@ import React from "react"; import "./CodeBlock.css"; const CodeBlock = () => { - const textBlock = - " oo oooo oo <br/>" + - " oo oo oo oo <br/>" + - " oo oo oo oo <br/>" + - " oooooo oo oo oooooo <br/>" + - " oo oo oo oo <br/>" + - " oo oooo oo <br/>"; - const charList = textBlock.split(''); + const textBlock = + " oo oooo oo <br/>" + + " oo oo oo oo <br/>" + + " oo oo oo oo <br/>" + + " oooooo oo oo oooooo <br/>" + + " oo oo oo oo <br/>" + + " oo oooo oo <br/>"; + const charList = textBlock.split(""); - // Binary representation of the string "OpenDC!" ;) - const binaryString = "01001111011100000110010101101110010001000100001100100001"; + // Binary representation of the string "OpenDC!" ;) + const binaryString = + "01001111011100000110010101101110010001000100001100100001"; - let binaryIndex = 0; - for (let i = 0; i < charList.length; i++) { - if (charList[i] === "o") { - charList[i] = binaryString[binaryIndex]; - binaryIndex++; - } + let binaryIndex = 0; + for (let i = 0; i < charList.length; i++) { + if (charList[i] === "o") { + charList[i] = binaryString[binaryIndex]; + binaryIndex++; } + } - return ( - <div className="code-block" dangerouslySetInnerHTML={{__html: textBlock}}/> - ); + return ( + <div + className="code-block" + dangerouslySetInnerHTML={{ __html: textBlock }} + /> + ); }; export default CodeBlock; diff --git a/src/components/not-found/TerminalWindow.js b/src/components/not-found/TerminalWindow.js index 52d3c062..c6b8b78b 100644 --- a/src/components/not-found/TerminalWindow.js +++ b/src/components/not-found/TerminalWindow.js @@ -1,26 +1,29 @@ import React from "react"; -import {Link} from "react-router-dom"; +import { Link } from "react-router-dom"; import BlinkingCursor from "./BlinkingCursor"; import CodeBlock from "./CodeBlock"; import "./TerminalWindow.css"; const TerminalWindow = () => ( - <div className="terminal-window"> - <div className="terminal-header">Terminal -- bash</div> - <div className="terminal-body"> - <div className="segfault">$ status<br/> - opendc[4264]: segfault at 0000051497be459d1 err 12 in libopendc.9.0.4<br/> - opendc[4269]: segfault at 000004234855fc2db err 3 in libopendc.9.0.4<br/> - opendc[4270]: STDERR Page does not exist<br/> - </div> - <CodeBlock/> - <div className="sub-title">Got lost?<BlinkingCursor/></div> - <Link to="/" className="home-btn"> - <span className="fa fa-home"/> GET ME BACK TO OPENDC - </Link> - </div> + <div className="terminal-window"> + <div className="terminal-header">Terminal -- bash</div> + <div className="terminal-body"> + <div className="segfault"> + $ status<br /> + opendc[4264]: segfault at 0000051497be459d1 err 12 in libopendc.9.0.4<br + /> + opendc[4269]: segfault at 000004234855fc2db err 3 in libopendc.9.0.4<br /> + opendc[4270]: STDERR Page does not exist<br /> + </div> + <CodeBlock /> + <div className="sub-title"> + Got lost?<BlinkingCursor /> + </div> + <Link to="/" className="home-btn"> + <span className="fa fa-home" /> GET ME BACK TO OPENDC + </Link> </div> + </div> ); - export default TerminalWindow; diff --git a/src/components/simulations/FilterButton.js b/src/components/simulations/FilterButton.js index b26dd231..aa41f180 100644 --- a/src/components/simulations/FilterButton.js +++ b/src/components/simulations/FilterButton.js @@ -1,22 +1,24 @@ -import classNames from 'classnames'; -import PropTypes from 'prop-types'; -import React from 'react'; +import classNames from "classnames"; +import PropTypes from "prop-types"; +import React from "react"; -const FilterButton = ({active, children, onClick}) => ( - <button className={classNames("btn btn-secondary", {"active": active})} - onClick={() => { - if (!active) { - onClick(); - } - }}> - {children} - </button> +const FilterButton = ({ active, children, onClick }) => ( + <button + className={classNames("btn btn-secondary", { active: active })} + onClick={() => { + if (!active) { + onClick(); + } + }} + > + {children} + </button> ); FilterButton.propTypes = { - active: PropTypes.bool.isRequired, - children: PropTypes.node.isRequired, - onClick: PropTypes.func.isRequired + active: PropTypes.bool.isRequired, + children: PropTypes.node.isRequired, + onClick: PropTypes.func.isRequired }; export default FilterButton; diff --git a/src/components/simulations/FilterPanel.js b/src/components/simulations/FilterPanel.js index 504e24e4..836c0842 100644 --- a/src/components/simulations/FilterPanel.js +++ b/src/components/simulations/FilterPanel.js @@ -1,13 +1,13 @@ -import React from 'react'; +import React from "react"; import FilterLink from "../../containers/simulations/FilterLink"; import "./FilterPanel.css"; const FilterPanel = () => ( - <div className="btn-group filter-panel mb-2"> - <FilterLink filter="SHOW_ALL">All Simulations</FilterLink> - <FilterLink filter="SHOW_OWN">My Simulations</FilterLink> - <FilterLink filter="SHOW_SHARED">Shared with me</FilterLink> - </div> + <div className="btn-group filter-panel mb-2"> + <FilterLink filter="SHOW_ALL">All Simulations</FilterLink> + <FilterLink filter="SHOW_OWN">My Simulations</FilterLink> + <FilterLink filter="SHOW_SHARED">Shared with me</FilterLink> + </div> ); export default FilterPanel; diff --git a/src/components/simulations/NewSimulationButtonComponent.js b/src/components/simulations/NewSimulationButtonComponent.js index 74036c1b..7e12d30f 100644 --- a/src/components/simulations/NewSimulationButtonComponent.js +++ b/src/components/simulations/NewSimulationButtonComponent.js @@ -1,17 +1,17 @@ -import PropTypes from 'prop-types'; -import React from 'react'; +import PropTypes from "prop-types"; +import React from "react"; -const NewSimulationButtonComponent = ({onClick}) => ( - <div className="bottom-btn-container"> - <div className="btn btn-primary float-right" onClick={onClick}> - <span className="fa fa-plus mr-2"/> - New Simulation - </div> +const NewSimulationButtonComponent = ({ onClick }) => ( + <div className="bottom-btn-container"> + <div className="btn btn-primary float-right" onClick={onClick}> + <span className="fa fa-plus mr-2" /> + New Simulation </div> + </div> ); NewSimulationButtonComponent.propTypes = { - onClick: PropTypes.func.isRequired, + onClick: PropTypes.func.isRequired }; export default NewSimulationButtonComponent; diff --git a/src/components/simulations/SimulationActionButtons.js b/src/components/simulations/SimulationActionButtons.js index c8325a71..46f4f159 100644 --- a/src/components/simulations/SimulationActionButtons.js +++ b/src/components/simulations/SimulationActionButtons.js @@ -1,37 +1,37 @@ import PropTypes from "prop-types"; -import React from 'react'; -import {Link} from "react-router-dom"; +import React from "react"; +import { Link } from "react-router-dom"; -const SimulationActionButtons = ({simulationId, onViewUsers, onDelete}) => ( - <td className="text-right"> - <Link - to={"/simulations/" + simulationId} - className="btn btn-outline-primary btn-sm mr-2" - title="Open this simulation" - > - <span className="fa fa-play"/> - </Link> - <div - className="btn btn-outline-success btn-sm disabled mr-2" - title="View and edit collaborators (not supported yet)" - onClick={() => onViewUsers(simulationId)} - > - <span className="fa fa-users"/> - </div> - <div - className="btn btn-outline-danger btn-sm" - title="Delete this simulation" - onClick={() => onDelete(simulationId)} - > - <span className="fa fa-trash"/> - </div> - </td> +const SimulationActionButtons = ({ simulationId, onViewUsers, onDelete }) => ( + <td className="text-right"> + <Link + to={"/simulations/" + simulationId} + className="btn btn-outline-primary btn-sm mr-2" + title="Open this simulation" + > + <span className="fa fa-play" /> + </Link> + <div + className="btn btn-outline-success btn-sm disabled mr-2" + title="View and edit collaborators (not supported yet)" + onClick={() => onViewUsers(simulationId)} + > + <span className="fa fa-users" /> + </div> + <div + className="btn btn-outline-danger btn-sm" + title="Delete this simulation" + onClick={() => onDelete(simulationId)} + > + <span className="fa fa-trash" /> + </div> + </td> ); SimulationActionButtons.propTypes = { - simulationId: PropTypes.number.isRequired, - onViewUsers: PropTypes.func, - onDelete: PropTypes.func, + simulationId: PropTypes.number.isRequired, + onViewUsers: PropTypes.func, + onDelete: PropTypes.func }; export default SimulationActionButtons; diff --git a/src/components/simulations/SimulationAuthList.js b/src/components/simulations/SimulationAuthList.js index 27b141fe..f29dc96d 100644 --- a/src/components/simulations/SimulationAuthList.js +++ b/src/components/simulations/SimulationAuthList.js @@ -1,38 +1,43 @@ -import PropTypes from 'prop-types'; -import React from 'react'; +import PropTypes from "prop-types"; +import React from "react"; import Shapes from "../../shapes/index"; import SimulationAuthRow from "./SimulationAuthRow"; -const SimulationAuthList = ({authorizations}) => { - return ( - <div className="vertically-expanding-container"> - {authorizations.length === 0 ? - <div className="alert alert-info"> - <span className="info-icon fa fa-question-circle mr-2"/> - <strong>No simulations here yet...</strong> Add some with the 'New Simulation' button! - </div> : - <table className="table table-striped"> - <thead> - <tr> - <th>Simulation name</th> - <th>Last edited</th> - <th>Access rights</th> - <th/> - </tr> - </thead> - <tbody> - {authorizations.map(authorization => ( - <SimulationAuthRow simulationAuth={authorization} key={authorization.simulation.id}/> - ))} - </tbody> - </table> - } +const SimulationAuthList = ({ authorizations }) => { + return ( + <div className="vertically-expanding-container"> + {authorizations.length === 0 ? ( + <div className="alert alert-info"> + <span className="info-icon fa fa-question-circle mr-2" /> + <strong>No simulations here yet...</strong> Add some with the 'New + Simulation' button! </div> - ); + ) : ( + <table className="table table-striped"> + <thead> + <tr> + <th>Simulation name</th> + <th>Last edited</th> + <th>Access rights</th> + <th /> + </tr> + </thead> + <tbody> + {authorizations.map(authorization => ( + <SimulationAuthRow + simulationAuth={authorization} + key={authorization.simulation.id} + /> + ))} + </tbody> + </table> + )} + </div> + ); }; SimulationAuthList.propTypes = { - authorizations: PropTypes.arrayOf(Shapes.Authorization).isRequired, + authorizations: PropTypes.arrayOf(Shapes.Authorization).isRequired }; export default SimulationAuthList; diff --git a/src/components/simulations/SimulationAuthRow.js b/src/components/simulations/SimulationAuthRow.js index 5f452f3e..b638fbce 100644 --- a/src/components/simulations/SimulationAuthRow.js +++ b/src/components/simulations/SimulationAuthRow.js @@ -1,28 +1,32 @@ -import classNames from 'classnames'; -import React from 'react'; +import classNames from "classnames"; +import React from "react"; import SimulationActions from "../../containers/simulations/SimulationActions"; import Shapes from "../../shapes/index"; -import {AUTH_DESCRIPTION_MAP, AUTH_ICON_MAP} from "../../util/authorizations"; -import {parseAndFormatDateTime} from "../../util/date-time"; +import { AUTH_DESCRIPTION_MAP, AUTH_ICON_MAP } from "../../util/authorizations"; +import { parseAndFormatDateTime } from "../../util/date-time"; -const SimulationAuthRow = ({simulationAuth}) => ( - <tr> - <td className="pt-3"> - {simulationAuth.simulation.name} - </td> - <td className="pt-3"> - {parseAndFormatDateTime(simulationAuth.simulation.datetimeLastEdited)} - </td> - <td className="pt-3"> - <span className={classNames("fa", "fa-" + AUTH_ICON_MAP[simulationAuth.authorizationLevel], "mr-2")}/> - {AUTH_DESCRIPTION_MAP[simulationAuth.authorizationLevel]} - </td> - <SimulationActions simulationId={simulationAuth.simulation.id}/> - </tr> +const SimulationAuthRow = ({ simulationAuth }) => ( + <tr> + <td className="pt-3">{simulationAuth.simulation.name}</td> + <td className="pt-3"> + {parseAndFormatDateTime(simulationAuth.simulation.datetimeLastEdited)} + </td> + <td className="pt-3"> + <span + className={classNames( + "fa", + "fa-" + AUTH_ICON_MAP[simulationAuth.authorizationLevel], + "mr-2" + )} + /> + {AUTH_DESCRIPTION_MAP[simulationAuth.authorizationLevel]} + </td> + <SimulationActions simulationId={simulationAuth.simulation.id} /> + </tr> ); SimulationAuthRow.propTypes = { - simulationAuth: Shapes.Authorization.isRequired, + simulationAuth: Shapes.Authorization.isRequired }; export default SimulationAuthRow; diff --git a/src/containers/app/map/DatacenterContainer.js b/src/containers/app/map/DatacenterContainer.js index 6859f2d8..125739f3 100644 --- a/src/containers/app/map/DatacenterContainer.js +++ b/src/containers/app/map/DatacenterContainer.js @@ -1,19 +1,17 @@ -import {connect} from "react-redux"; +import { connect } from "react-redux"; import DatacenterGroup from "../../../components/app/map/groups/DatacenterGroup"; const mapStateToProps = state => { - if (state.currentDatacenterId === -1) { - return {}; - } + if (state.currentDatacenterId === -1) { + return {}; + } - return { - datacenter: state.objects.datacenter[state.currentDatacenterId], - interactionLevel: state.interactionLevel, - }; + return { + datacenter: state.objects.datacenter[state.currentDatacenterId], + interactionLevel: state.interactionLevel + }; }; -const DatacenterContainer = connect( - mapStateToProps -)(DatacenterGroup); +const DatacenterContainer = connect(mapStateToProps)(DatacenterGroup); export default DatacenterContainer; diff --git a/src/containers/app/map/GrayContainer.js b/src/containers/app/map/GrayContainer.js index a22ef3c8..d215bf6c 100644 --- a/src/containers/app/map/GrayContainer.js +++ b/src/containers/app/map/GrayContainer.js @@ -1,16 +1,13 @@ -import {connect} from "react-redux"; -import {goDownOneInteractionLevel} from "../../../actions/interaction-level"; +import { connect } from "react-redux"; +import { goDownOneInteractionLevel } from "../../../actions/interaction-level"; import GrayLayer from "../../../components/app/map/elements/GrayLayer"; const mapDispatchToProps = dispatch => { - return { - onClick: () => dispatch(goDownOneInteractionLevel()) - }; + return { + onClick: () => dispatch(goDownOneInteractionLevel()) + }; }; -const GrayContainer = connect( - undefined, - mapDispatchToProps -)(GrayLayer); +const GrayContainer = connect(undefined, mapDispatchToProps)(GrayLayer); export default GrayContainer; diff --git a/src/containers/app/map/MapStage.js b/src/containers/app/map/MapStage.js index 32bde27c..a8467171 100644 --- a/src/containers/app/map/MapStage.js +++ b/src/containers/app/map/MapStage.js @@ -1,25 +1,31 @@ -import {connect} from "react-redux"; -import {setMapDimensions, setMapPositionWithBoundsCheck, zoomInOnPosition} from "../../../actions/map"; +import { connect } from "react-redux"; +import { + setMapDimensions, + setMapPositionWithBoundsCheck, + zoomInOnPosition +} from "../../../actions/map"; import MapStageComponent from "../../../components/app/map/MapStageComponent"; const mapStateToProps = state => { - return { - mapPosition: state.map.position, - mapDimensions: state.map.dimensions, - }; + return { + mapPosition: state.map.position, + mapDimensions: state.map.dimensions + }; }; const mapDispatchToProps = dispatch => { - return { - zoomInOnPosition: (zoomIn, x, y) => dispatch(zoomInOnPosition(zoomIn, x, y)), - setMapPositionWithBoundsCheck: (x, y) => dispatch(setMapPositionWithBoundsCheck(x, y)), - setMapDimensions: (width, height) => dispatch(setMapDimensions(width, height)), - }; + return { + zoomInOnPosition: (zoomIn, x, y) => + dispatch(zoomInOnPosition(zoomIn, x, y)), + setMapPositionWithBoundsCheck: (x, y) => + dispatch(setMapPositionWithBoundsCheck(x, y)), + setMapDimensions: (width, height) => + dispatch(setMapDimensions(width, height)) + }; }; -const MapStage = connect( - mapStateToProps, - mapDispatchToProps -)(MapStageComponent); +const MapStage = connect(mapStateToProps, mapDispatchToProps)( + MapStageComponent +); export default MapStage; diff --git a/src/containers/app/map/RackContainer.js b/src/containers/app/map/RackContainer.js index 38f01efc..365bb062 100644 --- a/src/containers/app/map/RackContainer.js +++ b/src/containers/app/map/RackContainer.js @@ -1,26 +1,30 @@ -import {connect} from "react-redux"; +import { connect } from "react-redux"; import RackGroup from "../../../components/app/map/groups/RackGroup"; -import {getStateLoad} from "../../../util/simulation-load"; +import { getStateLoad } from "../../../util/simulation-load"; const mapStateToProps = (state, ownProps) => { - const inSimulation = state.currentExperimentId !== -1; + const inSimulation = state.currentExperimentId !== -1; - let rackLoad = undefined; - if (inSimulation) { - if (state.states.rack[state.currentTick] && state.states.rack[state.currentTick][ownProps.tile.objectId]) { - rackLoad = getStateLoad(state.loadMetric, state.states.rack[state.currentTick][ownProps.tile.objectId]); - } + let rackLoad = undefined; + if (inSimulation) { + if ( + state.states.rack[state.currentTick] && + state.states.rack[state.currentTick][ownProps.tile.objectId] + ) { + rackLoad = getStateLoad( + state.loadMetric, + state.states.rack[state.currentTick][ownProps.tile.objectId] + ); } + } - return { - interactionLevel: state.interactionLevel, - inSimulation, - rackLoad, - }; + return { + interactionLevel: state.interactionLevel, + inSimulation, + rackLoad + }; }; -const RackContainer = connect( - mapStateToProps -)(RackGroup); +const RackContainer = connect(mapStateToProps)(RackGroup); export default RackContainer; diff --git a/src/containers/app/map/RackEnergyFillContainer.js b/src/containers/app/map/RackEnergyFillContainer.js index d83dc386..0b7921d9 100644 --- a/src/containers/app/map/RackEnergyFillContainer.js +++ b/src/containers/app/map/RackEnergyFillContainer.js @@ -1,28 +1,40 @@ -import {connect} from "react-redux"; +import { connect } from "react-redux"; import RackFillBar from "../../../components/app/map/elements/RackFillBar"; const mapStateToProps = (state, ownProps) => { - let energyConsumptionTotal = 0; - const rack = state.objects.rack[state.objects.tile[ownProps.tileId].objectId]; - const machineIds = rack.machineIds; - machineIds.forEach(machineId => { - if (machineId !== null) { - const machine = state.objects.machine[machineId]; - machine.cpuIds.forEach(id => energyConsumptionTotal += state.objects.cpu[id].energyConsumptionW); - machine.gpuIds.forEach(id => energyConsumptionTotal += state.objects.gpu[id].energyConsumptionW); - machine.memoryIds.forEach(id => energyConsumptionTotal += state.objects.memory[id].energyConsumptionW); - machine.storageIds.forEach(id => energyConsumptionTotal += state.objects.storage[id].energyConsumptionW); - } - }); + let energyConsumptionTotal = 0; + const rack = state.objects.rack[state.objects.tile[ownProps.tileId].objectId]; + const machineIds = rack.machineIds; + machineIds.forEach(machineId => { + if (machineId !== null) { + const machine = state.objects.machine[machineId]; + machine.cpuIds.forEach( + id => + (energyConsumptionTotal += state.objects.cpu[id].energyConsumptionW) + ); + machine.gpuIds.forEach( + id => + (energyConsumptionTotal += state.objects.gpu[id].energyConsumptionW) + ); + machine.memoryIds.forEach( + id => + (energyConsumptionTotal += + state.objects.memory[id].energyConsumptionW) + ); + machine.storageIds.forEach( + id => + (energyConsumptionTotal += + state.objects.storage[id].energyConsumptionW) + ); + } + }); - return { - type: "energy", - fillFraction: Math.min(1, energyConsumptionTotal / rack.powerCapacityW), - }; + return { + type: "energy", + fillFraction: Math.min(1, energyConsumptionTotal / rack.powerCapacityW) + }; }; -const RackSpaceFillContainer = connect( - mapStateToProps -)(RackFillBar); +const RackSpaceFillContainer = connect(mapStateToProps)(RackFillBar); export default RackSpaceFillContainer; diff --git a/src/containers/app/map/RackSpaceFillContainer.js b/src/containers/app/map/RackSpaceFillContainer.js index bbcf4e2e..cc4d1251 100644 --- a/src/containers/app/map/RackSpaceFillContainer.js +++ b/src/containers/app/map/RackSpaceFillContainer.js @@ -1,16 +1,16 @@ -import {connect} from "react-redux"; +import { connect } from "react-redux"; import RackFillBar from "../../../components/app/map/elements/RackFillBar"; const mapStateToProps = (state, ownProps) => { - const machineIds = state.objects.rack[state.objects.tile[ownProps.tileId].objectId].machineIds; - return { - type: "space", - fillFraction: machineIds.filter(id => id !== null).length / machineIds.length, - }; + const machineIds = + state.objects.rack[state.objects.tile[ownProps.tileId].objectId].machineIds; + return { + type: "space", + fillFraction: + machineIds.filter(id => id !== null).length / machineIds.length + }; }; -const RackSpaceFillContainer = connect( - mapStateToProps -)(RackFillBar); +const RackSpaceFillContainer = connect(mapStateToProps)(RackFillBar); export default RackSpaceFillContainer; diff --git a/src/containers/app/map/RoomContainer.js b/src/containers/app/map/RoomContainer.js index c8e146d6..b83c7fa0 100644 --- a/src/containers/app/map/RoomContainer.js +++ b/src/containers/app/map/RoomContainer.js @@ -1,24 +1,21 @@ -import {connect} from "react-redux"; -import {goFromBuildingToRoom} from "../../../actions/interaction-level"; +import { connect } from "react-redux"; +import { goFromBuildingToRoom } from "../../../actions/interaction-level"; import RoomGroup from "../../../components/app/map/groups/RoomGroup"; const mapStateToProps = (state, ownProps) => { - return { - interactionLevel: state.interactionLevel, - currentRoomInConstruction: state.construction.currentRoomInConstruction, - room: state.objects.room[ownProps.roomId], - }; + return { + interactionLevel: state.interactionLevel, + currentRoomInConstruction: state.construction.currentRoomInConstruction, + room: state.objects.room[ownProps.roomId] + }; }; const mapDispatchToProps = (dispatch, ownProps) => { - return { - onClick: () => dispatch(goFromBuildingToRoom(ownProps.roomId)), - }; + return { + onClick: () => dispatch(goFromBuildingToRoom(ownProps.roomId)) + }; }; -const RoomContainer = connect( - mapStateToProps, - mapDispatchToProps -)(RoomGroup); +const RoomContainer = connect(mapStateToProps, mapDispatchToProps)(RoomGroup); export default RoomContainer; diff --git a/src/containers/app/map/TileContainer.js b/src/containers/app/map/TileContainer.js index 299016d1..9e179924 100644 --- a/src/containers/app/map/TileContainer.js +++ b/src/containers/app/map/TileContainer.js @@ -1,40 +1,43 @@ -import {connect} from "react-redux"; -import {goFromRoomToRack} from "../../../actions/interaction-level"; +import { connect } from "react-redux"; +import { goFromRoomToRack } from "../../../actions/interaction-level"; import TileGroup from "../../../components/app/map/groups/TileGroup"; -import {getStateLoad} from "../../../util/simulation-load"; +import { getStateLoad } from "../../../util/simulation-load"; const mapStateToProps = (state, ownProps) => { - const tile = state.objects.tile[ownProps.tileId]; - const inSimulation = state.currentExperimentId !== -1; + const tile = state.objects.tile[ownProps.tileId]; + const inSimulation = state.currentExperimentId !== -1; - let roomLoad = undefined; - if (inSimulation) { - if (state.states.room[state.currentTick] && state.states.room[state.currentTick][tile.roomId]) { - roomLoad = getStateLoad(state.loadMetric, state.states.room[state.currentTick][tile.roomId]); - } + let roomLoad = undefined; + if (inSimulation) { + if ( + state.states.room[state.currentTick] && + state.states.room[state.currentTick][tile.roomId] + ) { + roomLoad = getStateLoad( + state.loadMetric, + state.states.room[state.currentTick][tile.roomId] + ); } + } - return { - interactionLevel: state.interactionLevel, - tile, - inSimulation, - roomLoad, - }; + return { + interactionLevel: state.interactionLevel, + tile, + inSimulation, + roomLoad + }; }; const mapDispatchToProps = dispatch => { - return { - onClick: tile => { - if (tile.objectType) { - dispatch(goFromRoomToRack(tile.id)) - } - } - }; + return { + onClick: tile => { + if (tile.objectType) { + dispatch(goFromRoomToRack(tile.id)); + } + } + }; }; -const TileContainer = connect( - mapStateToProps, - mapDispatchToProps -)(TileGroup); +const TileContainer = connect(mapStateToProps, mapDispatchToProps)(TileGroup); export default TileContainer; diff --git a/src/containers/app/map/WallContainer.js b/src/containers/app/map/WallContainer.js index 0ce8875a..38192b05 100644 --- a/src/containers/app/map/WallContainer.js +++ b/src/containers/app/map/WallContainer.js @@ -1,14 +1,14 @@ -import {connect} from "react-redux"; +import { connect } from "react-redux"; import WallGroup from "../../../components/app/map/groups/WallGroup"; const mapStateToProps = (state, ownProps) => { - return { - tiles: state.objects.room[ownProps.roomId].tileIds.map(tileId => state.objects.tile[tileId]), - }; + return { + tiles: state.objects.room[ownProps.roomId].tileIds.map( + tileId => state.objects.tile[tileId] + ) + }; }; -const WallContainer = connect( - mapStateToProps -)(WallGroup); +const WallContainer = connect(mapStateToProps)(WallGroup); export default WallContainer; diff --git a/src/containers/app/map/controls/ScaleIndicatorContainer.js b/src/containers/app/map/controls/ScaleIndicatorContainer.js index 12596c9c..f075cde5 100644 --- a/src/containers/app/map/controls/ScaleIndicatorContainer.js +++ b/src/containers/app/map/controls/ScaleIndicatorContainer.js @@ -1,14 +1,14 @@ -import {connect} from "react-redux"; +import { connect } from "react-redux"; import ScaleIndicatorComponent from "../../../../components/app/map/controls/ScaleIndicatorComponent"; const mapStateToProps = state => { - return { - scale: state.map.scale, - }; + return { + scale: state.map.scale + }; }; -const ScaleIndicatorContainer = connect( - mapStateToProps -)(ScaleIndicatorComponent); +const ScaleIndicatorContainer = connect(mapStateToProps)( + ScaleIndicatorComponent +); export default ScaleIndicatorContainer; diff --git a/src/containers/app/map/controls/ZoomControlContainer.js b/src/containers/app/map/controls/ZoomControlContainer.js index fd0e7563..50910bd6 100644 --- a/src/containers/app/map/controls/ZoomControlContainer.js +++ b/src/containers/app/map/controls/ZoomControlContainer.js @@ -1,22 +1,21 @@ -import {connect} from "react-redux"; -import {zoomInOnCenter} from "../../../../actions/map"; +import { connect } from "react-redux"; +import { zoomInOnCenter } from "../../../../actions/map"; import ZoomControlComponent from "../../../../components/app/map/controls/ZoomControlComponent"; const mapStateToProps = state => { - return { - mapScale: state.map.scale, - }; + return { + mapScale: state.map.scale + }; }; const mapDispatchToProps = dispatch => { - return { - zoomInOnCenter: zoomIn => dispatch(zoomInOnCenter(zoomIn)), - }; + return { + zoomInOnCenter: zoomIn => dispatch(zoomInOnCenter(zoomIn)) + }; }; -const ZoomControlContainer = connect( - mapStateToProps, - mapDispatchToProps -)(ZoomControlComponent); +const ZoomControlContainer = connect(mapStateToProps, mapDispatchToProps)( + ZoomControlComponent +); export default ZoomControlContainer; diff --git a/src/containers/app/map/layers/MapLayer.js b/src/containers/app/map/layers/MapLayer.js index ea3a0b57..cf971350 100644 --- a/src/containers/app/map/layers/MapLayer.js +++ b/src/containers/app/map/layers/MapLayer.js @@ -1,15 +1,13 @@ -import {connect} from "react-redux"; +import { connect } from "react-redux"; import MapLayerComponent from "../../../../components/app/map/layers/MapLayerComponent"; const mapStateToProps = state => { - return { - mapPosition: state.map.position, - mapScale: state.map.scale, - }; + return { + mapPosition: state.map.position, + mapScale: state.map.scale + }; }; -const MapLayer = connect( - mapStateToProps -)(MapLayerComponent); +const MapLayer = connect(mapStateToProps)(MapLayerComponent); export default MapLayer; diff --git a/src/containers/app/map/layers/ObjectHoverLayer.js b/src/containers/app/map/layers/ObjectHoverLayer.js index d905fd42..9b28575e 100644 --- a/src/containers/app/map/layers/ObjectHoverLayer.js +++ b/src/containers/app/map/layers/ObjectHoverLayer.js @@ -1,37 +1,37 @@ -import {connect} from "react-redux"; -import {addRackToTile} from "../../../../actions/topology/room"; +import { connect } from "react-redux"; +import { addRackToTile } from "../../../../actions/topology/room"; import ObjectHoverLayerComponent from "../../../../components/app/map/layers/ObjectHoverLayerComponent"; -import {findTileWithPosition} from "../../../../util/tile-calculations"; +import { findTileWithPosition } from "../../../../util/tile-calculations"; const mapStateToProps = state => { - return { - mapPosition: state.map.position, - mapScale: state.map.scale, - isEnabled: () => state.construction.inRackConstructionMode, - isValid: (x, y) => { - if (state.interactionLevel.mode !== "ROOM") { - return false; - } + return { + mapPosition: state.map.position, + mapScale: state.map.scale, + isEnabled: () => state.construction.inRackConstructionMode, + isValid: (x, y) => { + if (state.interactionLevel.mode !== "ROOM") { + return false; + } - const currentRoom = state.objects.room[state.interactionLevel.roomId]; - const tiles = currentRoom.tileIds.map(tileId => state.objects.tile[tileId]); - const tile = findTileWithPosition(tiles, x, y); + const currentRoom = state.objects.room[state.interactionLevel.roomId]; + const tiles = currentRoom.tileIds.map( + tileId => state.objects.tile[tileId] + ); + const tile = findTileWithPosition(tiles, x, y); - return !(tile === null || tile.objectType); - - }, - }; + return !(tile === null || tile.objectType); + } + }; }; const mapDispatchToProps = dispatch => { - return { - onClick: (x, y) => dispatch(addRackToTile(x, y)), - }; + return { + onClick: (x, y) => dispatch(addRackToTile(x, y)) + }; }; -const ObjectHoverLayer = connect( - mapStateToProps, - mapDispatchToProps -)(ObjectHoverLayerComponent); +const ObjectHoverLayer = connect(mapStateToProps, mapDispatchToProps)( + ObjectHoverLayerComponent +); export default ObjectHoverLayer; diff --git a/src/containers/app/map/layers/RoomHoverLayer.js b/src/containers/app/map/layers/RoomHoverLayer.js index fbcbed7e..910d47fb 100644 --- a/src/containers/app/map/layers/RoomHoverLayer.js +++ b/src/containers/app/map/layers/RoomHoverLayer.js @@ -1,50 +1,59 @@ -import {connect} from "react-redux"; -import {toggleTileAtLocation} from "../../../../actions/topology/building"; +import { connect } from "react-redux"; +import { toggleTileAtLocation } from "../../../../actions/topology/building"; import RoomHoverLayerComponent from "../../../../components/app/map/layers/RoomHoverLayerComponent"; import { - deriveValidNextTilePositions, - findPositionInPositions, - findPositionInRooms + deriveValidNextTilePositions, + findPositionInPositions, + findPositionInRooms } from "../../../../util/tile-calculations"; const mapStateToProps = state => { - return { - mapPosition: state.map.position, - mapScale: state.map.scale, - isEnabled: () => state.construction.currentRoomInConstruction !== -1, - isValid: (x, y) => { - if (state.interactionLevel.mode !== "BUILDING") { - return false; - } + return { + mapPosition: state.map.position, + mapScale: state.map.scale, + isEnabled: () => state.construction.currentRoomInConstruction !== -1, + isValid: (x, y) => { + if (state.interactionLevel.mode !== "BUILDING") { + return false; + } - const newRoom = Object.assign({}, state.objects.room[state.construction.currentRoomInConstruction]); - const oldRooms = Object.keys(state.objects.room) - .map(id => Object.assign({}, state.objects.room[id])) - .filter(room => state.objects.datacenter[state.currentDatacenterId].roomIds.indexOf(room.id) !== -1 - && room.id !== state.construction.currentRoomInConstruction); + const newRoom = Object.assign( + {}, + state.objects.room[state.construction.currentRoomInConstruction] + ); + const oldRooms = Object.keys(state.objects.room) + .map(id => Object.assign({}, state.objects.room[id])) + .filter( + room => + state.objects.datacenter[state.currentDatacenterId].roomIds.indexOf( + room.id + ) !== -1 && room.id !== state.construction.currentRoomInConstruction + ); - [...oldRooms, newRoom].forEach(room => { - room.tiles = room.tileIds.map(tileId => state.objects.tile[tileId]); - }); - if (newRoom.tileIds.length === 0) { - return findPositionInRooms(oldRooms, x, y) === -1; - } + [...oldRooms, newRoom].forEach(room => { + room.tiles = room.tileIds.map(tileId => state.objects.tile[tileId]); + }); + if (newRoom.tileIds.length === 0) { + return findPositionInRooms(oldRooms, x, y) === -1; + } - const validNextPositions = deriveValidNextTilePositions(oldRooms, newRoom.tiles); - return findPositionInPositions(validNextPositions, x, y) !== -1; - }, - }; + const validNextPositions = deriveValidNextTilePositions( + oldRooms, + newRoom.tiles + ); + return findPositionInPositions(validNextPositions, x, y) !== -1; + } + }; }; const mapDispatchToProps = dispatch => { - return { - onClick: (x, y) => dispatch(toggleTileAtLocation(x, y)), - }; + return { + onClick: (x, y) => dispatch(toggleTileAtLocation(x, y)) + }; }; -const RoomHoverLayer = connect( - mapStateToProps, - mapDispatchToProps -)(RoomHoverLayerComponent); +const RoomHoverLayer = connect(mapStateToProps, mapDispatchToProps)( + RoomHoverLayerComponent +); export default RoomHoverLayer; diff --git a/src/containers/app/sidebars/elements/LoadBarContainer.js b/src/containers/app/sidebars/elements/LoadBarContainer.js index ccaf1729..2e637f9a 100644 --- a/src/containers/app/sidebars/elements/LoadBarContainer.js +++ b/src/containers/app/sidebars/elements/LoadBarContainer.js @@ -1,25 +1,32 @@ -import {connect} from "react-redux"; +import { connect } from "react-redux"; import LoadBarComponent from "../../../../components/app/sidebars/elements/LoadBarComponent"; -import {getStateLoad} from "../../../../util/simulation-load"; +import { getStateLoad } from "../../../../util/simulation-load"; const mapStateToProps = (state, ownProps) => { - let percent = 0; - let enabled = false; + let percent = 0; + let enabled = false; - const objectStates = state.states[ownProps.objectType]; - if (objectStates[state.currentTick] && objectStates[state.currentTick][ownProps.objectId]) { - percent = Math.floor(100 * getStateLoad(state.loadMetric, objectStates[state.currentTick][ownProps.objectId])); - enabled = true; - } + const objectStates = state.states[ownProps.objectType]; + if ( + objectStates[state.currentTick] && + objectStates[state.currentTick][ownProps.objectId] + ) { + percent = Math.floor( + 100 * + getStateLoad( + state.loadMetric, + objectStates[state.currentTick][ownProps.objectId] + ) + ); + enabled = true; + } - return { - percent, - enabled - }; + return { + percent, + enabled + }; }; -const LoadBarContainer = connect( - mapStateToProps -)(LoadBarComponent); +const LoadBarContainer = connect(mapStateToProps)(LoadBarComponent); export default LoadBarContainer; diff --git a/src/containers/app/sidebars/elements/LoadChartContainer.js b/src/containers/app/sidebars/elements/LoadChartContainer.js index 227a4fd5..57bfec38 100644 --- a/src/containers/app/sidebars/elements/LoadChartContainer.js +++ b/src/containers/app/sidebars/elements/LoadChartContainer.js @@ -1,27 +1,31 @@ -import {connect} from "react-redux"; +import { connect } from "react-redux"; import LoadChartComponent from "../../../../components/app/sidebars/elements/LoadChartComponent"; -import {getStateLoad} from "../../../../util/simulation-load"; +import { getStateLoad } from "../../../../util/simulation-load"; const mapStateToProps = (state, ownProps) => { - const data = []; + const data = []; - if (state.lastSimulatedTick !== -1) { - const objectStates = state.states[ownProps.objectType]; - Object.keys(objectStates).forEach(tick => { - if (objectStates[tick][ownProps.objectId]) { - data.push({x: tick, y: getStateLoad(state.loadMetric, objectStates[tick][ownProps.objectId])}); - } + if (state.lastSimulatedTick !== -1) { + const objectStates = state.states[ownProps.objectType]; + Object.keys(objectStates).forEach(tick => { + if (objectStates[tick][ownProps.objectId]) { + data.push({ + x: tick, + y: getStateLoad( + state.loadMetric, + objectStates[tick][ownProps.objectId] + ) }); - } + } + }); + } - return { - data, - currentTick: state.currentTick, - }; + return { + data, + currentTick: state.currentTick + }; }; -const LoadChartContainer = connect( - mapStateToProps -)(LoadChartComponent); +const LoadChartContainer = connect(mapStateToProps)(LoadChartComponent); export default LoadChartContainer; diff --git a/src/containers/app/sidebars/simulation/ExperimentMetadataContainer.js b/src/containers/app/sidebars/simulation/ExperimentMetadataContainer.js index a5e403ce..25a0d9e9 100644 --- a/src/containers/app/sidebars/simulation/ExperimentMetadataContainer.js +++ b/src/containers/app/sidebars/simulation/ExperimentMetadataContainer.js @@ -1,29 +1,38 @@ -import {connect} from "react-redux"; +import { connect } from "react-redux"; import ExperimentMetadataComponent from "../../../../components/app/sidebars/simulation/ExperimentMetadataComponent"; const mapStateToProps = state => { - if (!state.objects.experiment[state.currentExperimentId]) { - return { - experimentName: "Loading experiment", - pathName: "", - traceName: "", - schedulerName: "", - } - } - - const path = state.objects.path[state.objects.experiment[state.currentExperimentId].pathId]; - const pathName = path.name ? path.name : "Path " + path.id; - + if (!state.objects.experiment[state.currentExperimentId]) { return { - experimentName: state.objects.experiment[state.currentExperimentId].name, - pathName, - traceName: state.objects.trace[state.objects.experiment[state.currentExperimentId].traceId].name, - schedulerName: state.objects.scheduler[state.objects.experiment[state.currentExperimentId].schedulerName].name, + experimentName: "Loading experiment", + pathName: "", + traceName: "", + schedulerName: "" }; + } + + const path = + state.objects.path[ + state.objects.experiment[state.currentExperimentId].pathId + ]; + const pathName = path.name ? path.name : "Path " + path.id; + + return { + experimentName: state.objects.experiment[state.currentExperimentId].name, + pathName, + traceName: + state.objects.trace[ + state.objects.experiment[state.currentExperimentId].traceId + ].name, + schedulerName: + state.objects.scheduler[ + state.objects.experiment[state.currentExperimentId].schedulerName + ].name + }; }; -const ExperimentMetadataContainer = connect( - mapStateToProps -)(ExperimentMetadataComponent); +const ExperimentMetadataContainer = connect(mapStateToProps)( + ExperimentMetadataComponent +); export default ExperimentMetadataContainer; diff --git a/src/containers/app/sidebars/simulation/LoadMetricContainer.js b/src/containers/app/sidebars/simulation/LoadMetricContainer.js index 5ce3542c..0c66b582 100644 --- a/src/containers/app/sidebars/simulation/LoadMetricContainer.js +++ b/src/containers/app/sidebars/simulation/LoadMetricContainer.js @@ -1,14 +1,12 @@ -import {connect} from "react-redux"; +import { connect } from "react-redux"; import LoadMetricComponent from "../../../../components/app/sidebars/simulation/LoadMetricComponent"; const mapStateToProps = state => { - return { - loadMetric: state.loadMetric, - } + return { + loadMetric: state.loadMetric + }; }; -const LoadMetricContainer = connect( - mapStateToProps -)(LoadMetricComponent); +const LoadMetricContainer = connect(mapStateToProps)(LoadMetricComponent); export default LoadMetricContainer; diff --git a/src/containers/app/sidebars/simulation/TaskContainer.js b/src/containers/app/sidebars/simulation/TaskContainer.js index 357bd7ed..093d4266 100644 --- a/src/containers/app/sidebars/simulation/TaskContainer.js +++ b/src/containers/app/sidebars/simulation/TaskContainer.js @@ -1,23 +1,26 @@ -import {connect} from "react-redux"; +import { connect } from "react-redux"; import TaskComponent from "../../../../components/app/sidebars/simulation/TaskComponent"; const mapStateToProps = (state, ownProps) => { - let flopsLeft = state.objects.task[ownProps.taskId].totalFlopCount; + let flopsLeft = state.objects.task[ownProps.taskId].totalFlopCount; - if (state.states.task[state.currentTick] && state.states.task[state.currentTick][ownProps.taskId]) { - flopsLeft = state.states.task[state.currentTick][ownProps.taskId].flopsLeft; - } else if (state.objects.task[ownProps.taskId].startTick < state.currentTick) { - flopsLeft = 0; - } + if ( + state.states.task[state.currentTick] && + state.states.task[state.currentTick][ownProps.taskId] + ) { + flopsLeft = state.states.task[state.currentTick][ownProps.taskId].flopsLeft; + } else if ( + state.objects.task[ownProps.taskId].startTick < state.currentTick + ) { + flopsLeft = 0; + } - return { - task: state.objects.task[ownProps.taskId], - flopsLeft, - }; + return { + task: state.objects.task[ownProps.taskId], + flopsLeft + }; }; -const TaskContainer = connect( - mapStateToProps -)(TaskComponent); +const TaskContainer = connect(mapStateToProps)(TaskComponent); export default TaskContainer; diff --git a/src/containers/app/sidebars/simulation/TraceContainer.js b/src/containers/app/sidebars/simulation/TraceContainer.js index 7955f313..682b6cc9 100644 --- a/src/containers/app/sidebars/simulation/TraceContainer.js +++ b/src/containers/app/sidebars/simulation/TraceContainer.js @@ -1,22 +1,25 @@ -import {connect} from "react-redux"; +import { connect } from "react-redux"; import TraceComponent from "../../../../components/app/sidebars/simulation/TraceComponent"; const mapStateToProps = state => { - if (!state.objects.experiment[state.currentExperimentId] || - !state.objects.trace[state.objects.experiment[state.currentExperimentId].traceId].jobIds) { - return { - jobs: [] - }; - } - + if ( + !state.objects.experiment[state.currentExperimentId] || + !state.objects.trace[ + state.objects.experiment[state.currentExperimentId].traceId + ].jobIds + ) { return { - jobs: state.objects.trace[state.objects.experiment[state.currentExperimentId].traceId].jobIds - .map(id => state.objects.job[id]), + jobs: [] }; + } + + return { + jobs: state.objects.trace[ + state.objects.experiment[state.currentExperimentId].traceId + ].jobIds.map(id => state.objects.job[id]) + }; }; -const TraceContainer = connect( - mapStateToProps -)(TraceComponent); +const TraceContainer = connect(mapStateToProps)(TraceComponent); export default TraceContainer; diff --git a/src/containers/app/sidebars/topology/TopologySidebar.js b/src/containers/app/sidebars/topology/TopologySidebar.js index ac59f5cc..31c902fc 100644 --- a/src/containers/app/sidebars/topology/TopologySidebar.js +++ b/src/containers/app/sidebars/topology/TopologySidebar.js @@ -1,14 +1,12 @@ -import {connect} from "react-redux"; +import { connect } from "react-redux"; import TopologySidebarComponent from "../../../../components/app/sidebars/topology/TopologySidebarComponent"; const mapStateToProps = state => { - return { - interactionLevel: state.interactionLevel - }; + return { + interactionLevel: state.interactionLevel + }; }; -const TopologySidebar = connect( - mapStateToProps -)(TopologySidebarComponent); +const TopologySidebar = connect(mapStateToProps)(TopologySidebarComponent); export default TopologySidebar; diff --git a/src/containers/app/sidebars/topology/building/BuildingSidebarContainer.js b/src/containers/app/sidebars/topology/building/BuildingSidebarContainer.js index ce7a308a..da24b8f0 100644 --- a/src/containers/app/sidebars/topology/building/BuildingSidebarContainer.js +++ b/src/containers/app/sidebars/topology/building/BuildingSidebarContainer.js @@ -1,14 +1,14 @@ -import {connect} from "react-redux"; +import { connect } from "react-redux"; import BuildingSidebarComponent from "../../../../../components/app/sidebars/topology/building/BuildingSidebarComponent"; const mapStateToProps = state => { - return { - inSimulation: state.currentExperimentId !== -1 - }; + return { + inSimulation: state.currentExperimentId !== -1 + }; }; -const BuildingSidebarContainer = connect( - mapStateToProps -)(BuildingSidebarComponent); +const BuildingSidebarContainer = connect(mapStateToProps)( + BuildingSidebarComponent +); export default BuildingSidebarContainer; diff --git a/src/containers/app/sidebars/topology/building/NewRoomConstructionContainer.js b/src/containers/app/sidebars/topology/building/NewRoomConstructionContainer.js index 3ec1349b..bb64cbb4 100644 --- a/src/containers/app/sidebars/topology/building/NewRoomConstructionContainer.js +++ b/src/containers/app/sidebars/topology/building/NewRoomConstructionContainer.js @@ -1,28 +1,27 @@ -import {connect} from "react-redux"; +import { connect } from "react-redux"; import { - cancelNewRoomConstruction, - finishNewRoomConstruction, - startNewRoomConstruction + cancelNewRoomConstruction, + finishNewRoomConstruction, + startNewRoomConstruction } from "../../../../../actions/topology/building"; import StartNewRoomConstructionComponent from "../../../../../components/app/sidebars/topology/building/NewRoomConstructionComponent"; const mapStateToProps = state => { - return { - currentRoomInConstruction: state.construction.currentRoomInConstruction - }; + return { + currentRoomInConstruction: state.construction.currentRoomInConstruction + }; }; const mapDispatchToProps = dispatch => { - return { - onStart: () => dispatch(startNewRoomConstruction()), - onFinish: () => dispatch(finishNewRoomConstruction()), - onCancel: () => dispatch(cancelNewRoomConstruction()), - }; + return { + onStart: () => dispatch(startNewRoomConstruction()), + onFinish: () => dispatch(finishNewRoomConstruction()), + onCancel: () => dispatch(cancelNewRoomConstruction()) + }; }; -const NewRoomConstructionButton = connect( - mapStateToProps, - mapDispatchToProps -)(StartNewRoomConstructionComponent); +const NewRoomConstructionButton = connect(mapStateToProps, mapDispatchToProps)( + StartNewRoomConstructionComponent +); export default NewRoomConstructionButton; diff --git a/src/containers/app/sidebars/topology/machine/BackToRackContainer.js b/src/containers/app/sidebars/topology/machine/BackToRackContainer.js index f0ac9220..885c533d 100644 --- a/src/containers/app/sidebars/topology/machine/BackToRackContainer.js +++ b/src/containers/app/sidebars/topology/machine/BackToRackContainer.js @@ -1,16 +1,15 @@ -import {connect} from "react-redux"; -import {goDownOneInteractionLevel} from "../../../../../actions/interaction-level"; +import { connect } from "react-redux"; +import { goDownOneInteractionLevel } from "../../../../../actions/interaction-level"; import BackToRackComponent from "../../../../../components/app/sidebars/topology/machine/BackToRackComponent"; const mapDispatchToProps = dispatch => { - return { - onClick: () => dispatch(goDownOneInteractionLevel()), - }; + return { + onClick: () => dispatch(goDownOneInteractionLevel()) + }; }; -const BackToRackContainer = connect( - undefined, - mapDispatchToProps -)(BackToRackComponent); +const BackToRackContainer = connect(undefined, mapDispatchToProps)( + BackToRackComponent +); export default BackToRackContainer; diff --git a/src/containers/app/sidebars/topology/machine/DeleteMachineContainer.js b/src/containers/app/sidebars/topology/machine/DeleteMachineContainer.js index bfdde179..f42c8ba7 100644 --- a/src/containers/app/sidebars/topology/machine/DeleteMachineContainer.js +++ b/src/containers/app/sidebars/topology/machine/DeleteMachineContainer.js @@ -1,16 +1,15 @@ -import {connect} from "react-redux"; -import {openDeleteMachineModal} from "../../../../../actions/modals/topology"; +import { connect } from "react-redux"; +import { openDeleteMachineModal } from "../../../../../actions/modals/topology"; import DeleteMachineComponent from "../../../../../components/app/sidebars/topology/machine/DeleteMachineComponent"; const mapDispatchToProps = dispatch => { - return { - onClick: () => dispatch(openDeleteMachineModal()), - }; + return { + onClick: () => dispatch(openDeleteMachineModal()) + }; }; -const DeleteMachineContainer = connect( - undefined, - mapDispatchToProps -)(DeleteMachineComponent); +const DeleteMachineContainer = connect(undefined, mapDispatchToProps)( + DeleteMachineComponent +); export default DeleteMachineContainer; diff --git a/src/containers/app/sidebars/topology/machine/MachineNameContainer.js b/src/containers/app/sidebars/topology/machine/MachineNameContainer.js index 9d23dcb6..05d2bf80 100644 --- a/src/containers/app/sidebars/topology/machine/MachineNameContainer.js +++ b/src/containers/app/sidebars/topology/machine/MachineNameContainer.js @@ -1,14 +1,12 @@ -import {connect} from "react-redux"; +import { connect } from "react-redux"; import MachineNameComponent from "../../../../../components/app/sidebars/topology/machine/MachineNameComponent"; const mapStateToProps = state => { - return { - position: state.interactionLevel.position, - }; + return { + position: state.interactionLevel.position + }; }; -const MachineNameContainer = connect( - mapStateToProps -)(MachineNameComponent); +const MachineNameContainer = connect(mapStateToProps)(MachineNameComponent); export default MachineNameContainer; diff --git a/src/containers/app/sidebars/topology/machine/MachineSidebarContainer.js b/src/containers/app/sidebars/topology/machine/MachineSidebarContainer.js index 5c28248c..7729385e 100644 --- a/src/containers/app/sidebars/topology/machine/MachineSidebarContainer.js +++ b/src/containers/app/sidebars/topology/machine/MachineSidebarContainer.js @@ -1,16 +1,18 @@ -import {connect} from "react-redux"; +import { connect } from "react-redux"; import MachineSidebarComponent from "../../../../../components/app/sidebars/topology/machine/MachineSidebarComponent"; const mapStateToProps = state => { - return { - inSimulation: state.currentExperimentId !== -1, - machineId: state.objects.rack[state.objects.tile[state.interactionLevel.tileId].objectId] - .machineIds[state.interactionLevel.position - 1], - }; + return { + inSimulation: state.currentExperimentId !== -1, + machineId: + state.objects.rack[ + state.objects.tile[state.interactionLevel.tileId].objectId + ].machineIds[state.interactionLevel.position - 1] + }; }; -const MachineSidebarContainer = connect( - mapStateToProps -)(MachineSidebarComponent); +const MachineSidebarContainer = connect(mapStateToProps)( + MachineSidebarComponent +); export default MachineSidebarContainer; diff --git a/src/containers/app/sidebars/topology/machine/UnitAddContainer.js b/src/containers/app/sidebars/topology/machine/UnitAddContainer.js index f194ebcf..0e5a6073 100644 --- a/src/containers/app/sidebars/topology/machine/UnitAddContainer.js +++ b/src/containers/app/sidebars/topology/machine/UnitAddContainer.js @@ -1,22 +1,21 @@ -import {connect} from "react-redux"; -import {addUnit} from "../../../../../actions/topology/machine"; +import { connect } from "react-redux"; +import { addUnit } from "../../../../../actions/topology/machine"; import UnitAddComponent from "../../../../../components/app/sidebars/topology/machine/UnitAddComponent"; const mapStateToProps = (state, ownProps) => { - return { - units: Object.values(state.objects[ownProps.unitType]), - }; + return { + units: Object.values(state.objects[ownProps.unitType]) + }; }; const mapDispatchToProps = (dispatch, ownProps) => { - return { - onAdd: (id) => dispatch(addUnit(ownProps.unitType, id)), - }; + return { + onAdd: id => dispatch(addUnit(ownProps.unitType, id)) + }; }; -const UnitAddContainer = connect( - mapStateToProps, - mapDispatchToProps -)(UnitAddComponent); +const UnitAddContainer = connect(mapStateToProps, mapDispatchToProps)( + UnitAddComponent +); export default UnitAddContainer; diff --git a/src/containers/app/sidebars/topology/machine/UnitContainer.js b/src/containers/app/sidebars/topology/machine/UnitContainer.js index 12024d5a..a919e8d3 100644 --- a/src/containers/app/sidebars/topology/machine/UnitContainer.js +++ b/src/containers/app/sidebars/topology/machine/UnitContainer.js @@ -1,23 +1,22 @@ -import {connect} from "react-redux"; -import {deleteUnit} from "../../../../../actions/topology/machine"; +import { connect } from "react-redux"; +import { deleteUnit } from "../../../../../actions/topology/machine"; import UnitComponent from "../../../../../components/app/sidebars/topology/machine/UnitComponent"; const mapStateToProps = (state, ownProps) => { - return { - unit: state.objects[ownProps.unitType][ownProps.unitId], - inSimulation: state.currentExperimentId !== -1 - }; + return { + unit: state.objects[ownProps.unitType][ownProps.unitId], + inSimulation: state.currentExperimentId !== -1 + }; }; const mapDispatchToProps = (dispatch, ownProps) => { - return { - onDelete: () => dispatch(deleteUnit(ownProps.unitType, ownProps.index)), - }; + return { + onDelete: () => dispatch(deleteUnit(ownProps.unitType, ownProps.index)) + }; }; -const UnitContainer = connect( - mapStateToProps, - mapDispatchToProps -)(UnitComponent); +const UnitContainer = connect(mapStateToProps, mapDispatchToProps)( + UnitComponent +); export default UnitContainer; diff --git a/src/containers/app/sidebars/topology/machine/UnitListContainer.js b/src/containers/app/sidebars/topology/machine/UnitListContainer.js index e351c63c..6554b8f8 100644 --- a/src/containers/app/sidebars/topology/machine/UnitListContainer.js +++ b/src/containers/app/sidebars/topology/machine/UnitListContainer.js @@ -1,16 +1,18 @@ -import {connect} from "react-redux"; +import { connect } from "react-redux"; import UnitListComponent from "../../../../../components/app/sidebars/topology/machine/UnitListComponent"; const mapStateToProps = (state, ownProps) => { - return { - unitIds: state.objects.machine[state.objects.rack[state.objects.tile[state.interactionLevel.tileId].objectId] - .machineIds[state.interactionLevel.position - 1]][ownProps.unitType + "Ids"], - inSimulation: state.currentExperimentId !== -1 - }; + return { + unitIds: + state.objects.machine[ + state.objects.rack[ + state.objects.tile[state.interactionLevel.tileId].objectId + ].machineIds[state.interactionLevel.position - 1] + ][ownProps.unitType + "Ids"], + inSimulation: state.currentExperimentId !== -1 + }; }; -const UnitListContainer = connect( - mapStateToProps -)(UnitListComponent); +const UnitListContainer = connect(mapStateToProps)(UnitListComponent); export default UnitListContainer; diff --git a/src/containers/app/sidebars/topology/machine/UnitTabsContainer.js b/src/containers/app/sidebars/topology/machine/UnitTabsContainer.js index 46952c74..85d83877 100644 --- a/src/containers/app/sidebars/topology/machine/UnitTabsContainer.js +++ b/src/containers/app/sidebars/topology/machine/UnitTabsContainer.js @@ -1,14 +1,12 @@ -import {connect} from "react-redux"; +import { connect } from "react-redux"; import UnitTabsComponent from "../../../../../components/app/sidebars/topology/machine/UnitTabsComponent"; const mapStateToProps = state => { - return { - inSimulation: state.currentExperimentId !== -1, - }; + return { + inSimulation: state.currentExperimentId !== -1 + }; }; -const UnitTabsContainer = connect( - mapStateToProps -)(UnitTabsComponent); +const UnitTabsContainer = connect(mapStateToProps)(UnitTabsComponent); export default UnitTabsContainer; diff --git a/src/containers/app/sidebars/topology/rack/BackToRoomContainer.js b/src/containers/app/sidebars/topology/rack/BackToRoomContainer.js index 01653540..1b1bb2b0 100644 --- a/src/containers/app/sidebars/topology/rack/BackToRoomContainer.js +++ b/src/containers/app/sidebars/topology/rack/BackToRoomContainer.js @@ -1,16 +1,15 @@ -import {connect} from "react-redux"; -import {goDownOneInteractionLevel} from "../../../../../actions/interaction-level"; +import { connect } from "react-redux"; +import { goDownOneInteractionLevel } from "../../../../../actions/interaction-level"; import BackToRoomComponent from "../../../../../components/app/sidebars/topology/rack/BackToRoomComponent"; const mapDispatchToProps = dispatch => { - return { - onClick: () => dispatch(goDownOneInteractionLevel()), - }; + return { + onClick: () => dispatch(goDownOneInteractionLevel()) + }; }; -const BackToRoomContainer = connect( - undefined, - mapDispatchToProps -)(BackToRoomComponent); +const BackToRoomContainer = connect(undefined, mapDispatchToProps)( + BackToRoomComponent +); export default BackToRoomContainer; diff --git a/src/containers/app/sidebars/topology/rack/DeleteRackContainer.js b/src/containers/app/sidebars/topology/rack/DeleteRackContainer.js index cf225558..a54ceb23 100644 --- a/src/containers/app/sidebars/topology/rack/DeleteRackContainer.js +++ b/src/containers/app/sidebars/topology/rack/DeleteRackContainer.js @@ -1,16 +1,15 @@ -import {connect} from "react-redux"; -import {openDeleteRackModal} from "../../../../../actions/modals/topology"; +import { connect } from "react-redux"; +import { openDeleteRackModal } from "../../../../../actions/modals/topology"; import DeleteRackComponent from "../../../../../components/app/sidebars/topology/rack/DeleteRackComponent"; const mapDispatchToProps = dispatch => { - return { - onClick: () => dispatch(openDeleteRackModal()), - }; + return { + onClick: () => dispatch(openDeleteRackModal()) + }; }; -const DeleteRackContainer = connect( - undefined, - mapDispatchToProps -)(DeleteRackComponent); +const DeleteRackContainer = connect(undefined, mapDispatchToProps)( + DeleteRackComponent +); export default DeleteRackContainer; diff --git a/src/containers/app/sidebars/topology/rack/EmptySlotContainer.js b/src/containers/app/sidebars/topology/rack/EmptySlotContainer.js index b8f5e553..527805a2 100644 --- a/src/containers/app/sidebars/topology/rack/EmptySlotContainer.js +++ b/src/containers/app/sidebars/topology/rack/EmptySlotContainer.js @@ -1,22 +1,21 @@ -import {connect} from "react-redux"; -import {addMachine} from "../../../../../actions/topology/rack"; +import { connect } from "react-redux"; +import { addMachine } from "../../../../../actions/topology/rack"; import EmptySlotComponent from "../../../../../components/app/sidebars/topology/rack/EmptySlotComponent"; const mapStateToProps = state => { - return { - inSimulation: state.currentExperimentId !== -1 - }; + return { + inSimulation: state.currentExperimentId !== -1 + }; }; const mapDispatchToProps = (dispatch, ownProps) => { - return { - onAdd: () => dispatch(addMachine(ownProps.position)), - }; + return { + onAdd: () => dispatch(addMachine(ownProps.position)) + }; }; -const EmptySlotContainer = connect( - mapStateToProps, - mapDispatchToProps -)(EmptySlotComponent); +const EmptySlotContainer = connect(mapStateToProps, mapDispatchToProps)( + EmptySlotComponent +); export default EmptySlotContainer; diff --git a/src/containers/app/sidebars/topology/rack/MachineContainer.js b/src/containers/app/sidebars/topology/rack/MachineContainer.js index cd15ddd0..8cd177e7 100644 --- a/src/containers/app/sidebars/topology/rack/MachineContainer.js +++ b/src/containers/app/sidebars/topology/rack/MachineContainer.js @@ -1,35 +1,40 @@ -import {connect} from "react-redux"; -import {goFromRackToMachine} from "../../../../../actions/interaction-level"; +import { connect } from "react-redux"; +import { goFromRackToMachine } from "../../../../../actions/interaction-level"; import MachineComponent from "../../../../../components/app/sidebars/topology/rack/MachineComponent"; -import {getStateLoad} from "../../../../../util/simulation-load"; +import { getStateLoad } from "../../../../../util/simulation-load"; const mapStateToProps = (state, ownProps) => { - const machine = state.objects.machine[ownProps.machineId]; - const inSimulation = state.currentExperimentId !== -1; + const machine = state.objects.machine[ownProps.machineId]; + const inSimulation = state.currentExperimentId !== -1; - let machineLoad = undefined; - if (inSimulation) { - if (state.states.machine[state.currentTick] && state.states.machine[state.currentTick][machine.id]) { - machineLoad = getStateLoad(state.loadMetric, state.states.machine[state.currentTick][machine.id]); - } + let machineLoad = undefined; + if (inSimulation) { + if ( + state.states.machine[state.currentTick] && + state.states.machine[state.currentTick][machine.id] + ) { + machineLoad = getStateLoad( + state.loadMetric, + state.states.machine[state.currentTick][machine.id] + ); } + } - return { - machine, - inSimulation, - machineLoad - }; + return { + machine, + inSimulation, + machineLoad + }; }; const mapDispatchToProps = (dispatch, ownProps) => { - return { - onClick: () => dispatch(goFromRackToMachine(ownProps.position)), - }; + return { + onClick: () => dispatch(goFromRackToMachine(ownProps.position)) + }; }; -const MachineContainer = connect( - mapStateToProps, - mapDispatchToProps -)(MachineComponent); +const MachineContainer = connect(mapStateToProps, mapDispatchToProps)( + MachineComponent +); export default MachineContainer; diff --git a/src/containers/app/sidebars/topology/rack/MachineListContainer.js b/src/containers/app/sidebars/topology/rack/MachineListContainer.js index dbedfbb2..b19a50ae 100644 --- a/src/containers/app/sidebars/topology/rack/MachineListContainer.js +++ b/src/containers/app/sidebars/topology/rack/MachineListContainer.js @@ -1,14 +1,15 @@ -import {connect} from "react-redux"; +import { connect } from "react-redux"; import MachineListComponent from "../../../../../components/app/sidebars/topology/rack/MachineListComponent"; const mapStateToProps = state => { - return { - machineIds: state.objects.rack[state.objects.tile[state.interactionLevel.tileId].objectId].machineIds, - }; + return { + machineIds: + state.objects.rack[ + state.objects.tile[state.interactionLevel.tileId].objectId + ].machineIds + }; }; -const MachineListContainer = connect( - mapStateToProps -)(MachineListComponent); +const MachineListContainer = connect(mapStateToProps)(MachineListComponent); export default MachineListContainer; diff --git a/src/containers/app/sidebars/topology/rack/RackNameContainer.js b/src/containers/app/sidebars/topology/rack/RackNameContainer.js index 49a58155..8f364ca0 100644 --- a/src/containers/app/sidebars/topology/rack/RackNameContainer.js +++ b/src/containers/app/sidebars/topology/rack/RackNameContainer.js @@ -1,22 +1,24 @@ -import {connect} from "react-redux"; -import {openEditRackNameModal} from "../../../../../actions/modals/topology"; +import { connect } from "react-redux"; +import { openEditRackNameModal } from "../../../../../actions/modals/topology"; import RackNameComponent from "../../../../../components/app/sidebars/topology/rack/RackNameComponent"; const mapStateToProps = state => { - return { - rackName: state.objects.rack[state.objects.tile[state.interactionLevel.tileId].objectId].name, - }; + return { + rackName: + state.objects.rack[ + state.objects.tile[state.interactionLevel.tileId].objectId + ].name + }; }; const mapDispatchToProps = dispatch => { - return { - onEdit: () => dispatch(openEditRackNameModal()), - }; + return { + onEdit: () => dispatch(openEditRackNameModal()) + }; }; -const RackNameContainer = connect( - mapStateToProps, - mapDispatchToProps -)(RackNameComponent); +const RackNameContainer = connect(mapStateToProps, mapDispatchToProps)( + RackNameComponent +); export default RackNameContainer; diff --git a/src/containers/app/sidebars/topology/rack/RackSidebarContainer.js b/src/containers/app/sidebars/topology/rack/RackSidebarContainer.js index ba51ee4a..0a2bfdcc 100644 --- a/src/containers/app/sidebars/topology/rack/RackSidebarContainer.js +++ b/src/containers/app/sidebars/topology/rack/RackSidebarContainer.js @@ -1,15 +1,13 @@ -import {connect} from "react-redux"; +import { connect } from "react-redux"; import RackSidebarComponent from "../../../../../components/app/sidebars/topology/rack/RackSidebarComponent"; const mapStateToProps = state => { - return { - rackId: state.objects.tile[state.interactionLevel.tileId].objectId, - inSimulation: state.currentExperimentId !== -1, - }; + return { + rackId: state.objects.tile[state.interactionLevel.tileId].objectId, + inSimulation: state.currentExperimentId !== -1 + }; }; -const RackSidebarContainer = connect( - mapStateToProps -)(RackSidebarComponent); +const RackSidebarContainer = connect(mapStateToProps)(RackSidebarComponent); export default RackSidebarContainer; diff --git a/src/containers/app/sidebars/topology/room/BackToBuildingContainer.js b/src/containers/app/sidebars/topology/room/BackToBuildingContainer.js index a6366552..02288b7b 100644 --- a/src/containers/app/sidebars/topology/room/BackToBuildingContainer.js +++ b/src/containers/app/sidebars/topology/room/BackToBuildingContainer.js @@ -1,16 +1,15 @@ -import {connect} from "react-redux"; -import {goDownOneInteractionLevel} from "../../../../../actions/interaction-level"; +import { connect } from "react-redux"; +import { goDownOneInteractionLevel } from "../../../../../actions/interaction-level"; import BackToBuildingComponent from "../../../../../components/app/sidebars/topology/room/BackToBuildingComponent"; const mapDispatchToProps = dispatch => { - return { - onClick: () => dispatch(goDownOneInteractionLevel()), - }; + return { + onClick: () => dispatch(goDownOneInteractionLevel()) + }; }; -const BackToBuildingContainer = connect( - undefined, - mapDispatchToProps -)(BackToBuildingComponent); +const BackToBuildingContainer = connect(undefined, mapDispatchToProps)( + BackToBuildingComponent +); export default BackToBuildingContainer; diff --git a/src/containers/app/sidebars/topology/room/DeleteRoomContainer.js b/src/containers/app/sidebars/topology/room/DeleteRoomContainer.js index 0c9aef1c..5223061d 100644 --- a/src/containers/app/sidebars/topology/room/DeleteRoomContainer.js +++ b/src/containers/app/sidebars/topology/room/DeleteRoomContainer.js @@ -1,16 +1,15 @@ -import {connect} from "react-redux"; -import {openDeleteRoomModal} from "../../../../../actions/modals/topology"; +import { connect } from "react-redux"; +import { openDeleteRoomModal } from "../../../../../actions/modals/topology"; import DeleteRoomComponent from "../../../../../components/app/sidebars/topology/room/DeleteRoomComponent"; const mapDispatchToProps = dispatch => { - return { - onClick: () => dispatch(openDeleteRoomModal()), - }; + return { + onClick: () => dispatch(openDeleteRoomModal()) + }; }; -const DeleteRoomContainer = connect( - undefined, - mapDispatchToProps -)(DeleteRoomComponent); +const DeleteRoomContainer = connect(undefined, mapDispatchToProps)( + DeleteRoomComponent +); export default DeleteRoomContainer; diff --git a/src/containers/app/sidebars/topology/room/RackConstructionContainer.js b/src/containers/app/sidebars/topology/room/RackConstructionContainer.js index f06a3ab2..0fc22b09 100644 --- a/src/containers/app/sidebars/topology/room/RackConstructionContainer.js +++ b/src/containers/app/sidebars/topology/room/RackConstructionContainer.js @@ -1,23 +1,25 @@ -import {connect} from "react-redux"; -import {startRackConstruction, stopRackConstruction} from "../../../../../actions/topology/room"; +import { connect } from "react-redux"; +import { + startRackConstruction, + stopRackConstruction +} from "../../../../../actions/topology/room"; import RackConstructionComponent from "../../../../../components/app/sidebars/topology/room/RackConstructionComponent"; const mapStateToProps = state => { - return { - inRackConstructionMode: state.construction.inRackConstructionMode, - }; + return { + inRackConstructionMode: state.construction.inRackConstructionMode + }; }; const mapDispatchToProps = dispatch => { - return { - onStart: () => dispatch(startRackConstruction()), - onStop: () => dispatch(stopRackConstruction()), - }; + return { + onStart: () => dispatch(startRackConstruction()), + onStop: () => dispatch(stopRackConstruction()) + }; }; -const RackConstructionContainer = connect( - mapStateToProps, - mapDispatchToProps -)(RackConstructionComponent); +const RackConstructionContainer = connect(mapStateToProps, mapDispatchToProps)( + RackConstructionComponent +); export default RackConstructionContainer; diff --git a/src/containers/app/sidebars/topology/room/RoomNameContainer.js b/src/containers/app/sidebars/topology/room/RoomNameContainer.js index c1f7f397..36125521 100644 --- a/src/containers/app/sidebars/topology/room/RoomNameContainer.js +++ b/src/containers/app/sidebars/topology/room/RoomNameContainer.js @@ -1,22 +1,21 @@ -import {connect} from "react-redux"; -import {openEditRoomNameModal} from "../../../../../actions/modals/topology"; +import { connect } from "react-redux"; +import { openEditRoomNameModal } from "../../../../../actions/modals/topology"; import RoomNameComponent from "../../../../../components/app/sidebars/topology/room/RoomNameComponent"; const mapStateToProps = state => { - return { - roomName: state.objects.room[state.interactionLevel.roomId].name, - }; + return { + roomName: state.objects.room[state.interactionLevel.roomId].name + }; }; const mapDispatchToProps = dispatch => { - return { - onEdit: () => dispatch(openEditRoomNameModal()), - }; + return { + onEdit: () => dispatch(openEditRoomNameModal()) + }; }; -const RoomNameContainer = connect( - mapStateToProps, - mapDispatchToProps -)(RoomNameComponent); +const RoomNameContainer = connect(mapStateToProps, mapDispatchToProps)( + RoomNameComponent +); export default RoomNameContainer; diff --git a/src/containers/app/sidebars/topology/room/RoomSidebarContainer.js b/src/containers/app/sidebars/topology/room/RoomSidebarContainer.js index 6371e6a1..38d5fb80 100644 --- a/src/containers/app/sidebars/topology/room/RoomSidebarContainer.js +++ b/src/containers/app/sidebars/topology/room/RoomSidebarContainer.js @@ -1,16 +1,14 @@ -import {connect} from "react-redux"; +import { connect } from "react-redux"; import RoomSidebarComponent from "../../../../../components/app/sidebars/topology/room/RoomSidebarComponent"; const mapStateToProps = state => { - return { - roomId: state.interactionLevel.roomId, - roomType: state.objects.room[state.interactionLevel.roomId].roomType, - inSimulation: state.currentExperimentId !== -1, - }; + return { + roomId: state.interactionLevel.roomId, + roomType: state.objects.room[state.interactionLevel.roomId].roomType, + inSimulation: state.currentExperimentId !== -1 + }; }; -const RoomSidebarContainer = connect( - mapStateToProps -)(RoomSidebarComponent); +const RoomSidebarContainer = connect(mapStateToProps)(RoomSidebarComponent); export default RoomSidebarContainer; diff --git a/src/containers/app/sidebars/topology/room/RoomTypeContainer.js b/src/containers/app/sidebars/topology/room/RoomTypeContainer.js index 8cc1126a..414852f1 100644 --- a/src/containers/app/sidebars/topology/room/RoomTypeContainer.js +++ b/src/containers/app/sidebars/topology/room/RoomTypeContainer.js @@ -1,14 +1,12 @@ -import {connect} from "react-redux"; +import { connect } from "react-redux"; import RoomTypeComponent from "../../../../../components/app/sidebars/topology/room/RoomTypeComponent"; const mapStateToProps = state => { - return { - roomType: state.objects.room[state.interactionLevel.roomId].roomType, - }; + return { + roomType: state.objects.room[state.interactionLevel.roomId].roomType + }; }; -const RoomNameContainer = connect( - mapStateToProps -)(RoomTypeComponent); +const RoomNameContainer = connect(mapStateToProps)(RoomTypeComponent); export default RoomNameContainer; diff --git a/src/containers/app/timeline/PlayButtonContainer.js b/src/containers/app/timeline/PlayButtonContainer.js index 1003b69c..4e3c3d81 100644 --- a/src/containers/app/timeline/PlayButtonContainer.js +++ b/src/containers/app/timeline/PlayButtonContainer.js @@ -1,25 +1,27 @@ -import {connect} from "react-redux"; -import {pauseSimulation, playSimulation} from "../../../actions/simulation/playback"; +import { connect } from "react-redux"; +import { + pauseSimulation, + playSimulation +} from "../../../actions/simulation/playback"; import PlayButtonComponent from "../../../components/app/timeline/PlayButtonComponent"; const mapStateToProps = state => { - return { - isPlaying: state.isPlaying, - currentTick: state.currentTick, - lastSimulatedTick: state.lastSimulatedTick, - }; + return { + isPlaying: state.isPlaying, + currentTick: state.currentTick, + lastSimulatedTick: state.lastSimulatedTick + }; }; const mapDispatchToProps = dispatch => { - return { - onPlay: () => dispatch(playSimulation()), - onPause: () => dispatch(pauseSimulation()), - }; + return { + onPlay: () => dispatch(playSimulation()), + onPause: () => dispatch(pauseSimulation()) + }; }; -const PlayButtonContainer = connect( - mapStateToProps, - mapDispatchToProps -)(PlayButtonComponent); +const PlayButtonContainer = connect(mapStateToProps, mapDispatchToProps)( + PlayButtonComponent +); export default PlayButtonContainer; diff --git a/src/containers/app/timeline/TimelineContainer.js b/src/containers/app/timeline/TimelineContainer.js index 46491f9b..74d37d58 100644 --- a/src/containers/app/timeline/TimelineContainer.js +++ b/src/containers/app/timeline/TimelineContainer.js @@ -1,39 +1,41 @@ -import {connect} from "react-redux"; -import {pauseSimulation} from "../../../actions/simulation/playback"; -import {incrementTick} from "../../../actions/simulation/tick"; -import {setCurrentDatacenter} from "../../../actions/topology/building"; +import { connect } from "react-redux"; +import { pauseSimulation } from "../../../actions/simulation/playback"; +import { incrementTick } from "../../../actions/simulation/tick"; +import { setCurrentDatacenter } from "../../../actions/topology/building"; import TimelineComponent from "../../../components/app/timeline/TimelineComponent"; const mapStateToProps = state => { - let sections = []; - if (state.currentExperimentId !== -1) { - const sectionIds = state.objects.path[state.objects.experiment[state.currentExperimentId].pathId].sectionIds; + let sections = []; + if (state.currentExperimentId !== -1) { + const sectionIds = + state.objects.path[ + state.objects.experiment[state.currentExperimentId].pathId + ].sectionIds; - if (sectionIds) { - sections = sectionIds.map(sectionId => state.objects.section[sectionId]); - } + if (sectionIds) { + sections = sectionIds.map(sectionId => state.objects.section[sectionId]); } + } - return { - isPlaying: state.isPlaying, - currentTick: state.currentTick, - lastSimulatedTick: state.lastSimulatedTick, - currentDatacenterId: state.currentDatacenterId, - sections, - }; + return { + isPlaying: state.isPlaying, + currentTick: state.currentTick, + lastSimulatedTick: state.lastSimulatedTick, + currentDatacenterId: state.currentDatacenterId, + sections + }; }; const mapDispatchToProps = dispatch => { - return { - incrementTick: () => dispatch(incrementTick()), - pauseSimulation: () => dispatch(pauseSimulation()), - setCurrentDatacenter: id => dispatch(setCurrentDatacenter(id)) - }; + return { + incrementTick: () => dispatch(incrementTick()), + pauseSimulation: () => dispatch(pauseSimulation()), + setCurrentDatacenter: id => dispatch(setCurrentDatacenter(id)) + }; }; -const TimelineContainer = connect( - mapStateToProps, - mapDispatchToProps -)(TimelineComponent); +const TimelineContainer = connect(mapStateToProps, mapDispatchToProps)( + TimelineComponent +); export default TimelineContainer; diff --git a/src/containers/app/timeline/TimelineControlsContainer.js b/src/containers/app/timeline/TimelineControlsContainer.js index e91a0aca..ac851b2e 100644 --- a/src/containers/app/timeline/TimelineControlsContainer.js +++ b/src/containers/app/timeline/TimelineControlsContainer.js @@ -1,34 +1,36 @@ -import {connect} from "react-redux"; -import {goToTick} from "../../../actions/simulation/tick"; +import { connect } from "react-redux"; +import { goToTick } from "../../../actions/simulation/tick"; import TimelineControlsComponent from "../../../components/app/timeline/TimelineControlsComponent"; const mapStateToProps = state => { - let sectionTicks = []; - if (state.currentExperimentId !== -1) { - const sectionIds = state.objects.path[state.objects.experiment[state.currentExperimentId].pathId].sectionIds; - if (sectionIds) { - sectionTicks = sectionIds - .filter(sectionId => state.objects.section[sectionId].startTick !== 0) - .map(sectionId => state.objects.section[sectionId].startTick); - } + let sectionTicks = []; + if (state.currentExperimentId !== -1) { + const sectionIds = + state.objects.path[ + state.objects.experiment[state.currentExperimentId].pathId + ].sectionIds; + if (sectionIds) { + sectionTicks = sectionIds + .filter(sectionId => state.objects.section[sectionId].startTick !== 0) + .map(sectionId => state.objects.section[sectionId].startTick); } + } - return { - currentTick: state.currentTick, - lastSimulatedTick: state.lastSimulatedTick, - sectionTicks, - }; + return { + currentTick: state.currentTick, + lastSimulatedTick: state.lastSimulatedTick, + sectionTicks + }; }; const mapDispatchToProps = dispatch => { - return { - goToTick: (tick) => dispatch(goToTick(tick)), - }; + return { + goToTick: tick => dispatch(goToTick(tick)) + }; }; -const TimelineControlsContainer = connect( - mapStateToProps, - mapDispatchToProps -)(TimelineControlsComponent); +const TimelineControlsContainer = connect(mapStateToProps, mapDispatchToProps)( + TimelineControlsComponent +); export default TimelineControlsContainer; diff --git a/src/containers/app/timeline/TimelineLabelsContainer.js b/src/containers/app/timeline/TimelineLabelsContainer.js index 3dfad9f2..9d7f268d 100644 --- a/src/containers/app/timeline/TimelineLabelsContainer.js +++ b/src/containers/app/timeline/TimelineLabelsContainer.js @@ -1,15 +1,15 @@ -import {connect} from "react-redux"; +import { connect } from "react-redux"; import TimelineLabelsComponent from "../../../components/app/timeline/TimelineLabelsComponent"; const mapStateToProps = state => { - return { - currentTick: state.currentTick, - lastSimulatedTick: state.lastSimulatedTick, - }; + return { + currentTick: state.currentTick, + lastSimulatedTick: state.lastSimulatedTick + }; }; -const TimelineLabelsContainer = connect( - mapStateToProps -)(TimelineLabelsComponent); +const TimelineLabelsContainer = connect(mapStateToProps)( + TimelineLabelsComponent +); export default TimelineLabelsContainer; diff --git a/src/containers/auth/Login.js b/src/containers/auth/Login.js index 4b008da4..de12f815 100644 --- a/src/containers/auth/Login.js +++ b/src/containers/auth/Login.js @@ -1,61 +1,56 @@ import PropTypes from "prop-types"; import React from "react"; import GoogleLogin from "react-google-login"; -import {connect} from "react-redux"; -import {logIn} from "../../actions/auth"; +import { connect } from "react-redux"; +import { logIn } from "../../actions/auth"; class LoginContainer extends React.Component { - static propTypes = { - visible: PropTypes.bool.isRequired, - onLogin: PropTypes.func.isRequired, - }; - - onAuthResponse(response) { - this.props.onLogin({ - email: response.getBasicProfile().getEmail(), - givenName: response.getBasicProfile().getGivenName(), - familyName: response.getBasicProfile().getFamilyName(), - googleId: response.googleId, - authToken: response.getAuthResponse().id_token, - expiresAt: response.getAuthResponse().expires_at - }); + static propTypes = { + visible: PropTypes.bool.isRequired, + onLogin: PropTypes.func.isRequired + }; + + onAuthResponse(response) { + this.props.onLogin({ + email: response.getBasicProfile().getEmail(), + givenName: response.getBasicProfile().getGivenName(), + familyName: response.getBasicProfile().getFamilyName(), + googleId: response.googleId, + authToken: response.getAuthResponse().id_token, + expiresAt: response.getAuthResponse().expires_at + }); + } + + render() { + if (!this.props.visible) { + return <span />; } - render() { - if (!this.props.visible) { - return <span/>; - } - - return ( - <GoogleLogin - clientId={process.env.REACT_APP_OAUTH_CLIENT_ID} - onSuccess={this.onAuthResponse.bind(this)} - onFailure={this.onAuthResponse.bind(this)} - className="login btn btn-primary" - > - <span className='fa fa-google'/> - {' '} - <span>Login with Google</span> - </GoogleLogin> - ); - } + return ( + <GoogleLogin + clientId={process.env.REACT_APP_OAUTH_CLIENT_ID} + onSuccess={this.onAuthResponse.bind(this)} + onFailure={this.onAuthResponse.bind(this)} + className="login btn btn-primary" + > + <span className="fa fa-google" /> <span>Login with Google</span> + </GoogleLogin> + ); + } } const mapStateToProps = (state, ownProps) => { - return { - visible: ownProps.visible, - }; + return { + visible: ownProps.visible + }; }; const mapDispatchToProps = dispatch => { - return { - onLogin: (payload) => dispatch(logIn(payload)), - }; + return { + onLogin: payload => dispatch(logIn(payload)) + }; }; -const Login = connect( - mapStateToProps, - mapDispatchToProps -)(LoginContainer); +const Login = connect(mapStateToProps, mapDispatchToProps)(LoginContainer); export default Login; diff --git a/src/containers/auth/Logout.js b/src/containers/auth/Logout.js index ec2b8842..918932f6 100644 --- a/src/containers/auth/Logout.js +++ b/src/containers/auth/Logout.js @@ -1,16 +1,13 @@ -import {connect} from "react-redux"; -import {logOut} from "../../actions/auth"; +import { connect } from "react-redux"; +import { logOut } from "../../actions/auth"; import LogoutButton from "../../components/navigation/LogoutButton"; const mapDispatchToProps = dispatch => { - return { - onLogout: () => dispatch(logOut()), - }; + return { + onLogout: () => dispatch(logOut()) + }; }; -const Logout = connect( - undefined, - mapDispatchToProps -)(LogoutButton); +const Logout = connect(undefined, mapDispatchToProps)(LogoutButton); export default Logout; diff --git a/src/containers/auth/ProfileName.js b/src/containers/auth/ProfileName.js index 27df133c..21941bd2 100644 --- a/src/containers/auth/ProfileName.js +++ b/src/containers/auth/ProfileName.js @@ -1,16 +1,14 @@ import React from "react"; -import {connect} from "react-redux"; +import { connect } from "react-redux"; const mapStateToProps = state => { - return { - text: state.auth.givenName + " " + state.auth.familyName - }; + return { + text: state.auth.givenName + " " + state.auth.familyName + }; }; -const SpanElement = ({text}) => <span>{text}</span>; +const SpanElement = ({ text }) => <span>{text}</span>; -const ProfileName = connect( - mapStateToProps -)(SpanElement); +const ProfileName = connect(mapStateToProps)(SpanElement); export default ProfileName; diff --git a/src/containers/experiments/ExperimentListContainer.js b/src/containers/experiments/ExperimentListContainer.js index 0c6818fa..632942bf 100644 --- a/src/containers/experiments/ExperimentListContainer.js +++ b/src/containers/experiments/ExperimentListContainer.js @@ -1,23 +1,27 @@ -import {connect} from "react-redux"; +import { connect } from "react-redux"; import ExperimentListComponent from "../../components/experiments/ExperimentListComponent"; const mapStateToProps = state => { - if (state.currentSimulationId === -1 || !("experimentIds" in state.objects.simulation[state.currentSimulationId])) { - return { - experimentIds: [], - }; - } + if ( + state.currentSimulationId === -1 || + !("experimentIds" in state.objects.simulation[state.currentSimulationId]) + ) { + return { + experimentIds: [] + }; + } - const experimentIds = state.objects.simulation[state.currentSimulationId].experimentIds; - if (experimentIds) { - return { - experimentIds, - }; - } + const experimentIds = + state.objects.simulation[state.currentSimulationId].experimentIds; + if (experimentIds) { + return { + experimentIds + }; + } }; -const ExperimentListContainer = connect( - mapStateToProps -)(ExperimentListComponent); +const ExperimentListContainer = connect(mapStateToProps)( + ExperimentListComponent +); export default ExperimentListContainer; diff --git a/src/containers/experiments/ExperimentRowContainer.js b/src/containers/experiments/ExperimentRowContainer.js index 1db89b7d..96ebc3db 100644 --- a/src/containers/experiments/ExperimentRowContainer.js +++ b/src/containers/experiments/ExperimentRowContainer.js @@ -1,28 +1,30 @@ -import {connect} from "react-redux"; -import {deleteExperiment} from "../../actions/experiments"; +import { connect } from "react-redux"; +import { deleteExperiment } from "../../actions/experiments"; import ExperimentRowComponent from "../../components/experiments/ExperimentRowComponent"; const mapStateToProps = (state, ownProps) => { - const experiment = Object.assign({}, state.objects.experiment[ownProps.experimentId]); - experiment.trace = state.objects.trace[experiment.traceId]; - experiment.scheduler = state.objects.scheduler[experiment.schedulerName]; - experiment.path = state.objects.path[experiment.pathId]; + const experiment = Object.assign( + {}, + state.objects.experiment[ownProps.experimentId] + ); + experiment.trace = state.objects.trace[experiment.traceId]; + experiment.scheduler = state.objects.scheduler[experiment.schedulerName]; + experiment.path = state.objects.path[experiment.pathId]; - return { - experiment, - simulationId: state.currentSimulationId, - }; + return { + experiment, + simulationId: state.currentSimulationId + }; }; const mapDispatchToProps = dispatch => { - return { - onDelete: id => dispatch(deleteExperiment(id)) - }; + return { + onDelete: id => dispatch(deleteExperiment(id)) + }; }; -const ExperimentRowContainer = connect( - mapStateToProps, - mapDispatchToProps -)(ExperimentRowComponent); +const ExperimentRowContainer = connect(mapStateToProps, mapDispatchToProps)( + ExperimentRowComponent +); export default ExperimentRowContainer; diff --git a/src/containers/experiments/NewExperimentButtonContainer.js b/src/containers/experiments/NewExperimentButtonContainer.js index 1abbb7b7..60eb92a6 100644 --- a/src/containers/experiments/NewExperimentButtonContainer.js +++ b/src/containers/experiments/NewExperimentButtonContainer.js @@ -1,16 +1,15 @@ -import {connect} from "react-redux"; -import {openNewExperimentModal} from "../../actions/modals/experiments"; +import { connect } from "react-redux"; +import { openNewExperimentModal } from "../../actions/modals/experiments"; import NewExperimentButtonComponent from "../../components/experiments/NewExperimentButtonComponent"; const mapDispatchToProps = dispatch => { - return { - onClick: () => dispatch(openNewExperimentModal()) - }; + return { + onClick: () => dispatch(openNewExperimentModal()) + }; }; -const NewExperimentButtonContainer = connect( - undefined, - mapDispatchToProps -)(NewExperimentButtonComponent); +const NewExperimentButtonContainer = connect(undefined, mapDispatchToProps)( + NewExperimentButtonComponent +); export default NewExperimentButtonContainer; diff --git a/src/containers/modals/DeleteMachineModal.js b/src/containers/modals/DeleteMachineModal.js index c2b658d9..eba37833 100644 --- a/src/containers/modals/DeleteMachineModal.js +++ b/src/containers/modals/DeleteMachineModal.js @@ -1,36 +1,37 @@ import React from "react"; -import {connect} from "react-redux"; -import {closeDeleteMachineModal} from "../../actions/modals/topology"; -import {deleteMachine} from "../../actions/topology/machine"; +import { connect } from "react-redux"; +import { closeDeleteMachineModal } from "../../actions/modals/topology"; +import { deleteMachine } from "../../actions/topology/machine"; import ConfirmationModal from "../../components/modals/ConfirmationModal"; -const DeleteMachineModalComponent = ({visible, callback}) => ( - <ConfirmationModal title="Delete this machine" - message="Are you sure you want to delete this machine?" - show={visible} - callback={callback}/> +const DeleteMachineModalComponent = ({ visible, callback }) => ( + <ConfirmationModal + title="Delete this machine" + message="Are you sure you want to delete this machine?" + show={visible} + callback={callback} + /> ); const mapStateToProps = state => { - return { - visible: state.modals.deleteMachineModalVisible - }; + return { + visible: state.modals.deleteMachineModalVisible + }; }; const mapDispatchToProps = dispatch => { - return { - callback: (isConfirmed) => { - if (isConfirmed) { - dispatch(deleteMachine()); - } - dispatch(closeDeleteMachineModal()); - } - }; + return { + callback: isConfirmed => { + if (isConfirmed) { + dispatch(deleteMachine()); + } + dispatch(closeDeleteMachineModal()); + } + }; }; -const DeleteMachineModal = connect( - mapStateToProps, - mapDispatchToProps -)(DeleteMachineModalComponent); +const DeleteMachineModal = connect(mapStateToProps, mapDispatchToProps)( + DeleteMachineModalComponent +); export default DeleteMachineModal; diff --git a/src/containers/modals/DeleteProfileModal.js b/src/containers/modals/DeleteProfileModal.js index 709b4a92..674e9408 100644 --- a/src/containers/modals/DeleteProfileModal.js +++ b/src/containers/modals/DeleteProfileModal.js @@ -1,36 +1,37 @@ import React from "react"; -import {connect} from "react-redux"; -import {closeDeleteProfileModal} from "../../actions/modals/profile"; -import {deleteCurrentUser} from "../../actions/users"; +import { connect } from "react-redux"; +import { closeDeleteProfileModal } from "../../actions/modals/profile"; +import { deleteCurrentUser } from "../../actions/users"; import ConfirmationModal from "../../components/modals/ConfirmationModal"; -const DeleteProfileModalComponent = ({visible, callback}) => ( - <ConfirmationModal title="Delete my account" - message="Are you sure you want to delete your OpenDC account?" - show={visible} - callback={callback}/> +const DeleteProfileModalComponent = ({ visible, callback }) => ( + <ConfirmationModal + title="Delete my account" + message="Are you sure you want to delete your OpenDC account?" + show={visible} + callback={callback} + /> ); const mapStateToProps = state => { - return { - visible: state.modals.deleteProfileModalVisible - }; + return { + visible: state.modals.deleteProfileModalVisible + }; }; const mapDispatchToProps = dispatch => { - return { - callback: (isConfirmed) => { - if (isConfirmed) { - dispatch(deleteCurrentUser()); - } - dispatch(closeDeleteProfileModal()); - } - }; + return { + callback: isConfirmed => { + if (isConfirmed) { + dispatch(deleteCurrentUser()); + } + dispatch(closeDeleteProfileModal()); + } + }; }; -const DeleteProfileModal = connect( - mapStateToProps, - mapDispatchToProps -)(DeleteProfileModalComponent); +const DeleteProfileModal = connect(mapStateToProps, mapDispatchToProps)( + DeleteProfileModalComponent +); export default DeleteProfileModal; diff --git a/src/containers/modals/DeleteRackModal.js b/src/containers/modals/DeleteRackModal.js index 6515ab96..41bacb37 100644 --- a/src/containers/modals/DeleteRackModal.js +++ b/src/containers/modals/DeleteRackModal.js @@ -1,36 +1,37 @@ import React from "react"; -import {connect} from "react-redux"; -import {closeDeleteRackModal} from "../../actions/modals/topology"; -import {deleteRack} from "../../actions/topology/rack"; +import { connect } from "react-redux"; +import { closeDeleteRackModal } from "../../actions/modals/topology"; +import { deleteRack } from "../../actions/topology/rack"; import ConfirmationModal from "../../components/modals/ConfirmationModal"; -const DeleteRackModalComponent = ({visible, callback}) => ( - <ConfirmationModal title="Delete this rack" - message="Are you sure you want to delete this rack?" - show={visible} - callback={callback}/> +const DeleteRackModalComponent = ({ visible, callback }) => ( + <ConfirmationModal + title="Delete this rack" + message="Are you sure you want to delete this rack?" + show={visible} + callback={callback} + /> ); const mapStateToProps = state => { - return { - visible: state.modals.deleteRackModalVisible - }; + return { + visible: state.modals.deleteRackModalVisible + }; }; const mapDispatchToProps = dispatch => { - return { - callback: (isConfirmed) => { - if (isConfirmed) { - dispatch(deleteRack()); - } - dispatch(closeDeleteRackModal()); - } - }; + return { + callback: isConfirmed => { + if (isConfirmed) { + dispatch(deleteRack()); + } + dispatch(closeDeleteRackModal()); + } + }; }; -const DeleteRackModal = connect( - mapStateToProps, - mapDispatchToProps -)(DeleteRackModalComponent); +const DeleteRackModal = connect(mapStateToProps, mapDispatchToProps)( + DeleteRackModalComponent +); export default DeleteRackModal; diff --git a/src/containers/modals/DeleteRoomModal.js b/src/containers/modals/DeleteRoomModal.js index a32c9ca1..339ff22c 100644 --- a/src/containers/modals/DeleteRoomModal.js +++ b/src/containers/modals/DeleteRoomModal.js @@ -1,36 +1,37 @@ import React from "react"; -import {connect} from "react-redux"; -import {closeDeleteRoomModal} from "../../actions/modals/topology"; -import {deleteRoom} from "../../actions/topology/room"; +import { connect } from "react-redux"; +import { closeDeleteRoomModal } from "../../actions/modals/topology"; +import { deleteRoom } from "../../actions/topology/room"; import ConfirmationModal from "../../components/modals/ConfirmationModal"; -const DeleteRoomModalComponent = ({visible, callback}) => ( - <ConfirmationModal title="Delete this room" - message="Are you sure you want to delete this room?" - show={visible} - callback={callback}/> +const DeleteRoomModalComponent = ({ visible, callback }) => ( + <ConfirmationModal + title="Delete this room" + message="Are you sure you want to delete this room?" + show={visible} + callback={callback} + /> ); const mapStateToProps = state => { - return { - visible: state.modals.deleteRoomModalVisible - }; + return { + visible: state.modals.deleteRoomModalVisible + }; }; const mapDispatchToProps = dispatch => { - return { - callback: (isConfirmed) => { - if (isConfirmed) { - dispatch(deleteRoom()); - } - dispatch(closeDeleteRoomModal()); - } - }; + return { + callback: isConfirmed => { + if (isConfirmed) { + dispatch(deleteRoom()); + } + dispatch(closeDeleteRoomModal()); + } + }; }; -const DeleteRoomModal = connect( - mapStateToProps, - mapDispatchToProps -)(DeleteRoomModalComponent); +const DeleteRoomModal = connect(mapStateToProps, mapDispatchToProps)( + DeleteRoomModalComponent +); export default DeleteRoomModal; diff --git a/src/containers/modals/EditRackNameModal.js b/src/containers/modals/EditRackNameModal.js index 6f638bbc..748e847b 100644 --- a/src/containers/modals/EditRackNameModal.js +++ b/src/containers/modals/EditRackNameModal.js @@ -1,39 +1,44 @@ import React from "react"; -import {connect} from "react-redux"; -import {closeEditRackNameModal} from "../../actions/modals/topology"; -import {editRackName} from "../../actions/topology/rack"; +import { connect } from "react-redux"; +import { closeEditRackNameModal } from "../../actions/modals/topology"; +import { editRackName } from "../../actions/topology/rack"; import TextInputModal from "../../components/modals/TextInputModal"; -const EditRackNameModalComponent = ({visible, previousName, callback}) => ( - <TextInputModal title="Edit rack name" - label="Rack name" - show={visible} - initialValue={previousName} - callback={callback}/> +const EditRackNameModalComponent = ({ visible, previousName, callback }) => ( + <TextInputModal + title="Edit rack name" + label="Rack name" + show={visible} + initialValue={previousName} + callback={callback} + /> ); const mapStateToProps = state => { - return { - visible: state.modals.editRackNameModalVisible, - previousName: state.interactionLevel.mode === "RACK" ? - state.objects.rack[state.objects.tile[state.interactionLevel.tileId].objectId].name : "", - }; + return { + visible: state.modals.editRackNameModalVisible, + previousName: + state.interactionLevel.mode === "RACK" + ? state.objects.rack[ + state.objects.tile[state.interactionLevel.tileId].objectId + ].name + : "" + }; }; const mapDispatchToProps = dispatch => { - return { - callback: (name) => { - if (name) { - dispatch(editRackName(name)); - } - dispatch(closeEditRackNameModal()); - } - }; + return { + callback: name => { + if (name) { + dispatch(editRackName(name)); + } + dispatch(closeEditRackNameModal()); + } + }; }; -const EditRackNameModal = connect( - mapStateToProps, - mapDispatchToProps -)(EditRackNameModalComponent); +const EditRackNameModal = connect(mapStateToProps, mapDispatchToProps)( + EditRackNameModalComponent +); export default EditRackNameModal; diff --git a/src/containers/modals/EditRoomNameModal.js b/src/containers/modals/EditRoomNameModal.js index be6230d0..be6c547c 100644 --- a/src/containers/modals/EditRoomNameModal.js +++ b/src/containers/modals/EditRoomNameModal.js @@ -1,38 +1,42 @@ import React from "react"; -import {connect} from "react-redux"; -import {closeEditRoomNameModal} from "../../actions/modals/topology"; -import {editRoomName} from "../../actions/topology/room"; +import { connect } from "react-redux"; +import { closeEditRoomNameModal } from "../../actions/modals/topology"; +import { editRoomName } from "../../actions/topology/room"; import TextInputModal from "../../components/modals/TextInputModal"; -const EditRoomNameModalComponent = ({visible, previousName, callback}) => ( - <TextInputModal title="Edit room name" - label="Room name" - show={visible} - initialValue={previousName} - callback={callback}/> +const EditRoomNameModalComponent = ({ visible, previousName, callback }) => ( + <TextInputModal + title="Edit room name" + label="Room name" + show={visible} + initialValue={previousName} + callback={callback} + /> ); const mapStateToProps = state => { - return { - visible: state.modals.editRoomNameModalVisible, - previousName: state.interactionLevel.mode === "ROOM" ? state.objects.room[state.interactionLevel.roomId].name : "", - }; + return { + visible: state.modals.editRoomNameModalVisible, + previousName: + state.interactionLevel.mode === "ROOM" + ? state.objects.room[state.interactionLevel.roomId].name + : "" + }; }; const mapDispatchToProps = dispatch => { - return { - callback: (name) => { - if (name) { - dispatch(editRoomName(name)); - } - dispatch(closeEditRoomNameModal()); - } - }; + return { + callback: name => { + if (name) { + dispatch(editRoomName(name)); + } + dispatch(closeEditRoomNameModal()); + } + }; }; -const EditRoomNameModal = connect( - mapStateToProps, - mapDispatchToProps -)(EditRoomNameModalComponent); +const EditRoomNameModal = connect(mapStateToProps, mapDispatchToProps)( + EditRoomNameModalComponent +); export default EditRoomNameModal; diff --git a/src/containers/modals/NewExperimentModal.js b/src/containers/modals/NewExperimentModal.js index 13aed74d..c703c39a 100644 --- a/src/containers/modals/NewExperimentModal.js +++ b/src/containers/modals/NewExperimentModal.js @@ -1,36 +1,39 @@ -import {connect} from "react-redux"; -import {addExperiment} from "../../actions/experiments"; -import {closeNewExperimentModal} from "../../actions/modals/experiments"; +import { connect } from "react-redux"; +import { addExperiment } from "../../actions/experiments"; +import { closeNewExperimentModal } from "../../actions/modals/experiments"; import NewExperimentModalComponent from "../../components/modals/custom-components/NewExperimentModalComponent"; const mapStateToProps = state => { - return { - show: state.modals.newExperimentModalVisible, - paths: Object.values(state.objects.path).filter(path => path.simulationId === state.currentSimulationId), - traces: Object.values(state.objects.trace), - schedulers: Object.values(state.objects.scheduler), - }; + return { + show: state.modals.newExperimentModalVisible, + paths: Object.values(state.objects.path).filter( + path => path.simulationId === state.currentSimulationId + ), + traces: Object.values(state.objects.trace), + schedulers: Object.values(state.objects.scheduler) + }; }; const mapDispatchToProps = dispatch => { - return { - callback: (name, pathId, traceId, schedulerName) => { - if (name) { - dispatch(addExperiment({ - name, - pathId, - traceId, - schedulerName - })); - } - dispatch(closeNewExperimentModal()); - } - }; + return { + callback: (name, pathId, traceId, schedulerName) => { + if (name) { + dispatch( + addExperiment({ + name, + pathId, + traceId, + schedulerName + }) + ); + } + dispatch(closeNewExperimentModal()); + } + }; }; -const NewExperimentModal = connect( - mapStateToProps, - mapDispatchToProps -)(NewExperimentModalComponent); +const NewExperimentModal = connect(mapStateToProps, mapDispatchToProps)( + NewExperimentModalComponent +); export default NewExperimentModal; diff --git a/src/containers/modals/NewSimulationModal.js b/src/containers/modals/NewSimulationModal.js index d85b59ef..80789cd2 100644 --- a/src/containers/modals/NewSimulationModal.js +++ b/src/containers/modals/NewSimulationModal.js @@ -1,35 +1,37 @@ import React from "react"; -import {connect} from "react-redux"; -import {closeNewSimulationModal} from "../../actions/modals/simulations"; -import {addSimulation} from "../../actions/simulations"; +import { connect } from "react-redux"; +import { closeNewSimulationModal } from "../../actions/modals/simulations"; +import { addSimulation } from "../../actions/simulations"; import TextInputModal from "../../components/modals/TextInputModal"; -const NewSimulationModalComponent = ({visible, callback}) => ( - <TextInputModal title="New Simulation" label="Simulation title" - show={visible} - callback={callback}/> +const NewSimulationModalComponent = ({ visible, callback }) => ( + <TextInputModal + title="New Simulation" + label="Simulation title" + show={visible} + callback={callback} + /> ); const mapStateToProps = state => { - return { - visible: state.modals.newSimulationModalVisible - }; + return { + visible: state.modals.newSimulationModalVisible + }; }; const mapDispatchToProps = dispatch => { - return { - callback: (text) => { - if (text) { - dispatch(addSimulation(text)); - } - dispatch(closeNewSimulationModal()); - } - }; + return { + callback: text => { + if (text) { + dispatch(addSimulation(text)); + } + dispatch(closeNewSimulationModal()); + } + }; }; -const NewSimulationModal = connect( - mapStateToProps, - mapDispatchToProps -)(NewSimulationModalComponent); +const NewSimulationModal = connect(mapStateToProps, mapDispatchToProps)( + NewSimulationModalComponent +); export default NewSimulationModal; diff --git a/src/containers/simulations/FilterLink.js b/src/containers/simulations/FilterLink.js index 00d8f722..2c5f4ed5 100644 --- a/src/containers/simulations/FilterLink.js +++ b/src/containers/simulations/FilterLink.js @@ -1,22 +1,19 @@ -import {connect} from "react-redux"; -import {setAuthVisibilityFilter} from "../../actions/simulations"; +import { connect } from "react-redux"; +import { setAuthVisibilityFilter } from "../../actions/simulations"; import FilterButton from "../../components/simulations/FilterButton"; const mapStateToProps = (state, ownProps) => { - return { - active: state.simulationList.authVisibilityFilter === ownProps.filter - }; + return { + active: state.simulationList.authVisibilityFilter === ownProps.filter + }; }; const mapDispatchToProps = (dispatch, ownProps) => { - return { - onClick: () => dispatch(setAuthVisibilityFilter(ownProps.filter)) - }; + return { + onClick: () => dispatch(setAuthVisibilityFilter(ownProps.filter)) + }; }; -const FilterLink = connect( - mapStateToProps, - mapDispatchToProps -)(FilterButton); +const FilterLink = connect(mapStateToProps, mapDispatchToProps)(FilterButton); export default FilterLink; diff --git a/src/containers/simulations/NewSimulationButtonContainer.js b/src/containers/simulations/NewSimulationButtonContainer.js index 722f8e44..3ea04d24 100644 --- a/src/containers/simulations/NewSimulationButtonContainer.js +++ b/src/containers/simulations/NewSimulationButtonContainer.js @@ -1,16 +1,15 @@ -import {connect} from "react-redux"; -import {openNewSimulationModal} from "../../actions/modals/simulations"; +import { connect } from "react-redux"; +import { openNewSimulationModal } from "../../actions/modals/simulations"; import NewSimulationButtonComponent from "../../components/simulations/NewSimulationButtonComponent"; const mapDispatchToProps = dispatch => { - return { - onClick: () => dispatch(openNewSimulationModal()) - }; + return { + onClick: () => dispatch(openNewSimulationModal()) + }; }; -const NewSimulationButtonContainer = connect( - undefined, - mapDispatchToProps -)(NewSimulationButtonComponent); +const NewSimulationButtonContainer = connect(undefined, mapDispatchToProps)( + NewSimulationButtonComponent +); export default NewSimulationButtonContainer; diff --git a/src/containers/simulations/SimulationActions.js b/src/containers/simulations/SimulationActions.js index 4dc93c77..32243eff 100644 --- a/src/containers/simulations/SimulationActions.js +++ b/src/containers/simulations/SimulationActions.js @@ -1,23 +1,22 @@ -import {connect} from "react-redux"; -import {deleteSimulation} from "../../actions/simulations"; +import { connect } from "react-redux"; +import { deleteSimulation } from "../../actions/simulations"; import SimulationActionButtons from "../../components/simulations/SimulationActionButtons"; const mapStateToProps = (state, ownProps) => { - return { - simulationId: ownProps.simulationId - }; + return { + simulationId: ownProps.simulationId + }; }; const mapDispatchToProps = dispatch => { - return { - onViewUsers: (id) => {}, // TODO implement user viewing - onDelete: (id) => dispatch(deleteSimulation(id)), - }; + return { + onViewUsers: id => {}, // TODO implement user viewing + onDelete: id => dispatch(deleteSimulation(id)) + }; }; -const SimulationActions = connect( - mapStateToProps, - mapDispatchToProps -)(SimulationActionButtons); +const SimulationActions = connect(mapStateToProps, mapDispatchToProps)( + SimulationActionButtons +); export default SimulationActions; diff --git a/src/containers/simulations/VisibleSimulationAuthList.js b/src/containers/simulations/VisibleSimulationAuthList.js index 324608c6..ffc74d9e 100644 --- a/src/containers/simulations/VisibleSimulationAuthList.js +++ b/src/containers/simulations/VisibleSimulationAuthList.js @@ -1,30 +1,40 @@ -import {connect} from "react-redux"; +import { connect } from "react-redux"; import SimulationList from "../../components/simulations/SimulationAuthList"; const getVisibleSimulationAuths = (simulationAuths, filter) => { - switch (filter) { - case 'SHOW_ALL': - return simulationAuths; - case 'SHOW_OWN': - return simulationAuths.filter(simulationAuth => simulationAuth.authorizationLevel === "OWN"); - case 'SHOW_SHARED': - return simulationAuths.filter(simulationAuth => simulationAuth.authorizationLevel !== "OWN"); - default: - return simulationAuths; - } + switch (filter) { + case "SHOW_ALL": + return simulationAuths; + case "SHOW_OWN": + return simulationAuths.filter( + simulationAuth => simulationAuth.authorizationLevel === "OWN" + ); + case "SHOW_SHARED": + return simulationAuths.filter( + simulationAuth => simulationAuth.authorizationLevel !== "OWN" + ); + default: + return simulationAuths; + } }; const mapStateToProps = state => { - const denormalizedAuthorizations = state.simulationList.authorizationsOfCurrentUser.map(authorizationIds => { - const authorization = state.objects.authorization[authorizationIds]; - authorization.user = state.objects.user[authorization.userId]; - authorization.simulation = state.objects.simulation[authorization.simulationId]; - return authorization; - }); + const denormalizedAuthorizations = state.simulationList.authorizationsOfCurrentUser.map( + authorizationIds => { + const authorization = state.objects.authorization[authorizationIds]; + authorization.user = state.objects.user[authorization.userId]; + authorization.simulation = + state.objects.simulation[authorization.simulationId]; + return authorization; + } + ); - return { - authorizations: getVisibleSimulationAuths(denormalizedAuthorizations, state.simulationList.authVisibilityFilter) - }; + return { + authorizations: getVisibleSimulationAuths( + denormalizedAuthorizations, + state.simulationList.authVisibilityFilter + ) + }; }; const VisibleSimulationAuthList = connect(mapStateToProps)(SimulationList); diff --git a/src/index.js b/src/index.js index 84d5329c..dad662c4 100644 --- a/src/index.js +++ b/src/index.js @@ -1,21 +1,21 @@ import React from "react"; import ReactDOM from "react-dom"; -import {Provider} from "react-redux"; -import {setupSocketConnection} from "./api/socket"; +import { Provider } from "react-redux"; +import { setupSocketConnection } from "./api/socket"; import "./index.css"; import registerServiceWorker from "./registerServiceWorker"; import Routes from "./routes"; import configureStore from "./store/configure-store"; setupSocketConnection(() => { - const store = configureStore(); + const store = configureStore(); - ReactDOM.render( - <Provider store={store}> - <Routes/> - </Provider>, - document.getElementById('root') - ); + ReactDOM.render( + <Provider store={store}> + <Routes /> + </Provider>, + document.getElementById("root") + ); - registerServiceWorker(); + registerServiceWorker(); }); diff --git a/src/pages/App.js b/src/pages/App.js index 801aefcd..ad201e7d 100644 --- a/src/pages/App.js +++ b/src/pages/App.js @@ -1,11 +1,11 @@ import PropTypes from "prop-types"; import React from "react"; import DocumentTitle from "react-document-title"; -import {connect} from "react-redux"; -import {ShortcutManager} from "react-shortcuts"; -import {openExperimentSucceeded} from "../actions/experiments"; -import {openSimulationSucceeded} from "../actions/simulations"; -import {resetCurrentDatacenter} from "../actions/topology/building"; +import { connect } from "react-redux"; +import { ShortcutManager } from "react-shortcuts"; +import { openExperimentSucceeded } from "../actions/experiments"; +import { openSimulationSucceeded } from "../actions/simulations"; +import { resetCurrentDatacenter } from "../actions/topology/building"; import ToolPanelComponent from "../components/app/map/controls/ToolPanelComponent"; import LoadingScreen from "../components/app/map/LoadingScreen"; import SimulationSidebarComponent from "../components/app/sidebars/simulation/SimulationSidebarComponent"; @@ -24,92 +24,102 @@ import KeymapConfiguration from "../shortcuts/keymap"; const shortcutManager = new ShortcutManager(KeymapConfiguration); class AppComponent extends React.Component { - static propTypes = { - simulationId: PropTypes.number.isRequired, - inSimulation: PropTypes.bool, - experimentId: PropTypes.number, - simulationName: PropTypes.string, - }; - static childContextTypes = { - shortcuts: PropTypes.object.isRequired - }; + static propTypes = { + simulationId: PropTypes.number.isRequired, + inSimulation: PropTypes.bool, + experimentId: PropTypes.number, + simulationName: PropTypes.string + }; + static childContextTypes = { + shortcuts: PropTypes.object.isRequired + }; - componentDidMount() { - this.props.resetCurrentDatacenter(); - if (this.props.inSimulation) { - this.props.openExperimentSucceeded(this.props.simulationId, this.props.experimentId); - return; - } - this.props.openSimulationSucceeded(this.props.simulationId); + componentDidMount() { + this.props.resetCurrentDatacenter(); + if (this.props.inSimulation) { + this.props.openExperimentSucceeded( + this.props.simulationId, + this.props.experimentId + ); + return; } + this.props.openSimulationSucceeded(this.props.simulationId); + } - getChildContext() { - return { - shortcuts: shortcutManager - } - } + getChildContext() { + return { + shortcuts: shortcutManager + }; + } - render() { - return ( - <DocumentTitle - title={this.props.simulationName ? this.props.simulationName + " - OpenDC" : "Simulation - OpenDC"} - > - <div className="page-container full-height"> - <AppNavbar simulationId={this.props.simulationId} inSimulation={true} fullWidth={true}/> - {this.props.datacenterIsLoading ? - <div className="full-height d-flex align-items-center justify-content-center"> - <LoadingScreen/> - </div> : - <div className="full-height"> - <MapStage/> - <ScaleIndicatorContainer/> - <ToolPanelComponent/> - <TopologySidebar/> - {this.props.inSimulation ? - <TimelineContainer/> : - undefined - } - {this.props.inSimulation ? - <SimulationSidebarComponent/> : - undefined - } - </div> - } - <EditRoomNameModal/> - <DeleteRoomModal/> - <EditRackNameModal/> - <DeleteRackModal/> - <DeleteMachineModal/> - </div> - </DocumentTitle> - ); - } + render() { + return ( + <DocumentTitle + title={ + this.props.simulationName + ? this.props.simulationName + " - OpenDC" + : "Simulation - OpenDC" + } + > + <div className="page-container full-height"> + <AppNavbar + simulationId={this.props.simulationId} + inSimulation={true} + fullWidth={true} + /> + {this.props.datacenterIsLoading ? ( + <div className="full-height d-flex align-items-center justify-content-center"> + <LoadingScreen /> + </div> + ) : ( + <div className="full-height"> + <MapStage /> + <ScaleIndicatorContainer /> + <ToolPanelComponent /> + <TopologySidebar /> + {this.props.inSimulation ? <TimelineContainer /> : undefined} + {this.props.inSimulation ? ( + <SimulationSidebarComponent /> + ) : ( + undefined + )} + </div> + )} + <EditRoomNameModal /> + <DeleteRoomModal /> + <EditRackNameModal /> + <DeleteRackModal /> + <DeleteMachineModal /> + </div> + </DocumentTitle> + ); + } } const mapStateToProps = state => { - let simulationName = undefined; - if (state.currentSimulationId !== -1 && state.objects.simulation[state.currentSimulationId]) { - simulationName = state.objects.simulation[state.currentSimulationId].name; - } + let simulationName = undefined; + if ( + state.currentSimulationId !== -1 && + state.objects.simulation[state.currentSimulationId] + ) { + simulationName = state.objects.simulation[state.currentSimulationId].name; + } - return { - datacenterIsLoading: state.currentDatacenterId === -1, - simulationName, - }; + return { + datacenterIsLoading: state.currentDatacenterId === -1, + simulationName + }; }; const mapDispatchToProps = dispatch => { - return { - resetCurrentDatacenter: () => dispatch(resetCurrentDatacenter()), - openSimulationSucceeded: id => dispatch(openSimulationSucceeded(id)), - openExperimentSucceeded: (simulationId, experimentId) => - dispatch(openExperimentSucceeded(simulationId, experimentId)), - }; + return { + resetCurrentDatacenter: () => dispatch(resetCurrentDatacenter()), + openSimulationSucceeded: id => dispatch(openSimulationSucceeded(id)), + openExperimentSucceeded: (simulationId, experimentId) => + dispatch(openExperimentSucceeded(simulationId, experimentId)) + }; }; -const App = connect( - mapStateToProps, - mapDispatchToProps -)(AppComponent); +const App = connect(mapStateToProps, mapDispatchToProps)(AppComponent); export default App; diff --git a/src/pages/Experiments.js b/src/pages/Experiments.js index c56ad5ce..2f73cd7e 100644 --- a/src/pages/Experiments.js +++ b/src/pages/Experiments.js @@ -1,66 +1,75 @@ import PropTypes from "prop-types"; import React from "react"; import DocumentTitle from "react-document-title"; -import {connect} from "react-redux"; -import {fetchExperimentsOfSimulation} from "../actions/experiments"; -import {openSimulationSucceeded} from "../actions/simulations"; +import { connect } from "react-redux"; +import { fetchExperimentsOfSimulation } from "../actions/experiments"; +import { openSimulationSucceeded } from "../actions/simulations"; import AppNavbar from "../components/navigation/AppNavbar"; import ExperimentListContainer from "../containers/experiments/ExperimentListContainer"; import NewExperimentButtonContainer from "../containers/experiments/NewExperimentButtonContainer"; import NewExperimentModal from "../containers/modals/NewExperimentModal"; class ExperimentsComponent extends React.Component { - static propTypes = { - simulationId: PropTypes.number.isRequired, - simulationName: PropTypes.string, - }; + static propTypes = { + simulationId: PropTypes.number.isRequired, + simulationName: PropTypes.string + }; - componentDidMount() { - this.props.storeSimulationId(this.props.simulationId); - this.props.fetchExperimentsOfSimulation(this.props.simulationId); - } + componentDidMount() { + this.props.storeSimulationId(this.props.simulationId); + this.props.fetchExperimentsOfSimulation(this.props.simulationId); + } - render() { - return ( - <DocumentTitle - title={this.props.simulationName ? - "Experiments - " + this.props.simulationName + " - OpenDC" : - "Experiments - OpenDC"} - > - <div className="full-height"> - <AppNavbar simulationId={this.props.simulationId} inSimulation={true} fullWidth={true}/> - <div className="container text-page-container full-height"> - <ExperimentListContainer/> - <NewExperimentButtonContainer/> - </div> - <NewExperimentModal/> - </div> - </DocumentTitle> - ); - } + render() { + return ( + <DocumentTitle + title={ + this.props.simulationName + ? "Experiments - " + this.props.simulationName + " - OpenDC" + : "Experiments - OpenDC" + } + > + <div className="full-height"> + <AppNavbar + simulationId={this.props.simulationId} + inSimulation={true} + fullWidth={true} + /> + <div className="container text-page-container full-height"> + <ExperimentListContainer /> + <NewExperimentButtonContainer /> + </div> + <NewExperimentModal /> + </div> + </DocumentTitle> + ); + } } const mapStateToProps = state => { - let simulationName = undefined; - if (state.currentSimulationId !== -1 && state.objects.simulation[state.currentSimulationId]) { - simulationName = state.objects.simulation[state.currentSimulationId].name; - } + let simulationName = undefined; + if ( + state.currentSimulationId !== -1 && + state.objects.simulation[state.currentSimulationId] + ) { + simulationName = state.objects.simulation[state.currentSimulationId].name; + } - return { - simulationName, - }; + return { + simulationName + }; }; const mapDispatchToProps = dispatch => { - return { - storeSimulationId: id => dispatch(openSimulationSucceeded(id)), - fetchExperimentsOfSimulation: id => dispatch(fetchExperimentsOfSimulation(id)), - }; + return { + storeSimulationId: id => dispatch(openSimulationSucceeded(id)), + fetchExperimentsOfSimulation: id => + dispatch(fetchExperimentsOfSimulation(id)) + }; }; -const Experiments = connect( - mapStateToProps, - mapDispatchToProps -)(ExperimentsComponent); +const Experiments = connect(mapStateToProps, mapDispatchToProps)( + ExperimentsComponent +); export default Experiments; diff --git a/src/pages/Home.js b/src/pages/Home.js index 03df4dc5..f6479722 100644 --- a/src/pages/Home.js +++ b/src/pages/Home.js @@ -1,4 +1,4 @@ -import React from 'react'; +import React from "react"; import DocumentTitle from "react-document-title"; import ContactSection from "../components/home/ContactSection"; import IntroSection from "../components/home/IntroSection"; @@ -13,48 +13,50 @@ import jQuery from "../util/jquery"; import "./Home.css"; class Home extends React.Component { - state = { - scrollSpySetup: false, - }; + state = { + scrollSpySetup: false + }; - componentDidMount() { - const scrollOffset = 60; - jQuery("#navbar").find("li a").click(function (e) { - if (jQuery(e.target).parents(".auth-links").length > 0) { - return; - } - e.preventDefault(); - jQuery(jQuery(this).attr('href'))[0].scrollIntoView(); - window.scrollBy(0, -scrollOffset); - }); - - if (!this.state.scrollSpySetup) { - jQuery("body").scrollspy({ - target: "#navbar", - offset: scrollOffset - }); - this.setState({scrollSpySetup: true}); + componentDidMount() { + const scrollOffset = 60; + jQuery("#navbar") + .find("li a") + .click(function(e) { + if (jQuery(e.target).parents(".auth-links").length > 0) { + return; } - } + e.preventDefault(); + jQuery(jQuery(this).attr("href"))[0].scrollIntoView(); + window.scrollBy(0, -scrollOffset); + }); - render() { - return ( - <div> - <HomeNavbar/> - <div className="body-wrapper page-container"> - <JumbotronHeader/> - <IntroSection/> - <StakeholderSection/> - <ModelingSection/> - <SimulationSection/> - <TechnologiesSection/> - <TeamSection/> - <ContactSection/> - <DocumentTitle title="OpenDC"/> - </div> - </div> - ); + if (!this.state.scrollSpySetup) { + jQuery("body").scrollspy({ + target: "#navbar", + offset: scrollOffset + }); + this.setState({ scrollSpySetup: true }); } + } + + render() { + return ( + <div> + <HomeNavbar /> + <div className="body-wrapper page-container"> + <JumbotronHeader /> + <IntroSection /> + <StakeholderSection /> + <ModelingSection /> + <SimulationSection /> + <TechnologiesSection /> + <TeamSection /> + <ContactSection /> + <DocumentTitle title="OpenDC" /> + </div> + </div> + ); + } } export default Home; diff --git a/src/pages/NotFound.js b/src/pages/NotFound.js index 4120e285..b344e923 100644 --- a/src/pages/NotFound.js +++ b/src/pages/NotFound.js @@ -1,14 +1,14 @@ -import React from 'react'; +import React from "react"; import DocumentTitle from "react-document-title"; import TerminalWindow from "../components/not-found/TerminalWindow"; -import './NotFound.css'; +import "./NotFound.css"; const NotFound = () => ( - <DocumentTitle title="Page Not Found - OpenDC"> - <div className="not-found-backdrop"> - <TerminalWindow/> - </div> - </DocumentTitle> + <DocumentTitle title="Page Not Found - OpenDC"> + <div className="not-found-backdrop"> + <TerminalWindow /> + </div> + </DocumentTitle> ); export default NotFound; diff --git a/src/pages/Profile.js b/src/pages/Profile.js index 8a418f80..106ec97e 100644 --- a/src/pages/Profile.js +++ b/src/pages/Profile.js @@ -1,42 +1,40 @@ -import React from 'react'; +import React from "react"; import DocumentTitle from "react-document-title"; -import {connect} from "react-redux"; -import {openDeleteProfileModal} from "../actions/modals/profile"; +import { connect } from "react-redux"; +import { openDeleteProfileModal } from "../actions/modals/profile"; import AppNavbar from "../components/navigation/AppNavbar"; import DeleteProfileModal from "../containers/modals/DeleteProfileModal"; -const ProfileContainer = ({onDelete}) => ( - <DocumentTitle title="My Profile - OpenDC"> - <div className="full-height"> - <AppNavbar inSimulation={false} fullWidth={false}/> - <div className="container text-page-container full-height"> - <button - className="btn btn-danger mb-2 ml-auto mr-auto" - style={{maxWidth: 300}} - onClick={onDelete} - > - Delete my account on OpenDC - </button> - <p className="text-muted text-center"> - This does not delete your Google account, but simply disconnects it from the OpenDC platform and - deletes any simulation info that is associated with you (simulations you own and any authorizations - you may have on other projects). - </p> - </div> - <DeleteProfileModal/> - </div> - </DocumentTitle> +const ProfileContainer = ({ onDelete }) => ( + <DocumentTitle title="My Profile - OpenDC"> + <div className="full-height"> + <AppNavbar inSimulation={false} fullWidth={false} /> + <div className="container text-page-container full-height"> + <button + className="btn btn-danger mb-2 ml-auto mr-auto" + style={{ maxWidth: 300 }} + onClick={onDelete} + > + Delete my account on OpenDC + </button> + <p className="text-muted text-center"> + This does not delete your Google account, but simply disconnects it + from the OpenDC platform and deletes any simulation info that is + associated with you (simulations you own and any authorizations you + may have on other projects). + </p> + </div> + <DeleteProfileModal /> + </div> + </DocumentTitle> ); const mapDispatchToProps = dispatch => { - return { - onDelete: () => dispatch(openDeleteProfileModal()), - }; + return { + onDelete: () => dispatch(openDeleteProfileModal()) + }; }; -const Profile = connect( - undefined, - mapDispatchToProps -)(ProfileContainer); +const Profile = connect(undefined, mapDispatchToProps)(ProfileContainer); export default Profile; diff --git a/src/pages/Simulations.js b/src/pages/Simulations.js index 46b2843c..ecff8fe6 100644 --- a/src/pages/Simulations.js +++ b/src/pages/Simulations.js @@ -1,8 +1,8 @@ -import React from 'react'; +import React from "react"; import DocumentTitle from "react-document-title"; -import {connect} from "react-redux"; -import {openNewSimulationModal} from "../actions/modals/simulations"; -import {fetchAuthorizationsOfCurrentUser} from "../actions/users"; +import { connect } from "react-redux"; +import { openNewSimulationModal } from "../actions/modals/simulations"; +import { fetchAuthorizationsOfCurrentUser } from "../actions/users"; import AppNavbar from "../components/navigation/AppNavbar"; import SimulationFilterPanel from "../components/simulations/FilterPanel"; import NewSimulationModal from "../containers/modals/NewSimulationModal"; @@ -10,37 +10,37 @@ import NewSimulationButtonContainer from "../containers/simulations/NewSimulatio import VisibleSimulationList from "../containers/simulations/VisibleSimulationAuthList"; class SimulationsContainer extends React.Component { - componentDidMount() { - this.props.fetchAuthorizationsOfCurrentUser(); - } + componentDidMount() { + this.props.fetchAuthorizationsOfCurrentUser(); + } - render() { - return ( - <DocumentTitle title="My Simulations - OpenDC"> - <div className="full-height"> - <AppNavbar inSimulation={false} fullWidth={false}/> - <div className="container text-page-container full-height"> - <SimulationFilterPanel/> - <VisibleSimulationList/> - <NewSimulationButtonContainer/> - </div> - <NewSimulationModal/> - </div> - </DocumentTitle> - ); - } + render() { + return ( + <DocumentTitle title="My Simulations - OpenDC"> + <div className="full-height"> + <AppNavbar inSimulation={false} fullWidth={false} /> + <div className="container text-page-container full-height"> + <SimulationFilterPanel /> + <VisibleSimulationList /> + <NewSimulationButtonContainer /> + </div> + <NewSimulationModal /> + </div> + </DocumentTitle> + ); + } } const mapDispatchToProps = dispatch => { - return { - fetchAuthorizationsOfCurrentUser: () => dispatch(fetchAuthorizationsOfCurrentUser()), - openNewSimulationModal: () => dispatch(openNewSimulationModal()), - }; + return { + fetchAuthorizationsOfCurrentUser: () => + dispatch(fetchAuthorizationsOfCurrentUser()), + openNewSimulationModal: () => dispatch(openNewSimulationModal()) + }; }; -const Simulations = connect( - undefined, - mapDispatchToProps -)(SimulationsContainer); +const Simulations = connect(undefined, mapDispatchToProps)( + SimulationsContainer +); export default Simulations; diff --git a/src/reducers/auth.js b/src/reducers/auth.js index a65b3b3e..635929d4 100644 --- a/src/reducers/auth.js +++ b/src/reducers/auth.js @@ -1,12 +1,12 @@ -import {LOG_IN_SUCCEEDED, LOG_OUT} from "../actions/auth"; +import { LOG_IN_SUCCEEDED, LOG_OUT } from "../actions/auth"; export function auth(state = {}, action) { - switch (action.type) { - case LOG_IN_SUCCEEDED: - return action.payload; - case LOG_OUT: - return {}; - default: - return state; - } + switch (action.type) { + case LOG_IN_SUCCEEDED: + return action.payload; + case LOG_OUT: + return {}; + default: + return state; + } } diff --git a/src/reducers/construction-mode.js b/src/reducers/construction-mode.js index e97c817e..4778bd44 100644 --- a/src/reducers/construction-mode.js +++ b/src/reducers/construction-mode.js @@ -1,38 +1,41 @@ -import {combineReducers} from "redux"; -import {OPEN_EXPERIMENT_SUCCEEDED} from "../actions/experiments"; +import { combineReducers } from "redux"; +import { OPEN_EXPERIMENT_SUCCEEDED } from "../actions/experiments"; import { - CANCEL_NEW_ROOM_CONSTRUCTION_SUCCEEDED, - FINISH_NEW_ROOM_CONSTRUCTION, - START_NEW_ROOM_CONSTRUCTION_SUCCEEDED + CANCEL_NEW_ROOM_CONSTRUCTION_SUCCEEDED, + FINISH_NEW_ROOM_CONSTRUCTION, + START_NEW_ROOM_CONSTRUCTION_SUCCEEDED } from "../actions/topology/building"; -import {START_RACK_CONSTRUCTION, STOP_RACK_CONSTRUCTION} from "../actions/topology/room"; +import { + START_RACK_CONSTRUCTION, + STOP_RACK_CONSTRUCTION +} from "../actions/topology/room"; export function currentRoomInConstruction(state = -1, action) { - switch (action.type) { - case START_NEW_ROOM_CONSTRUCTION_SUCCEEDED: - return action.roomId; - case CANCEL_NEW_ROOM_CONSTRUCTION_SUCCEEDED: - case FINISH_NEW_ROOM_CONSTRUCTION: - case OPEN_EXPERIMENT_SUCCEEDED: - return -1; - default: - return state; - } + switch (action.type) { + case START_NEW_ROOM_CONSTRUCTION_SUCCEEDED: + return action.roomId; + case CANCEL_NEW_ROOM_CONSTRUCTION_SUCCEEDED: + case FINISH_NEW_ROOM_CONSTRUCTION: + case OPEN_EXPERIMENT_SUCCEEDED: + return -1; + default: + return state; + } } export function inRackConstructionMode(state = false, action) { - switch (action.type) { - case START_RACK_CONSTRUCTION: - return true; - case STOP_RACK_CONSTRUCTION: - case OPEN_EXPERIMENT_SUCCEEDED: - return false; - default: - return state; - } + switch (action.type) { + case START_RACK_CONSTRUCTION: + return true; + case STOP_RACK_CONSTRUCTION: + case OPEN_EXPERIMENT_SUCCEEDED: + return false; + default: + return state; + } } export const construction = combineReducers({ - currentRoomInConstruction, - inRackConstructionMode, + currentRoomInConstruction, + inRackConstructionMode }); diff --git a/src/reducers/current-ids.js b/src/reducers/current-ids.js index c92ff93b..4e16630d 100644 --- a/src/reducers/current-ids.js +++ b/src/reducers/current-ids.js @@ -1,26 +1,28 @@ -import {OPEN_EXPERIMENT_SUCCEEDED} from "../actions/experiments"; -import {OPEN_SIMULATION_SUCCEEDED} from "../actions/simulations"; -import {RESET_CURRENT_DATACENTER, SET_CURRENT_DATACENTER} from "../actions/topology/building"; +import { OPEN_EXPERIMENT_SUCCEEDED } from "../actions/experiments"; +import { OPEN_SIMULATION_SUCCEEDED } from "../actions/simulations"; +import { + RESET_CURRENT_DATACENTER, + SET_CURRENT_DATACENTER +} from "../actions/topology/building"; export function currentDatacenterId(state = -1, action) { - switch (action.type) { - case SET_CURRENT_DATACENTER: - return action.datacenterId; - case RESET_CURRENT_DATACENTER: - return -1; - default: - return state; - } + switch (action.type) { + case SET_CURRENT_DATACENTER: + return action.datacenterId; + case RESET_CURRENT_DATACENTER: + return -1; + default: + return state; + } } export function currentSimulationId(state = -1, action) { - switch (action.type) { - case OPEN_SIMULATION_SUCCEEDED: - return action.id; - case OPEN_EXPERIMENT_SUCCEEDED: - return action.simulationId; - default: - return state; - } + switch (action.type) { + case OPEN_SIMULATION_SUCCEEDED: + return action.id; + case OPEN_EXPERIMENT_SUCCEEDED: + return action.simulationId; + default: + return state; + } } - diff --git a/src/reducers/index.js b/src/reducers/index.js index 17b75182..6f4d0c94 100644 --- a/src/reducers/index.js +++ b/src/reducers/index.js @@ -1,31 +1,37 @@ -import {combineReducers} from "redux"; -import {auth} from "./auth"; -import {construction} from "./construction-mode"; -import {currentDatacenterId, currentSimulationId} from "./current-ids"; -import {interactionLevel} from "./interaction-level"; -import {map} from "./map"; -import {modals} from "./modals"; -import {objects} from "./objects"; -import {simulationList} from "./simulation-list"; -import {currentExperimentId, currentTick, isPlaying, lastSimulatedTick, loadMetric} from "./simulation-mode"; -import {states} from "./states"; +import { combineReducers } from "redux"; +import { auth } from "./auth"; +import { construction } from "./construction-mode"; +import { currentDatacenterId, currentSimulationId } from "./current-ids"; +import { interactionLevel } from "./interaction-level"; +import { map } from "./map"; +import { modals } from "./modals"; +import { objects } from "./objects"; +import { simulationList } from "./simulation-list"; +import { + currentExperimentId, + currentTick, + isPlaying, + lastSimulatedTick, + loadMetric +} from "./simulation-mode"; +import { states } from "./states"; const rootReducer = combineReducers({ - objects, - states, - modals, - simulationList, - construction, - map, - currentSimulationId, - currentDatacenterId, - currentExperimentId, - currentTick, - lastSimulatedTick, - loadMetric, - isPlaying, - interactionLevel, - auth, + objects, + states, + modals, + simulationList, + construction, + map, + currentSimulationId, + currentDatacenterId, + currentExperimentId, + currentTick, + lastSimulatedTick, + loadMetric, + isPlaying, + interactionLevel, + auth }); export default rootReducer; diff --git a/src/reducers/interaction-level.js b/src/reducers/interaction-level.js index 5a45fc68..581906c5 100644 --- a/src/reducers/interaction-level.js +++ b/src/reducers/interaction-level.js @@ -1,59 +1,59 @@ -import {OPEN_EXPERIMENT_SUCCEEDED} from "../actions/experiments"; +import { OPEN_EXPERIMENT_SUCCEEDED } from "../actions/experiments"; import { - GO_DOWN_ONE_INTERACTION_LEVEL, - GO_FROM_BUILDING_TO_ROOM, - GO_FROM_RACK_TO_MACHINE, - GO_FROM_ROOM_TO_RACK + GO_DOWN_ONE_INTERACTION_LEVEL, + GO_FROM_BUILDING_TO_ROOM, + GO_FROM_RACK_TO_MACHINE, + GO_FROM_ROOM_TO_RACK } from "../actions/interaction-level"; -import {OPEN_SIMULATION_SUCCEEDED} from "../actions/simulations"; -import {SET_CURRENT_DATACENTER} from "../actions/topology/building"; +import { OPEN_SIMULATION_SUCCEEDED } from "../actions/simulations"; +import { SET_CURRENT_DATACENTER } from "../actions/topology/building"; -export function interactionLevel(state = {mode: "BUILDING"}, action) { - switch (action.type) { - case OPEN_EXPERIMENT_SUCCEEDED: - case OPEN_SIMULATION_SUCCEEDED: - case SET_CURRENT_DATACENTER: - return { - mode: "BUILDING" - }; - case GO_FROM_BUILDING_TO_ROOM: - return { - mode: "ROOM", - roomId: action.roomId - }; - case GO_FROM_ROOM_TO_RACK: - return { - mode: "RACK", - roomId: state.roomId, - tileId: action.tileId - }; - case GO_FROM_RACK_TO_MACHINE: - return { - mode: "MACHINE", - roomId: state.roomId, - tileId: state.tileId, - position: action.position, - }; - case GO_DOWN_ONE_INTERACTION_LEVEL: - if (state.mode === "ROOM") { - return { - mode: "BUILDING" - }; - } else if (state.mode === "RACK") { - return { - mode: "ROOM", - roomId: state.roomId - }; - } else if (state.mode === "MACHINE") { - return { - mode: "RACK", - roomId: state.roomId, - tileId: state.tileId - }; - } else { - return state; - } - default: - return state; - } +export function interactionLevel(state = { mode: "BUILDING" }, action) { + switch (action.type) { + case OPEN_EXPERIMENT_SUCCEEDED: + case OPEN_SIMULATION_SUCCEEDED: + case SET_CURRENT_DATACENTER: + return { + mode: "BUILDING" + }; + case GO_FROM_BUILDING_TO_ROOM: + return { + mode: "ROOM", + roomId: action.roomId + }; + case GO_FROM_ROOM_TO_RACK: + return { + mode: "RACK", + roomId: state.roomId, + tileId: action.tileId + }; + case GO_FROM_RACK_TO_MACHINE: + return { + mode: "MACHINE", + roomId: state.roomId, + tileId: state.tileId, + position: action.position + }; + case GO_DOWN_ONE_INTERACTION_LEVEL: + if (state.mode === "ROOM") { + return { + mode: "BUILDING" + }; + } else if (state.mode === "RACK") { + return { + mode: "ROOM", + roomId: state.roomId + }; + } else if (state.mode === "MACHINE") { + return { + mode: "RACK", + roomId: state.roomId, + tileId: state.tileId + }; + } else { + return state; + } + default: + return state; + } } diff --git a/src/reducers/map.js b/src/reducers/map.js index c36916b6..b75dc051 100644 --- a/src/reducers/map.js +++ b/src/reducers/map.js @@ -1,35 +1,39 @@ -import {combineReducers} from "redux"; -import {SET_MAP_DIMENSIONS, SET_MAP_POSITION, SET_MAP_SCALE} from "../actions/map"; +import { combineReducers } from "redux"; +import { + SET_MAP_DIMENSIONS, + SET_MAP_POSITION, + SET_MAP_SCALE +} from "../actions/map"; -export function position(state = {x: 0, y: 0}, action) { - switch (action.type) { - case SET_MAP_POSITION: - return {x: action.x, y: action.y}; - default: - return state; - } +export function position(state = { x: 0, y: 0 }, action) { + switch (action.type) { + case SET_MAP_POSITION: + return { x: action.x, y: action.y }; + default: + return state; + } } -export function dimensions(state = {width: 600, height: 400}, action) { - switch (action.type) { - case SET_MAP_DIMENSIONS: - return {width: action.width, height: action.height}; - default: - return state; - } +export function dimensions(state = { width: 600, height: 400 }, action) { + switch (action.type) { + case SET_MAP_DIMENSIONS: + return { width: action.width, height: action.height }; + default: + return state; + } } export function scale(state = 1, action) { - switch (action.type) { - case SET_MAP_SCALE: - return action.scale; - default: - return state; - } + switch (action.type) { + case SET_MAP_SCALE: + return action.scale; + default: + return state; + } } export const map = combineReducers({ - position, - dimensions, - scale + position, + dimensions, + scale }); diff --git a/src/reducers/modals.js b/src/reducers/modals.js index 3e9f0327..78527feb 100644 --- a/src/reducers/modals.js +++ b/src/reducers/modals.js @@ -1,42 +1,75 @@ -import {combineReducers} from "redux"; -import {OPEN_EXPERIMENT_SUCCEEDED} from "../actions/experiments"; -import {CLOSE_NEW_EXPERIMENT_MODAL, OPEN_NEW_EXPERIMENT_MODAL} from "../actions/modals/experiments"; -import {CLOSE_DELETE_PROFILE_MODAL, OPEN_DELETE_PROFILE_MODAL} from "../actions/modals/profile"; -import {CLOSE_NEW_SIMULATION_MODAL, OPEN_NEW_SIMULATION_MODAL} from "../actions/modals/simulations"; +import { combineReducers } from "redux"; +import { OPEN_EXPERIMENT_SUCCEEDED } from "../actions/experiments"; import { - CLOSE_DELETE_MACHINE_MODAL, - CLOSE_DELETE_RACK_MODAL, - CLOSE_DELETE_ROOM_MODAL, - CLOSE_EDIT_RACK_NAME_MODAL, - CLOSE_EDIT_ROOM_NAME_MODAL, - OPEN_DELETE_MACHINE_MODAL, - OPEN_DELETE_RACK_MODAL, - OPEN_DELETE_ROOM_MODAL, - OPEN_EDIT_RACK_NAME_MODAL, - OPEN_EDIT_ROOM_NAME_MODAL + CLOSE_NEW_EXPERIMENT_MODAL, + OPEN_NEW_EXPERIMENT_MODAL +} from "../actions/modals/experiments"; +import { + CLOSE_DELETE_PROFILE_MODAL, + OPEN_DELETE_PROFILE_MODAL +} from "../actions/modals/profile"; +import { + CLOSE_NEW_SIMULATION_MODAL, + OPEN_NEW_SIMULATION_MODAL +} from "../actions/modals/simulations"; +import { + CLOSE_DELETE_MACHINE_MODAL, + CLOSE_DELETE_RACK_MODAL, + CLOSE_DELETE_ROOM_MODAL, + CLOSE_EDIT_RACK_NAME_MODAL, + CLOSE_EDIT_ROOM_NAME_MODAL, + OPEN_DELETE_MACHINE_MODAL, + OPEN_DELETE_RACK_MODAL, + OPEN_DELETE_ROOM_MODAL, + OPEN_EDIT_RACK_NAME_MODAL, + OPEN_EDIT_ROOM_NAME_MODAL } from "../actions/modals/topology"; function modal(openAction, closeAction) { - return function (state = false, action) { - switch (action.type) { - case openAction: - return true; - case closeAction: - case OPEN_EXPERIMENT_SUCCEEDED: - return false; - default: - return state; - } + return function(state = false, action) { + switch (action.type) { + case openAction: + return true; + case closeAction: + case OPEN_EXPERIMENT_SUCCEEDED: + return false; + default: + return state; } + }; } export const modals = combineReducers({ - newSimulationModalVisible: modal(OPEN_NEW_SIMULATION_MODAL, CLOSE_NEW_SIMULATION_MODAL), - deleteProfileModalVisible: modal(OPEN_DELETE_PROFILE_MODAL, CLOSE_DELETE_PROFILE_MODAL), - editRoomNameModalVisible: modal(OPEN_EDIT_ROOM_NAME_MODAL, CLOSE_EDIT_ROOM_NAME_MODAL), - deleteRoomModalVisible: modal(OPEN_DELETE_ROOM_MODAL, CLOSE_DELETE_ROOM_MODAL), - editRackNameModalVisible: modal(OPEN_EDIT_RACK_NAME_MODAL, CLOSE_EDIT_RACK_NAME_MODAL), - deleteRackModalVisible: modal(OPEN_DELETE_RACK_MODAL, CLOSE_DELETE_RACK_MODAL), - deleteMachineModalVisible: modal(OPEN_DELETE_MACHINE_MODAL, CLOSE_DELETE_MACHINE_MODAL), - newExperimentModalVisible: modal(OPEN_NEW_EXPERIMENT_MODAL, CLOSE_NEW_EXPERIMENT_MODAL), + newSimulationModalVisible: modal( + OPEN_NEW_SIMULATION_MODAL, + CLOSE_NEW_SIMULATION_MODAL + ), + deleteProfileModalVisible: modal( + OPEN_DELETE_PROFILE_MODAL, + CLOSE_DELETE_PROFILE_MODAL + ), + editRoomNameModalVisible: modal( + OPEN_EDIT_ROOM_NAME_MODAL, + CLOSE_EDIT_ROOM_NAME_MODAL + ), + deleteRoomModalVisible: modal( + OPEN_DELETE_ROOM_MODAL, + CLOSE_DELETE_ROOM_MODAL + ), + editRackNameModalVisible: modal( + OPEN_EDIT_RACK_NAME_MODAL, + CLOSE_EDIT_RACK_NAME_MODAL + ), + deleteRackModalVisible: modal( + OPEN_DELETE_RACK_MODAL, + CLOSE_DELETE_RACK_MODAL + ), + deleteMachineModalVisible: modal( + OPEN_DELETE_MACHINE_MODAL, + CLOSE_DELETE_MACHINE_MODAL + ), + newExperimentModalVisible: modal( + OPEN_NEW_EXPERIMENT_MODAL, + CLOSE_NEW_EXPERIMENT_MODAL + ) }); diff --git a/src/reducers/objects.js b/src/reducers/objects.js index df148dee..99d91092 100644 --- a/src/reducers/objects.js +++ b/src/reducers/objects.js @@ -1,90 +1,80 @@ -import {combineReducers} from "redux"; +import { combineReducers } from "redux"; import { - ADD_ID_TO_STORE_OBJECT_LIST_PROP, - ADD_PROP_TO_STORE_OBJECT, - ADD_TO_STORE, - REMOVE_ID_FROM_STORE_OBJECT_LIST_PROP + ADD_ID_TO_STORE_OBJECT_LIST_PROP, + ADD_PROP_TO_STORE_OBJECT, + ADD_TO_STORE, + REMOVE_ID_FROM_STORE_OBJECT_LIST_PROP } from "../actions/objects"; export const objects = combineReducers({ - simulation: object("simulation"), - user: object("user"), - authorization: objectWithId("authorization", object => [object.userId, object.simulationId]), - failureModel: object("failureModel"), - cpu: object("cpu"), - gpu: object("gpu"), - memory: object("memory"), - storage: object("storage"), - machine: object("machine"), - rack: object("rack"), - coolingItem: object("coolingItem"), - psu: object("psu"), - tile: object("tile"), - room: object("room"), - datacenter: object("datacenter"), - section: object("section"), - path: object("path"), - task: object("task"), - job: object("job"), - trace: object("trace"), - scheduler: object("scheduler"), - experiment: object("experiment"), + simulation: object("simulation"), + user: object("user"), + authorization: objectWithId("authorization", object => [ + object.userId, + object.simulationId + ]), + failureModel: object("failureModel"), + cpu: object("cpu"), + gpu: object("gpu"), + memory: object("memory"), + storage: object("storage"), + machine: object("machine"), + rack: object("rack"), + coolingItem: object("coolingItem"), + psu: object("psu"), + tile: object("tile"), + room: object("room"), + datacenter: object("datacenter"), + section: object("section"), + path: object("path"), + task: object("task"), + job: object("job"), + trace: object("trace"), + scheduler: object("scheduler"), + experiment: object("experiment") }); function object(type) { - return objectWithId(type, object => object.id); + return objectWithId(type, object => object.id); } function objectWithId(type, getId) { - return (state = {}, action) => { - if (action.objectType !== type) { - return state; - } + return (state = {}, action) => { + if (action.objectType !== type) { + return state; + } - if (action.type === ADD_TO_STORE) { - return Object.assign( - {}, - state, - {[getId(action.object)]: action.object} - ); - } else if (action.type === ADD_PROP_TO_STORE_OBJECT) { - return Object.assign( - {}, - state, - { - [action.objectId]: Object.assign( - {}, - state[action.objectId], - action.propObject - ) - } - ); - } else if (action.type === ADD_ID_TO_STORE_OBJECT_LIST_PROP) { - return Object.assign( - {}, - state, - { - [action.objectId]: Object.assign( - {}, - state[action.objectId], - {[action.propName]: [...state[action.objectId][action.propName], action.id]} - ) - } - ); - } else if (action.type === REMOVE_ID_FROM_STORE_OBJECT_LIST_PROP) { - return Object.assign( - {}, - state, - { - [action.objectId]: Object.assign( - {}, - state[action.objectId], - {[action.propName]: state[action.objectId][action.propName].filter(id => id !== action.id)} - ) - } - ); - } + if (action.type === ADD_TO_STORE) { + return Object.assign({}, state, { + [getId(action.object)]: action.object + }); + } else if (action.type === ADD_PROP_TO_STORE_OBJECT) { + return Object.assign({}, state, { + [action.objectId]: Object.assign( + {}, + state[action.objectId], + action.propObject + ) + }); + } else if (action.type === ADD_ID_TO_STORE_OBJECT_LIST_PROP) { + return Object.assign({}, state, { + [action.objectId]: Object.assign({}, state[action.objectId], { + [action.propName]: [ + ...state[action.objectId][action.propName], + action.id + ] + }) + }); + } else if (action.type === REMOVE_ID_FROM_STORE_OBJECT_LIST_PROP) { + return Object.assign({}, state, { + [action.objectId]: Object.assign({}, state[action.objectId], { + [action.propName]: state[action.objectId][action.propName].filter( + id => id !== action.id + ) + }) + }); + } - return state; - }; + return state; + }; } diff --git a/src/reducers/simulation-list.js b/src/reducers/simulation-list.js index 86386093..9afa3586 100644 --- a/src/reducers/simulation-list.js +++ b/src/reducers/simulation-list.js @@ -1,37 +1,34 @@ -import {combineReducers} from "redux"; +import { combineReducers } from "redux"; import { - ADD_SIMULATION_SUCCEEDED, - DELETE_SIMULATION_SUCCEEDED, - SET_AUTH_VISIBILITY_FILTER + ADD_SIMULATION_SUCCEEDED, + DELETE_SIMULATION_SUCCEEDED, + SET_AUTH_VISIBILITY_FILTER } from "../actions/simulations"; -import {FETCH_AUTHORIZATIONS_OF_CURRENT_USER_SUCCEEDED} from "../actions/users"; +import { FETCH_AUTHORIZATIONS_OF_CURRENT_USER_SUCCEEDED } from "../actions/users"; export function authorizationsOfCurrentUser(state = [], action) { - switch (action.type) { - case FETCH_AUTHORIZATIONS_OF_CURRENT_USER_SUCCEEDED: - return action.authorizationsOfCurrentUser; - case ADD_SIMULATION_SUCCEEDED: - return [ - ...state, - action.authorization - ]; - case DELETE_SIMULATION_SUCCEEDED: - return state.filter(authorization => authorization[1] !== action.id); - default: - return state; - } + switch (action.type) { + case FETCH_AUTHORIZATIONS_OF_CURRENT_USER_SUCCEEDED: + return action.authorizationsOfCurrentUser; + case ADD_SIMULATION_SUCCEEDED: + return [...state, action.authorization]; + case DELETE_SIMULATION_SUCCEEDED: + return state.filter(authorization => authorization[1] !== action.id); + default: + return state; + } } export function authVisibilityFilter(state = "SHOW_ALL", action) { - switch (action.type) { - case SET_AUTH_VISIBILITY_FILTER: - return action.filter; - default: - return state; - } + switch (action.type) { + case SET_AUTH_VISIBILITY_FILTER: + return action.filter; + default: + return state; + } } export const simulationList = combineReducers({ - authorizationsOfCurrentUser, - authVisibilityFilter, + authorizationsOfCurrentUser, + authVisibilityFilter }); diff --git a/src/reducers/simulation-mode.js b/src/reducers/simulation-mode.js index b13ecbcc..02041468 100644 --- a/src/reducers/simulation-mode.js +++ b/src/reducers/simulation-mode.js @@ -1,59 +1,61 @@ -import {OPEN_EXPERIMENT_SUCCEEDED} from "../actions/experiments"; -import {CHANGE_LOAD_METRIC} from "../actions/simulation/load-metric"; -import {SET_PLAYING} from "../actions/simulation/playback"; -import {GO_TO_TICK, SET_LAST_SIMULATED_TICK} from "../actions/simulation/tick"; -import {OPEN_SIMULATION_SUCCEEDED} from "../actions/simulations"; +import { OPEN_EXPERIMENT_SUCCEEDED } from "../actions/experiments"; +import { CHANGE_LOAD_METRIC } from "../actions/simulation/load-metric"; +import { SET_PLAYING } from "../actions/simulation/playback"; +import { + GO_TO_TICK, + SET_LAST_SIMULATED_TICK +} from "../actions/simulation/tick"; +import { OPEN_SIMULATION_SUCCEEDED } from "../actions/simulations"; export function currentExperimentId(state = -1, action) { - switch (action.type) { - case OPEN_EXPERIMENT_SUCCEEDED: - return action.experimentId; - case OPEN_SIMULATION_SUCCEEDED: - return -1; - default: - return state; - } + switch (action.type) { + case OPEN_EXPERIMENT_SUCCEEDED: + return action.experimentId; + case OPEN_SIMULATION_SUCCEEDED: + return -1; + default: + return state; + } } export function currentTick(state = 0, action) { - switch (action.type) { - case GO_TO_TICK: - return action.tick; - case OPEN_EXPERIMENT_SUCCEEDED: - return 0; - default: - return state; - } + switch (action.type) { + case GO_TO_TICK: + return action.tick; + case OPEN_EXPERIMENT_SUCCEEDED: + return 0; + default: + return state; + } } export function loadMetric(state = "LOAD", action) { - switch (action.type) { - case CHANGE_LOAD_METRIC: - return action.metric; - default: - return state; - } + switch (action.type) { + case CHANGE_LOAD_METRIC: + return action.metric; + default: + return state; + } } export function isPlaying(state = false, action) { - switch (action.type) { - case SET_PLAYING: - return action.playing; - case OPEN_EXPERIMENT_SUCCEEDED: - return false; - default: - return state; - } + switch (action.type) { + case SET_PLAYING: + return action.playing; + case OPEN_EXPERIMENT_SUCCEEDED: + return false; + default: + return state; + } } export function lastSimulatedTick(state = -1, action) { - switch (action.type) { - case SET_LAST_SIMULATED_TICK: - return action.tick; - case OPEN_EXPERIMENT_SUCCEEDED: - return -1; - default: - return state; - } + switch (action.type) { + case SET_LAST_SIMULATED_TICK: + return action.tick; + case OPEN_EXPERIMENT_SUCCEEDED: + return -1; + default: + return state; + } } - diff --git a/src/reducers/states.js b/src/reducers/states.js index 81f078af..793f7b7d 100644 --- a/src/reducers/states.js +++ b/src/reducers/states.js @@ -1,37 +1,33 @@ -import {combineReducers} from "redux"; -import {ADD_BATCH_TO_STATES} from "../actions/states"; +import { combineReducers } from "redux"; +import { ADD_BATCH_TO_STATES } from "../actions/states"; export const states = combineReducers({ - task: objectStates("task"), - room: objectStates("room"), - rack: objectStates("rack"), - machine: objectStates("machine"), + task: objectStates("task"), + room: objectStates("room"), + rack: objectStates("rack"), + machine: objectStates("machine") }); function objectStates(type) { - return (state = {}, action) => { - if (action.objectType !== type) { - return state; - } + return (state = {}, action) => { + if (action.objectType !== type) { + return state; + } - if (action.type === ADD_BATCH_TO_STATES) { - const batch = {}; - for (let i in action.objects) { - batch[action.objects[i].tick] = Object.assign( - {}, - state[action.objects[i].tick], - batch[action.objects[i].tick], - {[action.objects[i][action.objectType + "Id"]]: action.objects[i]} - ); - } + if (action.type === ADD_BATCH_TO_STATES) { + const batch = {}; + for (let i in action.objects) { + batch[action.objects[i].tick] = Object.assign( + {}, + state[action.objects[i].tick], + batch[action.objects[i].tick], + { [action.objects[i][action.objectType + "Id"]]: action.objects[i] } + ); + } - return Object.assign( - {}, - state, - batch - ); - } + return Object.assign({}, state, batch); + } - return state; - }; + return state; + }; } diff --git a/src/registerServiceWorker.js b/src/registerServiceWorker.js index c7ecf951..0fe89a23 100644 --- a/src/registerServiceWorker.js +++ b/src/registerServiceWorker.js @@ -9,100 +9,100 @@ // This link also includes instructions on opting out of this behavior. const isLocalhost = Boolean( - window.location.hostname === 'localhost' || + window.location.hostname === "localhost" || // [::1] is the IPv6 localhost address. - window.location.hostname === '[::1]' || + window.location.hostname === "[::1]" || // 127.0.0.1/8 is considered localhost for IPv4. window.location.hostname.match( - /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ + /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ ) ); export default function register() { - if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { - // The URL constructor is available in all browsers that support SW. - const publicUrl = new URL(process.env.PUBLIC_URL, window.location); - if (publicUrl.origin !== window.location.origin) { - // Our service worker won't work if PUBLIC_URL is on a different origin - // from what our page is served on. This might happen if a CDN is used to - // serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374 - return; - } + if (process.env.NODE_ENV === "production" && "serviceWorker" in navigator) { + // The URL constructor is available in all browsers that support SW. + const publicUrl = new URL(process.env.PUBLIC_URL, window.location); + if (publicUrl.origin !== window.location.origin) { + // Our service worker won't work if PUBLIC_URL is on a different origin + // from what our page is served on. This might happen if a CDN is used to + // serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374 + return; + } - window.addEventListener('load', () => { - const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; + window.addEventListener("load", () => { + const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; - if (!isLocalhost) { - // Is not local host. Just register service worker - registerValidSW(swUrl); - } else { - // This is running on localhost. Lets check if a service worker still exists or not. - checkValidServiceWorker(swUrl); - } - }); - } + if (!isLocalhost) { + // Is not local host. Just register service worker + registerValidSW(swUrl); + } else { + // This is running on localhost. Lets check if a service worker still exists or not. + checkValidServiceWorker(swUrl); + } + }); + } } function registerValidSW(swUrl) { - navigator.serviceWorker - .register(swUrl) - .then(registration => { - registration.onupdatefound = () => { - const installingWorker = registration.installing; - installingWorker.onstatechange = () => { - if (installingWorker.state === 'installed') { - if (navigator.serviceWorker.controller) { - // At this point, the old content will have been purged and - // the fresh content will have been added to the cache. - // It's the perfect time to display a "New content is - // available; please refresh." message in your web app. - console.log('New content is available; please refresh.'); - } else { - // At this point, everything has been precached. - // It's the perfect time to display a - // "Content is cached for offline use." message. - console.log('Content is cached for offline use.'); - } - } - }; - }; - }) - .catch(error => { - console.error('Error during service worker registration:', error); - }); + navigator.serviceWorker + .register(swUrl) + .then(registration => { + registration.onupdatefound = () => { + const installingWorker = registration.installing; + installingWorker.onstatechange = () => { + if (installingWorker.state === "installed") { + if (navigator.serviceWorker.controller) { + // At this point, the old content will have been purged and + // the fresh content will have been added to the cache. + // It's the perfect time to display a "New content is + // available; please refresh." message in your web app. + console.log("New content is available; please refresh."); + } else { + // At this point, everything has been precached. + // It's the perfect time to display a + // "Content is cached for offline use." message. + console.log("Content is cached for offline use."); + } + } + }; + }; + }) + .catch(error => { + console.error("Error during service worker registration:", error); + }); } function checkValidServiceWorker(swUrl) { - // Check if the service worker can be found. If it can't reload the page. - fetch(swUrl) - .then(response => { - // Ensure service worker exists, and that we really are getting a JS file. - if ( - response.status === 404 || - response.headers.get('content-type').indexOf('javascript') === -1 - ) { - // No service worker found. Probably a different app. Reload the page. - navigator.serviceWorker.ready.then(registration => { - registration.unregister().then(() => { - window.location.reload(); - }); - }); - } else { - // Service worker found. Proceed as normal. - registerValidSW(swUrl); - } - }) - .catch(() => { - console.log( - 'No internet connection found. App is running in offline mode.' - ); + // Check if the service worker can be found. If it can't reload the page. + fetch(swUrl) + .then(response => { + // Ensure service worker exists, and that we really are getting a JS file. + if ( + response.status === 404 || + response.headers.get("content-type").indexOf("javascript") === -1 + ) { + // No service worker found. Probably a different app. Reload the page. + navigator.serviceWorker.ready.then(registration => { + registration.unregister().then(() => { + window.location.reload(); + }); }); + } else { + // Service worker found. Proceed as normal. + registerValidSW(swUrl); + } + }) + .catch(() => { + console.log( + "No internet connection found. App is running in offline mode." + ); + }); } export function unregister() { - if ('serviceWorker' in navigator) { - navigator.serviceWorker.ready.then(registration => { - registration.unregister(); - }); - } + if ("serviceWorker" in navigator) { + navigator.serviceWorker.ready.then(registration => { + registration.unregister(); + }); + } } diff --git a/src/routes/index.js b/src/routes/index.js index 96ac885c..f7523458 100644 --- a/src/routes/index.js +++ b/src/routes/index.js @@ -1,6 +1,6 @@ -import React from 'react'; -import {BrowserRouter, Redirect, Route, Switch} from "react-router-dom"; -import {userIsLoggedIn} from "../auth/index"; +import React from "react"; +import { BrowserRouter, Redirect, Route, Switch } from "react-router-dom"; +import { userIsLoggedIn } from "../auth/index"; import App from "../pages/App"; import Experiments from "../pages/Experiments"; import Home from "../pages/Home"; @@ -8,35 +8,57 @@ import NotFound from "../pages/NotFound"; import Profile from "../pages/Profile"; import Simulations from "../pages/Simulations"; -const ProtectedComponent = (component) => () => userIsLoggedIn() ? component : <Redirect to="/"/>; -const AppComponent = ({match}) => userIsLoggedIn() ? - <App simulationId={parseInt(match.params.simulationId, 10)}/> : - <Redirect to="/"/>; +const ProtectedComponent = component => () => + userIsLoggedIn() ? component : <Redirect to="/" />; +const AppComponent = ({ match }) => + userIsLoggedIn() ? ( + <App simulationId={parseInt(match.params.simulationId, 10)} /> + ) : ( + <Redirect to="/" /> + ); -const ExperimentsComponent = ({match}) => userIsLoggedIn() ? - <Experiments simulationId={parseInt(match.params.simulationId, 10)}/> : - <Redirect to="/"/>; +const ExperimentsComponent = ({ match }) => + userIsLoggedIn() ? ( + <Experiments simulationId={parseInt(match.params.simulationId, 10)} /> + ) : ( + <Redirect to="/" /> + ); -const SimulationComponent = ({match}) => userIsLoggedIn() ? +const SimulationComponent = ({ match }) => + userIsLoggedIn() ? ( <App - simulationId={parseInt(match.params.simulationId, 10)} - inSimulation={true} - experimentId={parseInt(match.params.experimentId, 10)} - /> : - <Redirect to="/"/>; + simulationId={parseInt(match.params.simulationId, 10)} + inSimulation={true} + experimentId={parseInt(match.params.experimentId, 10)} + /> + ) : ( + <Redirect to="/" /> + ); const Routes = () => ( - <BrowserRouter> - <Switch> - <Route exact path="/" component={Home}/> - <Route exact path="/simulations" render={ProtectedComponent(<Simulations/>)}/> - <Route exact path="/simulations/:simulationId" component={AppComponent}/> - <Route exact path="/simulations/:simulationId/experiments" component={ExperimentsComponent}/> - <Route exact path="/simulations/:simulationId/experiments/:experimentId" component={SimulationComponent}/> - <Route exact path="/profile" render={ProtectedComponent(<Profile/>)}/> - <Route path="/*" component={NotFound}/> - </Switch> - </BrowserRouter> + <BrowserRouter> + <Switch> + <Route exact path="/" component={Home} /> + <Route + exact + path="/simulations" + render={ProtectedComponent(<Simulations />)} + /> + <Route exact path="/simulations/:simulationId" component={AppComponent} /> + <Route + exact + path="/simulations/:simulationId/experiments" + component={ExperimentsComponent} + /> + <Route + exact + path="/simulations/:simulationId/experiments/:experimentId" + component={SimulationComponent} + /> + <Route exact path="/profile" render={ProtectedComponent(<Profile />)} /> + <Route path="/*" component={NotFound} /> + </Switch> + </BrowserRouter> ); export default Routes; diff --git a/src/sagas/experiments.js b/src/sagas/experiments.js index f21bb336..9b8c1a8f 100644 --- a/src/sagas/experiments.js +++ b/src/sagas/experiments.js @@ -1,144 +1,184 @@ -import {delay} from "redux-saga"; -import {call, put, select} from "redux-saga/effects"; -import {addPropToStoreObject, addToStore} from "../actions/objects"; -import {setLastSimulatedTick} from "../actions/simulation/tick"; -import {addBatchToStates} from "../actions/states"; +import { delay } from "redux-saga"; +import { call, put, select } from "redux-saga/effects"; +import { addPropToStoreObject, addToStore } from "../actions/objects"; +import { setLastSimulatedTick } from "../actions/simulation/tick"; +import { addBatchToStates } from "../actions/states"; import { - deleteExperiment, - getAllMachineStates, - getAllRackStates, - getAllRoomStates, - getAllTaskStates, - getExperiment, - getLastSimulatedTick + deleteExperiment, + getAllMachineStates, + getAllRackStates, + getAllRoomStates, + getAllTaskStates, + getExperiment, + getLastSimulatedTick } from "../api/routes/experiments"; -import {getTasksOfJob} from "../api/routes/jobs"; -import {addExperiment, getExperimentsOfSimulation, getSimulation} from "../api/routes/simulations"; -import {getJobsOfTrace} from "../api/routes/traces"; -import {fetchAndStoreAllSchedulers, fetchAndStoreAllTraces, fetchAndStorePathsOfSimulation} from "./objects"; -import {fetchAllDatacentersOfExperiment} from "./topology"; +import { getTasksOfJob } from "../api/routes/jobs"; +import { + addExperiment, + getExperimentsOfSimulation, + getSimulation +} from "../api/routes/simulations"; +import { getJobsOfTrace } from "../api/routes/traces"; +import { + fetchAndStoreAllSchedulers, + fetchAndStoreAllTraces, + fetchAndStorePathsOfSimulation +} from "./objects"; +import { fetchAllDatacentersOfExperiment } from "./topology"; export function* onOpenExperimentSucceeded(action) { - try { - const simulation = yield call(getSimulation, action.simulationId); - yield put(addToStore("simulation", simulation)); + try { + const simulation = yield call(getSimulation, action.simulationId); + yield put(addToStore("simulation", simulation)); - const experiment = yield call(getExperiment, action.experimentId); - yield put(addToStore("experiment", experiment)); + const experiment = yield call(getExperiment, action.experimentId); + yield put(addToStore("experiment", experiment)); - yield fetchExperimentSpecifications(); - yield fetchWorkloadOfTrace(experiment.traceId); + yield fetchExperimentSpecifications(); + yield fetchWorkloadOfTrace(experiment.traceId); - yield fetchAllDatacentersOfExperiment(experiment); - yield startStateFetchLoop(action.experimentId); - } catch (error) { - console.error(error); - } + yield fetchAllDatacentersOfExperiment(experiment); + yield startStateFetchLoop(action.experimentId); + } catch (error) { + console.error(error); + } } function* startStateFetchLoop(experimentId) { - try { - while ((yield select(state => state.currentExperimentId)) !== -1) { - const lastSimulatedTick = (yield call(getLastSimulatedTick, experimentId)).lastSimulatedTick; - if (lastSimulatedTick !== (yield select(state => state.lastSimulatedTick))) { - yield put(setLastSimulatedTick(lastSimulatedTick)); - - const taskStates = yield call(getAllTaskStates, experimentId); - const machineStates = yield call(getAllMachineStates, experimentId); - const rackStates = yield call(getAllRackStates, experimentId); - const roomStates = yield call(getAllRoomStates, experimentId); - - yield put(addBatchToStates("task", taskStates)); - yield put(addBatchToStates("machine", machineStates)); - yield put(addBatchToStates("rack", rackStates)); - yield put(addBatchToStates("room", roomStates)); - - yield delay(5000); - } else { - yield delay(10000); - } - } - } catch (error) { - console.error(error); + try { + while ((yield select(state => state.currentExperimentId)) !== -1) { + const lastSimulatedTick = (yield call(getLastSimulatedTick, experimentId)) + .lastSimulatedTick; + if ( + lastSimulatedTick !== (yield select(state => state.lastSimulatedTick)) + ) { + yield put(setLastSimulatedTick(lastSimulatedTick)); + + const taskStates = yield call(getAllTaskStates, experimentId); + const machineStates = yield call(getAllMachineStates, experimentId); + const rackStates = yield call(getAllRackStates, experimentId); + const roomStates = yield call(getAllRoomStates, experimentId); + + yield put(addBatchToStates("task", taskStates)); + yield put(addBatchToStates("machine", machineStates)); + yield put(addBatchToStates("rack", rackStates)); + yield put(addBatchToStates("room", roomStates)); + + yield delay(5000); + } else { + yield delay(10000); + } } + } catch (error) { + console.error(error); + } } export function* onFetchExperimentsOfSimulation() { - try { - const currentSimulationId = yield select(state => state.currentSimulationId); - - yield fetchExperimentSpecifications(); - const experiments = yield call(getExperimentsOfSimulation, currentSimulationId); - for (let i in experiments) { - yield put(addToStore("experiment", experiments[i])); - } - yield put(addPropToStoreObject("simulation", currentSimulationId, - {experimentIds: experiments.map(experiment => experiment.id)})); - } catch (error) { - console.error(error); + try { + const currentSimulationId = yield select( + state => state.currentSimulationId + ); + + yield fetchExperimentSpecifications(); + const experiments = yield call( + getExperimentsOfSimulation, + currentSimulationId + ); + for (let i in experiments) { + yield put(addToStore("experiment", experiments[i])); } + yield put( + addPropToStoreObject("simulation", currentSimulationId, { + experimentIds: experiments.map(experiment => experiment.id) + }) + ); + } catch (error) { + console.error(error); + } } function* fetchExperimentSpecifications() { - try { - const currentSimulationId = yield select(state => state.currentSimulationId); - yield fetchAndStorePathsOfSimulation(currentSimulationId); - yield fetchAndStoreAllTraces(); - yield fetchAndStoreAllSchedulers(); - } catch (error) { - console.error(error); - } + try { + const currentSimulationId = yield select( + state => state.currentSimulationId + ); + yield fetchAndStorePathsOfSimulation(currentSimulationId); + yield fetchAndStoreAllTraces(); + yield fetchAndStoreAllSchedulers(); + } catch (error) { + console.error(error); + } } function* fetchWorkloadOfTrace(traceId) { - try { - const jobs = yield call(getJobsOfTrace, traceId); - for (let i in jobs) { - const job = jobs[i]; - const tasks = yield call(getTasksOfJob, job.id); - job.taskIds = tasks.map(task => task.id); - for (let j in tasks) { - yield put(addToStore("task", tasks[j])); - } - yield put(addToStore("job", job)); - } - yield put(addPropToStoreObject("trace", traceId, {jobIds: jobs.map(job => job.id)})) - } catch (error) { - console.error(error); + try { + const jobs = yield call(getJobsOfTrace, traceId); + for (let i in jobs) { + const job = jobs[i]; + const tasks = yield call(getTasksOfJob, job.id); + job.taskIds = tasks.map(task => task.id); + for (let j in tasks) { + yield put(addToStore("task", tasks[j])); + } + yield put(addToStore("job", job)); } + yield put( + addPropToStoreObject("trace", traceId, { + jobIds: jobs.map(job => job.id) + }) + ); + } catch (error) { + console.error(error); + } } export function* onAddExperiment(action) { - try { - const currentSimulationId = yield select(state => state.currentSimulationId); - - const experiment = yield call(addExperiment, - currentSimulationId, - Object.assign({}, action.experiment, { - id: -1, - simulationId: currentSimulationId - }) - ); - yield put(addToStore("experiment", experiment)); - - const experimentIds = yield select(state => state.objects.simulation[currentSimulationId].experimentIds); - yield put(addPropToStoreObject("simulation", currentSimulationId, - {experimentIds: experimentIds.concat([experiment.id])})); - } catch (error) { - console.error(error); - } + try { + const currentSimulationId = yield select( + state => state.currentSimulationId + ); + + const experiment = yield call( + addExperiment, + currentSimulationId, + Object.assign({}, action.experiment, { + id: -1, + simulationId: currentSimulationId + }) + ); + yield put(addToStore("experiment", experiment)); + + const experimentIds = yield select( + state => state.objects.simulation[currentSimulationId].experimentIds + ); + yield put( + addPropToStoreObject("simulation", currentSimulationId, { + experimentIds: experimentIds.concat([experiment.id]) + }) + ); + } catch (error) { + console.error(error); + } } export function* onDeleteExperiment(action) { - try { - yield call(deleteExperiment, action.id); - - const currentSimulationId = yield select(state => state.currentSimulationId); - const experimentIds = yield select(state => state.objects.simulation[currentSimulationId].experimentIds); - - yield put(addPropToStoreObject("simulation", currentSimulationId, - {experimentIds: experimentIds.filter(id => id !== action.id)})); - } catch (error) { - console.error(error); - } + try { + yield call(deleteExperiment, action.id); + + const currentSimulationId = yield select( + state => state.currentSimulationId + ); + const experimentIds = yield select( + state => state.objects.simulation[currentSimulationId].experimentIds + ); + + yield put( + addPropToStoreObject("simulation", currentSimulationId, { + experimentIds: experimentIds.filter(id => id !== action.id) + }) + ); + } catch (error) { + console.error(error); + } } diff --git a/src/sagas/index.js b/src/sagas/index.js index b10d6a1c..56c8f09b 100644 --- a/src/sagas/index.js +++ b/src/sagas/index.js @@ -1,74 +1,106 @@ -import {takeEvery} from "redux-saga/effects"; -import {LOG_IN} from "../actions/auth"; +import { takeEvery } from "redux-saga/effects"; +import { LOG_IN } from "../actions/auth"; import { - ADD_EXPERIMENT, - DELETE_EXPERIMENT, - FETCH_EXPERIMENTS_OF_SIMULATION, - OPEN_EXPERIMENT_SUCCEEDED + ADD_EXPERIMENT, + DELETE_EXPERIMENT, + FETCH_EXPERIMENTS_OF_SIMULATION, + OPEN_EXPERIMENT_SUCCEEDED } from "../actions/experiments"; -import {ADD_SIMULATION, DELETE_SIMULATION, OPEN_SIMULATION_SUCCEEDED} from "../actions/simulations"; import { - ADD_TILE, - CANCEL_NEW_ROOM_CONSTRUCTION, - DELETE_TILE, - START_NEW_ROOM_CONSTRUCTION + ADD_SIMULATION, + DELETE_SIMULATION, + OPEN_SIMULATION_SUCCEEDED +} from "../actions/simulations"; +import { + ADD_TILE, + CANCEL_NEW_ROOM_CONSTRUCTION, + DELETE_TILE, + START_NEW_ROOM_CONSTRUCTION } from "../actions/topology/building"; -import {ADD_UNIT, DELETE_MACHINE, DELETE_UNIT} from "../actions/topology/machine"; -import {ADD_MACHINE, DELETE_RACK, EDIT_RACK_NAME} from "../actions/topology/rack"; -import {ADD_RACK_TO_TILE, DELETE_ROOM, EDIT_ROOM_NAME} from "../actions/topology/room"; -import {DELETE_CURRENT_USER, FETCH_AUTHORIZATIONS_OF_CURRENT_USER} from "../actions/users"; import { - onAddExperiment, - onDeleteExperiment, - onFetchExperimentsOfSimulation, - onOpenExperimentSucceeded + ADD_UNIT, + DELETE_MACHINE, + DELETE_UNIT +} from "../actions/topology/machine"; +import { + ADD_MACHINE, + DELETE_RACK, + EDIT_RACK_NAME +} from "../actions/topology/rack"; +import { + ADD_RACK_TO_TILE, + DELETE_ROOM, + EDIT_ROOM_NAME +} from "../actions/topology/room"; +import { + DELETE_CURRENT_USER, + FETCH_AUTHORIZATIONS_OF_CURRENT_USER +} from "../actions/users"; +import { + onAddExperiment, + onDeleteExperiment, + onFetchExperimentsOfSimulation, + onOpenExperimentSucceeded } from "./experiments"; -import {onDeleteCurrentUser} from "./profile"; -import {onOpenSimulationSucceeded, onSimulationAdd, onSimulationDelete} from "./simulations"; +import { onDeleteCurrentUser } from "./profile"; +import { + onOpenSimulationSucceeded, + onSimulationAdd, + onSimulationDelete +} from "./simulations"; import { - onAddMachine, - onAddRackToTile, - onAddTile, - onAddUnit, - onCancelNewRoomConstruction, - onDeleteMachine, - onDeleteRack, - onDeleteRoom, - onDeleteTile, - onDeleteUnit, - onEditRackName, - onEditRoomName, - onStartNewRoomConstruction + onAddMachine, + onAddRackToTile, + onAddTile, + onAddUnit, + onCancelNewRoomConstruction, + onDeleteMachine, + onDeleteRack, + onDeleteRoom, + onDeleteTile, + onDeleteUnit, + onEditRackName, + onEditRoomName, + onStartNewRoomConstruction } from "./topology"; -import {onFetchAuthorizationsOfCurrentUser, onFetchLoggedInUser} from "./users"; +import { + onFetchAuthorizationsOfCurrentUser, + onFetchLoggedInUser +} from "./users"; export default function* rootSaga() { - yield takeEvery(LOG_IN, onFetchLoggedInUser); + yield takeEvery(LOG_IN, onFetchLoggedInUser); - yield takeEvery(FETCH_AUTHORIZATIONS_OF_CURRENT_USER, onFetchAuthorizationsOfCurrentUser); - yield takeEvery(ADD_SIMULATION, onSimulationAdd); - yield takeEvery(DELETE_SIMULATION, onSimulationDelete); + yield takeEvery( + FETCH_AUTHORIZATIONS_OF_CURRENT_USER, + onFetchAuthorizationsOfCurrentUser + ); + yield takeEvery(ADD_SIMULATION, onSimulationAdd); + yield takeEvery(DELETE_SIMULATION, onSimulationDelete); - yield takeEvery(DELETE_CURRENT_USER, onDeleteCurrentUser); + yield takeEvery(DELETE_CURRENT_USER, onDeleteCurrentUser); - yield takeEvery(OPEN_SIMULATION_SUCCEEDED, onOpenSimulationSucceeded); - yield takeEvery(OPEN_EXPERIMENT_SUCCEEDED, onOpenExperimentSucceeded); + yield takeEvery(OPEN_SIMULATION_SUCCEEDED, onOpenSimulationSucceeded); + yield takeEvery(OPEN_EXPERIMENT_SUCCEEDED, onOpenExperimentSucceeded); - yield takeEvery(START_NEW_ROOM_CONSTRUCTION, onStartNewRoomConstruction); - yield takeEvery(CANCEL_NEW_ROOM_CONSTRUCTION, onCancelNewRoomConstruction); - yield takeEvery(ADD_TILE, onAddTile); - yield takeEvery(DELETE_TILE, onDeleteTile); - yield takeEvery(EDIT_ROOM_NAME, onEditRoomName); - yield takeEvery(DELETE_ROOM, onDeleteRoom); - yield takeEvery(EDIT_RACK_NAME, onEditRackName); - yield takeEvery(DELETE_RACK, onDeleteRack); - yield takeEvery(ADD_RACK_TO_TILE, onAddRackToTile); - yield takeEvery(ADD_MACHINE, onAddMachine); - yield takeEvery(DELETE_MACHINE, onDeleteMachine); - yield takeEvery(ADD_UNIT, onAddUnit); - yield takeEvery(DELETE_UNIT, onDeleteUnit); + yield takeEvery(START_NEW_ROOM_CONSTRUCTION, onStartNewRoomConstruction); + yield takeEvery(CANCEL_NEW_ROOM_CONSTRUCTION, onCancelNewRoomConstruction); + yield takeEvery(ADD_TILE, onAddTile); + yield takeEvery(DELETE_TILE, onDeleteTile); + yield takeEvery(EDIT_ROOM_NAME, onEditRoomName); + yield takeEvery(DELETE_ROOM, onDeleteRoom); + yield takeEvery(EDIT_RACK_NAME, onEditRackName); + yield takeEvery(DELETE_RACK, onDeleteRack); + yield takeEvery(ADD_RACK_TO_TILE, onAddRackToTile); + yield takeEvery(ADD_MACHINE, onAddMachine); + yield takeEvery(DELETE_MACHINE, onDeleteMachine); + yield takeEvery(ADD_UNIT, onAddUnit); + yield takeEvery(DELETE_UNIT, onDeleteUnit); - yield takeEvery(FETCH_EXPERIMENTS_OF_SIMULATION, onFetchExperimentsOfSimulation); - yield takeEvery(ADD_EXPERIMENT, onAddExperiment); - yield takeEvery(DELETE_EXPERIMENT, onDeleteExperiment); + yield takeEvery( + FETCH_EXPERIMENTS_OF_SIMULATION, + onFetchExperimentsOfSimulation + ); + yield takeEvery(ADD_EXPERIMENT, onAddExperiment); + yield takeEvery(DELETE_EXPERIMENT, onDeleteExperiment); } diff --git a/src/sagas/objects.js b/src/sagas/objects.js index 0a0154cc..3cfd43a6 100644 --- a/src/sagas/objects.js +++ b/src/sagas/objects.js @@ -1,140 +1,140 @@ -import {call, put, select} from "redux-saga/effects"; -import {addToStore} from "../actions/objects"; -import {getDatacenter, getRoomsOfDatacenter} from "../api/routes/datacenters"; -import {getPath, getSectionsOfPath} from "../api/routes/paths"; -import {getTilesOfRoom} from "../api/routes/rooms"; -import {getAllSchedulers} from "../api/routes/schedulers"; -import {getSection} from "../api/routes/sections"; -import {getPathsOfSimulation, getSimulation} from "../api/routes/simulations"; +import { call, put, select } from "redux-saga/effects"; +import { addToStore } from "../actions/objects"; +import { getDatacenter, getRoomsOfDatacenter } from "../api/routes/datacenters"; +import { getPath, getSectionsOfPath } from "../api/routes/paths"; +import { getTilesOfRoom } from "../api/routes/rooms"; +import { getAllSchedulers } from "../api/routes/schedulers"; +import { getSection } from "../api/routes/sections"; +import { getPathsOfSimulation, getSimulation } from "../api/routes/simulations"; import { - getAllCPUs, - getAllGPUs, - getAllMemories, - getAllStorages, - getCoolingItem, - getCPU, - getFailureModel, - getGPU, - getMemory, - getPSU, - getStorage + getAllCPUs, + getAllGPUs, + getAllMemories, + getAllStorages, + getCoolingItem, + getCPU, + getFailureModel, + getGPU, + getMemory, + getPSU, + getStorage } from "../api/routes/specifications"; -import {getMachinesOfRackByTile, getRackByTile} from "../api/routes/tiles"; -import {getAllTraces} from "../api/routes/traces"; -import {getUser} from "../api/routes/users"; +import { getMachinesOfRackByTile, getRackByTile } from "../api/routes/tiles"; +import { getAllTraces } from "../api/routes/traces"; +import { getUser } from "../api/routes/users"; export const OBJECT_SELECTORS = { - simulation: state => state.objects.simulation, - user: state => state.objects.user, - authorization: state => state.objects.authorization, - failureModel: state => state.objects.failureModel, - cpu: state => state.objects.cpu, - gpu: state => state.objects.gpu, - memory: state => state.objects.memory, - storage: state => state.objects.storage, - machine: state => state.objects.machine, - rack: state => state.objects.rack, - coolingItem: state => state.objects.coolingItem, - psu: state => state.objects.psu, - tile: state => state.objects.tile, - room: state => state.objects.room, - datacenter: state => state.objects.datacenter, - section: state => state.objects.section, - path: state => state.objects.path, + simulation: state => state.objects.simulation, + user: state => state.objects.user, + authorization: state => state.objects.authorization, + failureModel: state => state.objects.failureModel, + cpu: state => state.objects.cpu, + gpu: state => state.objects.gpu, + memory: state => state.objects.memory, + storage: state => state.objects.storage, + machine: state => state.objects.machine, + rack: state => state.objects.rack, + coolingItem: state => state.objects.coolingItem, + psu: state => state.objects.psu, + tile: state => state.objects.tile, + room: state => state.objects.room, + datacenter: state => state.objects.datacenter, + section: state => state.objects.section, + path: state => state.objects.path }; function* fetchAndStoreObject(objectType, id, apiCall) { - const objectStore = yield select(OBJECT_SELECTORS[objectType]); - let object = objectStore[id]; - if (!object) { - object = yield apiCall; - yield put(addToStore(objectType, object)); - } - return object; + const objectStore = yield select(OBJECT_SELECTORS[objectType]); + let object = objectStore[id]; + if (!object) { + object = yield apiCall; + yield put(addToStore(objectType, object)); + } + return object; } function* fetchAndStoreObjects(objectType, apiCall) { - const objects = yield apiCall; - for (let index in objects) { - yield put(addToStore(objectType, objects[index])); - } - return objects; + const objects = yield apiCall; + for (let index in objects) { + yield put(addToStore(objectType, objects[index])); + } + return objects; } -export const fetchAndStoreSimulation = (id) => - fetchAndStoreObject("simulation", id, call(getSimulation, id)); +export const fetchAndStoreSimulation = id => + fetchAndStoreObject("simulation", id, call(getSimulation, id)); -export const fetchAndStoreUser = (id) => - fetchAndStoreObject("user", id, call(getUser, id)); +export const fetchAndStoreUser = id => + fetchAndStoreObject("user", id, call(getUser, id)); -export const fetchAndStoreFailureModel = (id) => - fetchAndStoreObject("failureModel", id, call(getFailureModel, id)); +export const fetchAndStoreFailureModel = id => + fetchAndStoreObject("failureModel", id, call(getFailureModel, id)); export const fetchAndStoreAllCPUs = () => - fetchAndStoreObjects("cpu", call(getAllCPUs)); + fetchAndStoreObjects("cpu", call(getAllCPUs)); -export const fetchAndStoreCPU = (id) => - fetchAndStoreObject("cpu", id, call(getCPU, id)); +export const fetchAndStoreCPU = id => + fetchAndStoreObject("cpu", id, call(getCPU, id)); export const fetchAndStoreAllGPUs = () => - fetchAndStoreObjects("gpu", call(getAllGPUs)); + fetchAndStoreObjects("gpu", call(getAllGPUs)); -export const fetchAndStoreGPU = (id) => - fetchAndStoreObject("gpu", id, call(getGPU, id)); +export const fetchAndStoreGPU = id => + fetchAndStoreObject("gpu", id, call(getGPU, id)); export const fetchAndStoreAllMemories = () => - fetchAndStoreObjects("memory", call(getAllMemories)); + fetchAndStoreObjects("memory", call(getAllMemories)); -export const fetchAndStoreMemory = (id) => - fetchAndStoreObject("memory", id, call(getMemory, id)); +export const fetchAndStoreMemory = id => + fetchAndStoreObject("memory", id, call(getMemory, id)); export const fetchAndStoreAllStorages = () => - fetchAndStoreObjects("storage", call(getAllStorages)); + fetchAndStoreObjects("storage", call(getAllStorages)); -export const fetchAndStoreStorage = (id) => - fetchAndStoreObject("storage", id, call(getStorage, id)); +export const fetchAndStoreStorage = id => + fetchAndStoreObject("storage", id, call(getStorage, id)); -export const fetchAndStoreMachinesOfTile = (tileId) => - fetchAndStoreObjects("machine", call(getMachinesOfRackByTile, tileId)); +export const fetchAndStoreMachinesOfTile = tileId => + fetchAndStoreObjects("machine", call(getMachinesOfRackByTile, tileId)); export const fetchAndStoreRackOnTile = (id, tileId) => - fetchAndStoreObject("rack", id, call(getRackByTile, tileId)); + fetchAndStoreObject("rack", id, call(getRackByTile, tileId)); -export const fetchAndStoreCoolingItem = (id) => - fetchAndStoreObject("coolingItem", id, call(getCoolingItem, id)); +export const fetchAndStoreCoolingItem = id => + fetchAndStoreObject("coolingItem", id, call(getCoolingItem, id)); -export const fetchAndStorePSU = (id) => - fetchAndStoreObject("psu", id, call(getPSU, id)); +export const fetchAndStorePSU = id => + fetchAndStoreObject("psu", id, call(getPSU, id)); -export const fetchAndStoreTilesOfRoom = (roomId) => - fetchAndStoreObjects("tile", call(getTilesOfRoom, roomId)); +export const fetchAndStoreTilesOfRoom = roomId => + fetchAndStoreObjects("tile", call(getTilesOfRoom, roomId)); -export const fetchAndStoreRoomsOfDatacenter = (datacenterId) => - fetchAndStoreObjects("room", call(getRoomsOfDatacenter, datacenterId)); +export const fetchAndStoreRoomsOfDatacenter = datacenterId => + fetchAndStoreObjects("room", call(getRoomsOfDatacenter, datacenterId)); -export const fetchAndStoreDatacenter = (id) => - fetchAndStoreObject("datacenter", id, call(getDatacenter, id)); +export const fetchAndStoreDatacenter = id => + fetchAndStoreObject("datacenter", id, call(getDatacenter, id)); -export const fetchAndStoreSection = (id) => - fetchAndStoreObject("section", id, call(getSection, id)); +export const fetchAndStoreSection = id => + fetchAndStoreObject("section", id, call(getSection, id)); -export const fetchAndStoreSectionsOfPath = (pathId) => - fetchAndStoreObjects("section", call(getSectionsOfPath, pathId)); +export const fetchAndStoreSectionsOfPath = pathId => + fetchAndStoreObjects("section", call(getSectionsOfPath, pathId)); -export const fetchAndStorePath = (id) => - fetchAndStoreObject("path", id, call(getPath, id)); +export const fetchAndStorePath = id => + fetchAndStoreObject("path", id, call(getPath, id)); -export const fetchAndStorePathsOfSimulation = (simulationId) => - fetchAndStoreObjects("path", call(getPathsOfSimulation, simulationId)); +export const fetchAndStorePathsOfSimulation = simulationId => + fetchAndStoreObjects("path", call(getPathsOfSimulation, simulationId)); export const fetchAndStoreAllTraces = () => - fetchAndStoreObjects("trace", call(getAllTraces)); - -export const fetchAndStoreAllSchedulers = function* () { - const objects = yield call(getAllSchedulers); - for (let index in objects) { - objects[index].id = objects[index].name; - yield put(addToStore("scheduler", objects[index])); - } - return objects; + fetchAndStoreObjects("trace", call(getAllTraces)); + +export const fetchAndStoreAllSchedulers = function*() { + const objects = yield call(getAllSchedulers); + for (let index in objects) { + objects[index].id = objects[index].name; + yield put(addToStore("scheduler", objects[index])); + } + return objects; }; diff --git a/src/sagas/profile.js b/src/sagas/profile.js index 5eacbc73..31d4dd4f 100644 --- a/src/sagas/profile.js +++ b/src/sagas/profile.js @@ -1,12 +1,12 @@ -import {call, put} from "redux-saga/effects"; -import {deleteCurrentUserSucceeded} from "../actions/users"; -import {deleteUser} from "../api/routes/users"; +import { call, put } from "redux-saga/effects"; +import { deleteCurrentUserSucceeded } from "../actions/users"; +import { deleteUser } from "../api/routes/users"; export function* onDeleteCurrentUser(action) { - try { - yield call(deleteUser, action.userId); - yield put(deleteCurrentUserSucceeded()); - } catch (error) { - console.error(error); - } + try { + yield call(deleteUser, action.userId); + yield put(deleteCurrentUserSucceeded()); + } catch (error) { + console.error(error); + } } diff --git a/src/sagas/simulations.js b/src/sagas/simulations.js index cf0358f9..9df4e4b5 100644 --- a/src/sagas/simulations.js +++ b/src/sagas/simulations.js @@ -1,42 +1,51 @@ -import {call, put} from "redux-saga/effects"; -import {addToStore} from "../actions/objects"; -import {addSimulationSucceeded, deleteSimulationSucceeded} from "../actions/simulations"; -import {addSimulation, deleteSimulation, getSimulation} from "../api/routes/simulations"; -import {fetchLatestDatacenter} from "./topology"; +import { call, put } from "redux-saga/effects"; +import { addToStore } from "../actions/objects"; +import { + addSimulationSucceeded, + deleteSimulationSucceeded +} from "../actions/simulations"; +import { + addSimulation, + deleteSimulation, + getSimulation +} from "../api/routes/simulations"; +import { fetchLatestDatacenter } from "./topology"; export function* onOpenSimulationSucceeded(action) { - try { - const simulation = yield call(getSimulation, action.id); - yield put(addToStore("simulation", simulation)); + try { + const simulation = yield call(getSimulation, action.id); + yield put(addToStore("simulation", simulation)); - yield fetchLatestDatacenter(action.id); - } catch (error) { - console.error(error); - } + yield fetchLatestDatacenter(action.id); + } catch (error) { + console.error(error); + } } export function* onSimulationAdd(action) { - try { - const simulation = yield call(addSimulation, {name: action.name}); - yield put(addToStore("simulation", simulation)); + try { + const simulation = yield call(addSimulation, { name: action.name }); + yield put(addToStore("simulation", simulation)); - const authorization = { - simulationId: simulation.id, - userId: action.userId, - authorizationLevel: "OWN" - }; - yield put(addToStore("authorization", authorization)); - yield put(addSimulationSucceeded([authorization.userId, authorization.simulationId])); - } catch (error) { - console.error(error); - } + const authorization = { + simulationId: simulation.id, + userId: action.userId, + authorizationLevel: "OWN" + }; + yield put(addToStore("authorization", authorization)); + yield put( + addSimulationSucceeded([authorization.userId, authorization.simulationId]) + ); + } catch (error) { + console.error(error); + } } export function* onSimulationDelete(action) { - try { - yield call(deleteSimulation, action.id); - yield put(deleteSimulationSucceeded(action.id)); - } catch (error) { - console.error(error); - } + try { + yield call(deleteSimulation, action.id); + yield put(deleteSimulationSucceeded(action.id)); + } catch (error) { + console.error(error); + } } diff --git a/src/sagas/topology.js b/src/sagas/topology.js index 12f02e4b..13b4ed17 100644 --- a/src/sagas/topology.js +++ b/src/sagas/topology.js @@ -1,361 +1,434 @@ -import {call, put, select} from "redux-saga/effects"; -import {goDownOneInteractionLevel} from "../actions/interaction-level"; +import { call, put, select } from "redux-saga/effects"; +import { goDownOneInteractionLevel } from "../actions/interaction-level"; import { - addIdToStoreObjectListProp, - addPropToStoreObject, - addToStore, - removeIdFromStoreObjectListProp + addIdToStoreObjectListProp, + addPropToStoreObject, + addToStore, + removeIdFromStoreObjectListProp } from "../actions/objects"; import { - cancelNewRoomConstructionSucceeded, - setCurrentDatacenter, - startNewRoomConstructionSucceeded + cancelNewRoomConstructionSucceeded, + setCurrentDatacenter, + startNewRoomConstructionSucceeded } from "../actions/topology/building"; -import {addRoomToDatacenter} from "../api/routes/datacenters"; -import {addTileToRoom, deleteRoom, updateRoom} from "../api/routes/rooms"; +import { addRoomToDatacenter } from "../api/routes/datacenters"; +import { addTileToRoom, deleteRoom, updateRoom } from "../api/routes/rooms"; import { - addMachineToRackOnTile, - addRackToTile, - deleteMachineInRackOnTile, - deleteRackFromTile, - deleteTile, - updateMachineInRackOnTile, - updateRackOnTile + addMachineToRackOnTile, + addRackToTile, + deleteMachineInRackOnTile, + deleteRackFromTile, + deleteTile, + updateMachineInRackOnTile, + updateRackOnTile } from "../api/routes/tiles"; import { - DEFAULT_RACK_POWER_CAPACITY, - DEFAULT_RACK_SLOT_CAPACITY, - MAX_NUM_UNITS_PER_MACHINE + DEFAULT_RACK_POWER_CAPACITY, + DEFAULT_RACK_SLOT_CAPACITY, + MAX_NUM_UNITS_PER_MACHINE } from "../components/app/map/MapConstants"; import { - fetchAndStoreAllCPUs, - fetchAndStoreAllGPUs, - fetchAndStoreAllMemories, - fetchAndStoreAllStorages, - fetchAndStoreCoolingItem, - fetchAndStoreCPU, - fetchAndStoreDatacenter, - fetchAndStoreGPU, - fetchAndStoreMachinesOfTile, - fetchAndStoreMemory, - fetchAndStorePath, - fetchAndStorePathsOfSimulation, - fetchAndStorePSU, - fetchAndStoreRackOnTile, - fetchAndStoreRoomsOfDatacenter, - fetchAndStoreSectionsOfPath, - fetchAndStoreStorage, - fetchAndStoreTilesOfRoom + fetchAndStoreAllCPUs, + fetchAndStoreAllGPUs, + fetchAndStoreAllMemories, + fetchAndStoreAllStorages, + fetchAndStoreCoolingItem, + fetchAndStoreCPU, + fetchAndStoreDatacenter, + fetchAndStoreGPU, + fetchAndStoreMachinesOfTile, + fetchAndStoreMemory, + fetchAndStorePath, + fetchAndStorePathsOfSimulation, + fetchAndStorePSU, + fetchAndStoreRackOnTile, + fetchAndStoreRoomsOfDatacenter, + fetchAndStoreSectionsOfPath, + fetchAndStoreStorage, + fetchAndStoreTilesOfRoom } from "./objects"; export function* fetchLatestDatacenter(simulationId) { - try { - const paths = yield fetchAndStorePathsOfSimulation(simulationId); - const latestPath = paths[paths.length - 1]; - const sections = yield fetchAndStoreSectionsOfPath(latestPath.id); - const latestSection = sections[sections.length - 1]; - yield fetchAllUnitSpecifications(); - yield fetchDatacenter(latestSection.datacenterId); - yield put(setCurrentDatacenter(latestSection.datacenterId)); - } catch (error) { - console.error(error); - } + try { + const paths = yield fetchAndStorePathsOfSimulation(simulationId); + const latestPath = paths[paths.length - 1]; + const sections = yield fetchAndStoreSectionsOfPath(latestPath.id); + const latestSection = sections[sections.length - 1]; + yield fetchAllUnitSpecifications(); + yield fetchDatacenter(latestSection.datacenterId); + yield put(setCurrentDatacenter(latestSection.datacenterId)); + } catch (error) { + console.error(error); + } } export function* fetchAllDatacentersOfExperiment(experiment) { - try { - const path = yield fetchAndStorePath(experiment.pathId); - const sections = yield fetchAndStoreSectionsOfPath(path.id); - path.sectionIds = sections.map(section => section.id); - yield fetchAllUnitSpecifications(); - - for (let i in sections) { - yield fetchDatacenter(sections[i].datacenterId); - } - yield put(setCurrentDatacenter(sections[0].datacenterId)); - } catch (error) { - console.error(error); + try { + const path = yield fetchAndStorePath(experiment.pathId); + const sections = yield fetchAndStoreSectionsOfPath(path.id); + path.sectionIds = sections.map(section => section.id); + yield fetchAllUnitSpecifications(); + + for (let i in sections) { + yield fetchDatacenter(sections[i].datacenterId); } + yield put(setCurrentDatacenter(sections[0].datacenterId)); + } catch (error) { + console.error(error); + } } function* fetchDatacenter(datacenterId) { - try { - yield fetchAndStoreDatacenter(datacenterId); - const rooms = yield fetchAndStoreRoomsOfDatacenter(datacenterId); - yield put(addPropToStoreObject("datacenter", datacenterId, {roomIds: rooms.map(room => room.id)})); - - for (let index in rooms) { - yield fetchRoom(rooms[index].id); - } - } catch (error) { - console.error(error); + try { + yield fetchAndStoreDatacenter(datacenterId); + const rooms = yield fetchAndStoreRoomsOfDatacenter(datacenterId); + yield put( + addPropToStoreObject("datacenter", datacenterId, { + roomIds: rooms.map(room => room.id) + }) + ); + + for (let index in rooms) { + yield fetchRoom(rooms[index].id); } + } catch (error) { + console.error(error); + } } function* fetchAllUnitSpecifications() { - try { - yield fetchAndStoreAllCPUs(); - yield fetchAndStoreAllGPUs(); - yield fetchAndStoreAllMemories(); - yield fetchAndStoreAllStorages(); - } catch (error) { - console.error(error); - } + try { + yield fetchAndStoreAllCPUs(); + yield fetchAndStoreAllGPUs(); + yield fetchAndStoreAllMemories(); + yield fetchAndStoreAllStorages(); + } catch (error) { + console.error(error); + } } function* fetchRoom(roomId) { - const tiles = yield fetchAndStoreTilesOfRoom(roomId); - yield put(addPropToStoreObject("room", roomId, {tileIds: tiles.map(tile => tile.id)})); - - for (let index in tiles) { - yield fetchTile(tiles[index]); - } + const tiles = yield fetchAndStoreTilesOfRoom(roomId); + yield put( + addPropToStoreObject("room", roomId, { + tileIds: tiles.map(tile => tile.id) + }) + ); + + for (let index in tiles) { + yield fetchTile(tiles[index]); + } } function* fetchTile(tile) { - if (!tile.objectType) { - return; - } - - switch (tile.objectType) { - case "RACK": - const rack = yield fetchAndStoreRackOnTile(tile.objectId, tile.id); - yield put(addPropToStoreObject("tile", tile.id, {rackId: rack.id})); - yield fetchMachinesOfRack(tile.id, rack); - break; - case "COOLING_ITEM": - const coolingItem = yield fetchAndStoreCoolingItem(tile.objectId); - yield put(addPropToStoreObject("tile", tile.id, {coolingItemId: coolingItem.id})); - break; - case "PSU": - const psu = yield fetchAndStorePSU(tile.objectId); - yield put(addPropToStoreObject("tile", tile.id, {psuId: psu.id})); - break; - default: - console.warn("Unknown rack type encountered while fetching tile objects"); - } + if (!tile.objectType) { + return; + } + + switch (tile.objectType) { + case "RACK": + const rack = yield fetchAndStoreRackOnTile(tile.objectId, tile.id); + yield put(addPropToStoreObject("tile", tile.id, { rackId: rack.id })); + yield fetchMachinesOfRack(tile.id, rack); + break; + case "COOLING_ITEM": + const coolingItem = yield fetchAndStoreCoolingItem(tile.objectId); + yield put( + addPropToStoreObject("tile", tile.id, { coolingItemId: coolingItem.id }) + ); + break; + case "PSU": + const psu = yield fetchAndStorePSU(tile.objectId); + yield put(addPropToStoreObject("tile", tile.id, { psuId: psu.id })); + break; + default: + console.warn("Unknown rack type encountered while fetching tile objects"); + } } function* fetchMachinesOfRack(tileId, rack) { - const machines = yield fetchAndStoreMachinesOfTile(tileId); - const machineIds = new Array(rack.capacity).fill(null); - machines.forEach(machine => machineIds[machine.position - 1] = machine.id); - - yield put(addPropToStoreObject("rack", rack.id, {machineIds})); - - for (let index in machines) { - for (let i in machines[index].cpuIds) { - yield fetchAndStoreCPU(machines[index].cpuIds[i]); - } - for (let i in machines[index].gpuIds) { - yield fetchAndStoreGPU(machines[index].gpuIds[i]); - } - for (let i in machines[index].memoryIds) { - yield fetchAndStoreMemory(machines[index].memoryIds[i]); - } - for (let i in machines[index].storageIds) { - yield fetchAndStoreStorage(machines[index].storageIds[i]); - } + const machines = yield fetchAndStoreMachinesOfTile(tileId); + const machineIds = new Array(rack.capacity).fill(null); + machines.forEach(machine => (machineIds[machine.position - 1] = machine.id)); + + yield put(addPropToStoreObject("rack", rack.id, { machineIds })); + + for (let index in machines) { + for (let i in machines[index].cpuIds) { + yield fetchAndStoreCPU(machines[index].cpuIds[i]); + } + for (let i in machines[index].gpuIds) { + yield fetchAndStoreGPU(machines[index].gpuIds[i]); + } + for (let i in machines[index].memoryIds) { + yield fetchAndStoreMemory(machines[index].memoryIds[i]); + } + for (let i in machines[index].storageIds) { + yield fetchAndStoreStorage(machines[index].storageIds[i]); } + } } export function* onStartNewRoomConstruction() { - try { - const datacenterId = yield select(state => state.currentDatacenterId); - const room = yield call(addRoomToDatacenter, { - id: -1, - datacenterId, - roomType: "SERVER" - }); - const roomWithEmptyTileList = Object.assign({}, room, {tileIds: []}); - yield put(addToStore("room", roomWithEmptyTileList)); - yield put(addIdToStoreObjectListProp("datacenter", datacenterId, "roomIds", room.id)); - yield put(startNewRoomConstructionSucceeded(room.id)); - } catch (error) { - console.error(error); - } + try { + const datacenterId = yield select(state => state.currentDatacenterId); + const room = yield call(addRoomToDatacenter, { + id: -1, + datacenterId, + roomType: "SERVER" + }); + const roomWithEmptyTileList = Object.assign({}, room, { tileIds: [] }); + yield put(addToStore("room", roomWithEmptyTileList)); + yield put( + addIdToStoreObjectListProp("datacenter", datacenterId, "roomIds", room.id) + ); + yield put(startNewRoomConstructionSucceeded(room.id)); + } catch (error) { + console.error(error); + } } export function* onCancelNewRoomConstruction() { - try { - const datacenterId = yield select(state => state.currentDatacenterId); - const roomId = yield select(state => state.construction.currentRoomInConstruction); - yield call(deleteRoom, roomId); - yield put(removeIdFromStoreObjectListProp("datacenter", datacenterId, "roomIds", roomId)); - yield put(cancelNewRoomConstructionSucceeded()); - } catch (error) { - console.error(error); - } + try { + const datacenterId = yield select(state => state.currentDatacenterId); + const roomId = yield select( + state => state.construction.currentRoomInConstruction + ); + yield call(deleteRoom, roomId); + yield put( + removeIdFromStoreObjectListProp( + "datacenter", + datacenterId, + "roomIds", + roomId + ) + ); + yield put(cancelNewRoomConstructionSucceeded()); + } catch (error) { + console.error(error); + } } export function* onAddTile(action) { - try { - const roomId = yield select(state => state.construction.currentRoomInConstruction); - const tile = yield call(addTileToRoom, { - roomId, - positionX: action.positionX, - positionY: action.positionY - }); - yield put(addToStore("tile", tile)); - yield put(addIdToStoreObjectListProp("room", roomId, "tileIds", tile.id)); - } catch (error) { - console.error(error); - } + try { + const roomId = yield select( + state => state.construction.currentRoomInConstruction + ); + const tile = yield call(addTileToRoom, { + roomId, + positionX: action.positionX, + positionY: action.positionY + }); + yield put(addToStore("tile", tile)); + yield put(addIdToStoreObjectListProp("room", roomId, "tileIds", tile.id)); + } catch (error) { + console.error(error); + } } export function* onDeleteTile(action) { - try { - const roomId = yield select(state => state.construction.currentRoomInConstruction); - yield call(deleteTile, action.tileId); - yield put(removeIdFromStoreObjectListProp("room", roomId, "tileIds", action.tileId)); - } catch (error) { - console.error(error); - } + try { + const roomId = yield select( + state => state.construction.currentRoomInConstruction + ); + yield call(deleteTile, action.tileId); + yield put( + removeIdFromStoreObjectListProp("room", roomId, "tileIds", action.tileId) + ); + } catch (error) { + console.error(error); + } } export function* onEditRoomName(action) { - try { - const roomId = yield select(state => state.interactionLevel.roomId); - const room = Object.assign({}, yield select(state => state.objects.room[roomId])); - room.name = action.name; - yield call(updateRoom, room); - yield put(addPropToStoreObject("room", roomId, {name: action.name})); - } catch (error) { - console.error(error); - } + try { + const roomId = yield select(state => state.interactionLevel.roomId); + const room = Object.assign( + {}, + yield select(state => state.objects.room[roomId]) + ); + room.name = action.name; + yield call(updateRoom, room); + yield put(addPropToStoreObject("room", roomId, { name: action.name })); + } catch (error) { + console.error(error); + } } export function* onDeleteRoom() { - try { - const datacenterId = yield select(state => state.currentDatacenterId); - const roomId = yield select(state => state.interactionLevel.roomId); - yield call(deleteRoom, roomId); - yield put(goDownOneInteractionLevel()); - yield put(removeIdFromStoreObjectListProp("datacenter", datacenterId, "roomIds", roomId)); - } catch (error) { - console.error(error); - } + try { + const datacenterId = yield select(state => state.currentDatacenterId); + const roomId = yield select(state => state.interactionLevel.roomId); + yield call(deleteRoom, roomId); + yield put(goDownOneInteractionLevel()); + yield put( + removeIdFromStoreObjectListProp( + "datacenter", + datacenterId, + "roomIds", + roomId + ) + ); + } catch (error) { + console.error(error); + } } export function* onEditRackName(action) { - try { - const tileId = yield select(state => state.interactionLevel.tileId); - const rackId = yield select(state => state.objects.tile[state.interactionLevel.tileId].objectId); - const rack = Object.assign({}, yield select(state => state.objects.rack[rackId])); - rack.name = action.name; - yield call(updateRackOnTile, tileId, rack); - yield put(addPropToStoreObject("rack", rackId, {name: action.name})); - } catch (error) { - console.error(error); - } + try { + const tileId = yield select(state => state.interactionLevel.tileId); + const rackId = yield select( + state => state.objects.tile[state.interactionLevel.tileId].objectId + ); + const rack = Object.assign( + {}, + yield select(state => state.objects.rack[rackId]) + ); + rack.name = action.name; + yield call(updateRackOnTile, tileId, rack); + yield put(addPropToStoreObject("rack", rackId, { name: action.name })); + } catch (error) { + console.error(error); + } } export function* onDeleteRack() { - try { - const tileId = yield select(state => state.interactionLevel.tileId); - yield call(deleteRackFromTile, tileId); - yield put(goDownOneInteractionLevel()); - yield put(addPropToStoreObject("tile", tileId, {objectType: undefined})); - yield put(addPropToStoreObject("tile", tileId, {objectId: undefined})); - } catch (error) { - console.error(error); - } + try { + const tileId = yield select(state => state.interactionLevel.tileId); + yield call(deleteRackFromTile, tileId); + yield put(goDownOneInteractionLevel()); + yield put(addPropToStoreObject("tile", tileId, { objectType: undefined })); + yield put(addPropToStoreObject("tile", tileId, { objectId: undefined })); + } catch (error) { + console.error(error); + } } export function* onAddRackToTile(action) { - try { - const rack = yield call(addRackToTile, action.tileId, { - id: -1, - name: "Rack", - capacity: DEFAULT_RACK_SLOT_CAPACITY, - powerCapacityW: DEFAULT_RACK_POWER_CAPACITY - }); - rack.machineIds = new Array(rack.capacity).fill(null); - yield put(addToStore("rack", rack)); - yield put(addPropToStoreObject("tile", action.tileId, {objectId: rack.id})); - yield put(addPropToStoreObject("tile", action.tileId, {objectType: "RACK"})); - } catch (error) { - console.error(error); - } + try { + const rack = yield call(addRackToTile, action.tileId, { + id: -1, + name: "Rack", + capacity: DEFAULT_RACK_SLOT_CAPACITY, + powerCapacityW: DEFAULT_RACK_POWER_CAPACITY + }); + rack.machineIds = new Array(rack.capacity).fill(null); + yield put(addToStore("rack", rack)); + yield put( + addPropToStoreObject("tile", action.tileId, { objectId: rack.id }) + ); + yield put( + addPropToStoreObject("tile", action.tileId, { objectType: "RACK" }) + ); + } catch (error) { + console.error(error); + } } export function* onAddMachine(action) { - try { - const tileId = yield select(state => state.interactionLevel.tileId); - const rackId = yield select(state => state.objects.tile[state.interactionLevel.tileId].objectId); - const rack = yield select(state => state.objects.rack[rackId]); - - const machine = yield call(addMachineToRackOnTile, tileId, { - id: -1, - rackId, - position: action.position, - tags: [], - cpuIds: [], - gpuIds: [], - memoryIds: [], - storageIds: [], - }); - yield put(addToStore("machine", machine)); - - const machineIds = [...rack.machineIds]; - machineIds[machine.position - 1] = machine.id; - yield put(addPropToStoreObject("rack", rackId, {machineIds})); - } catch (error) { - console.error(error); - } + try { + const tileId = yield select(state => state.interactionLevel.tileId); + const rackId = yield select( + state => state.objects.tile[state.interactionLevel.tileId].objectId + ); + const rack = yield select(state => state.objects.rack[rackId]); + + const machine = yield call(addMachineToRackOnTile, tileId, { + id: -1, + rackId, + position: action.position, + tags: [], + cpuIds: [], + gpuIds: [], + memoryIds: [], + storageIds: [] + }); + yield put(addToStore("machine", machine)); + + const machineIds = [...rack.machineIds]; + machineIds[machine.position - 1] = machine.id; + yield put(addPropToStoreObject("rack", rackId, { machineIds })); + } catch (error) { + console.error(error); + } } export function* onDeleteMachine() { - try { - const tileId = yield select(state => state.interactionLevel.tileId); - const position = yield select(state => state.interactionLevel.position); - const rack = yield select(state => state.objects.rack[state.objects.tile[tileId].objectId]); - yield call(deleteMachineInRackOnTile, tileId, position); - const machineIds = [...rack.machineIds]; - machineIds[position - 1] = null; - yield put(goDownOneInteractionLevel()); - yield put(addPropToStoreObject("rack", rack.id, {machineIds})); - } catch (error) { - console.error(error); - } + try { + const tileId = yield select(state => state.interactionLevel.tileId); + const position = yield select(state => state.interactionLevel.position); + const rack = yield select( + state => state.objects.rack[state.objects.tile[tileId].objectId] + ); + yield call(deleteMachineInRackOnTile, tileId, position); + const machineIds = [...rack.machineIds]; + machineIds[position - 1] = null; + yield put(goDownOneInteractionLevel()); + yield put(addPropToStoreObject("rack", rack.id, { machineIds })); + } catch (error) { + console.error(error); + } } export function* onAddUnit(action) { - try { - const tileId = yield select(state => state.interactionLevel.tileId); - const position = yield select(state => state.interactionLevel.position); - const machine = yield select(state => state.objects.machine[state.objects.rack[ - state.objects.tile[tileId].objectId].machineIds[position - 1]]); - - if (machine[action.unitType + "Ids"].length >= MAX_NUM_UNITS_PER_MACHINE) { - return; - } - - const units = [...machine[action.unitType + "Ids"], action.id]; - const updatedMachine = Object.assign({}, machine, - {[action.unitType + "Ids"]: units}); - - yield call(updateMachineInRackOnTile, tileId, position, updatedMachine); - - yield put(addPropToStoreObject("machine", machine.id, {[action.unitType + "Ids"]: units})); - } catch (error) { - console.error(error); + try { + const tileId = yield select(state => state.interactionLevel.tileId); + const position = yield select(state => state.interactionLevel.position); + const machine = yield select( + state => + state.objects.machine[ + state.objects.rack[state.objects.tile[tileId].objectId].machineIds[ + position - 1 + ] + ] + ); + + if (machine[action.unitType + "Ids"].length >= MAX_NUM_UNITS_PER_MACHINE) { + return; } + + const units = [...machine[action.unitType + "Ids"], action.id]; + const updatedMachine = Object.assign({}, machine, { + [action.unitType + "Ids"]: units + }); + + yield call(updateMachineInRackOnTile, tileId, position, updatedMachine); + + yield put( + addPropToStoreObject("machine", machine.id, { + [action.unitType + "Ids"]: units + }) + ); + } catch (error) { + console.error(error); + } } export function* onDeleteUnit(action) { - try { - const tileId = yield select(state => state.interactionLevel.tileId); - const position = yield select(state => state.interactionLevel.position); - const machine = yield select(state => state.objects.machine[state.objects.rack[ - state.objects.tile[tileId].objectId].machineIds[position - 1]]); - const unitIds = machine[action.unitType + "Ids"].slice(); - unitIds.splice(action.index, 1); - const updatedMachine = Object.assign({}, machine, {[action.unitType + "Ids"]: unitIds}); - - yield call(updateMachineInRackOnTile, tileId, position, updatedMachine); - yield put(addPropToStoreObject("machine", machine.id, {[action.unitType + "Ids"]: unitIds})); - } catch (error) { - console.error(error); - } + try { + const tileId = yield select(state => state.interactionLevel.tileId); + const position = yield select(state => state.interactionLevel.position); + const machine = yield select( + state => + state.objects.machine[ + state.objects.rack[state.objects.tile[tileId].objectId].machineIds[ + position - 1 + ] + ] + ); + const unitIds = machine[action.unitType + "Ids"].slice(); + unitIds.splice(action.index, 1); + const updatedMachine = Object.assign({}, machine, { + [action.unitType + "Ids"]: unitIds + }); + + yield call(updateMachineInRackOnTile, tileId, position, updatedMachine); + yield put( + addPropToStoreObject("machine", machine.id, { + [action.unitType + "Ids"]: unitIds + }) + ); + } catch (error) { + console.error(error); + } } diff --git a/src/sagas/users.js b/src/sagas/users.js index f1ee9823..3825443a 100644 --- a/src/sagas/users.js +++ b/src/sagas/users.js @@ -1,46 +1,50 @@ -import {call, put} from "redux-saga/effects"; -import {logInSucceeded} from "../actions/auth"; -import {addToStore} from "../actions/objects"; -import {fetchAuthorizationsOfCurrentUserSucceeded} from "../actions/users"; -import {performTokenSignIn} from "../api/routes/token-signin"; -import {addUser, getAuthorizationsByUser} from "../api/routes/users"; -import {saveAuthLocalStorage} from "../auth/index"; -import {fetchAndStoreSimulation, fetchAndStoreUser} from "./objects"; +import { call, put } from "redux-saga/effects"; +import { logInSucceeded } from "../actions/auth"; +import { addToStore } from "../actions/objects"; +import { fetchAuthorizationsOfCurrentUserSucceeded } from "../actions/users"; +import { performTokenSignIn } from "../api/routes/token-signin"; +import { addUser, getAuthorizationsByUser } from "../api/routes/users"; +import { saveAuthLocalStorage } from "../auth/index"; +import { fetchAndStoreSimulation, fetchAndStoreUser } from "./objects"; export function* onFetchLoggedInUser(action) { - try { - const tokenResponse = yield call(performTokenSignIn, action.payload.authToken); - let userId = tokenResponse.userId; - - if (tokenResponse.isNewUser) { - saveAuthLocalStorage({authToken: action.payload.authToken}); - const newUser = yield call(addUser, action.payload); - userId = newUser.id; - } - - yield put(logInSucceeded(Object.assign({userId}, action.payload))); - } catch (error) { - console.error(error); + try { + const tokenResponse = yield call( + performTokenSignIn, + action.payload.authToken + ); + let userId = tokenResponse.userId; + + if (tokenResponse.isNewUser) { + saveAuthLocalStorage({ authToken: action.payload.authToken }); + const newUser = yield call(addUser, action.payload); + userId = newUser.id; } + + yield put(logInSucceeded(Object.assign({ userId }, action.payload))); + } catch (error) { + console.error(error); + } } export function* onFetchAuthorizationsOfCurrentUser(action) { - try { - const authorizations = yield call(getAuthorizationsByUser, action.userId); + try { + const authorizations = yield call(getAuthorizationsByUser, action.userId); - for (const authorization of authorizations) { - yield put(addToStore("authorization", authorization)); + for (const authorization of authorizations) { + yield put(addToStore("authorization", authorization)); - yield fetchAndStoreSimulation(authorization.simulationId); - yield fetchAndStoreUser(authorization.userId); - } + yield fetchAndStoreSimulation(authorization.simulationId); + yield fetchAndStoreUser(authorization.userId); + } - const authorizationIds = authorizations.map(authorization => ( - [authorization.userId, authorization.simulationId] - )); + const authorizationIds = authorizations.map(authorization => [ + authorization.userId, + authorization.simulationId + ]); - yield put(fetchAuthorizationsOfCurrentUserSucceeded(authorizationIds)); - } catch (error) { - console.error(error); - } + yield put(fetchAuthorizationsOfCurrentUserSucceeded(authorizationIds)); + } catch (error) { + console.error(error); + } } diff --git a/src/shapes/index.js b/src/shapes/index.js index c84e66e0..5570ef34 100644 --- a/src/shapes/index.js +++ b/src/shapes/index.js @@ -1,188 +1,188 @@ -import PropTypes from 'prop-types'; +import PropTypes from "prop-types"; const Shapes = {}; Shapes.User = PropTypes.shape({ - id: PropTypes.number.isRequired, - googleId: PropTypes.string.isRequired, - email: PropTypes.string.isRequired, - givenName: PropTypes.string.isRequired, - familyName: PropTypes.string.isRequired, + id: PropTypes.number.isRequired, + googleId: PropTypes.string.isRequired, + email: PropTypes.string.isRequired, + givenName: PropTypes.string.isRequired, + familyName: PropTypes.string.isRequired }); Shapes.Simulation = PropTypes.shape({ - id: PropTypes.number.isRequired, - name: PropTypes.string.isRequired, - datetimeCreated: PropTypes.string.isRequired, - datetimeLastEdited: PropTypes.string.isRequired, + id: PropTypes.number.isRequired, + name: PropTypes.string.isRequired, + datetimeCreated: PropTypes.string.isRequired, + datetimeLastEdited: PropTypes.string.isRequired }); Shapes.Authorization = PropTypes.shape({ - userId: PropTypes.number.isRequired, - user: Shapes.User, - simulationId: PropTypes.number.isRequired, - simulation: Shapes.Simulation, - authorizationLevel: PropTypes.string.isRequired, + userId: PropTypes.number.isRequired, + user: Shapes.User, + simulationId: PropTypes.number.isRequired, + simulation: Shapes.Simulation, + authorizationLevel: PropTypes.string.isRequired }); Shapes.FailureModel = PropTypes.shape({ - id: PropTypes.number.isRequired, - name: PropTypes.string.isRequired, - rate: PropTypes.number.isRequired, + id: PropTypes.number.isRequired, + name: PropTypes.string.isRequired, + rate: PropTypes.number.isRequired }); Shapes.ProcessingUnit = PropTypes.shape({ - id: PropTypes.number.isRequired, - manufacturer: PropTypes.string.isRequired, - family: PropTypes.string.isRequired, - generation: PropTypes.string.isRequired, - model: PropTypes.string.isRequired, - clockRateMhz: PropTypes.number.isRequired, - numberOfCores: PropTypes.number.isRequired, - energyConsumptionW: PropTypes.number.isRequired, - failureModelId: PropTypes.number.isRequired, - failureModel: Shapes.FailureModel, + id: PropTypes.number.isRequired, + manufacturer: PropTypes.string.isRequired, + family: PropTypes.string.isRequired, + generation: PropTypes.string.isRequired, + model: PropTypes.string.isRequired, + clockRateMhz: PropTypes.number.isRequired, + numberOfCores: PropTypes.number.isRequired, + energyConsumptionW: PropTypes.number.isRequired, + failureModelId: PropTypes.number.isRequired, + failureModel: Shapes.FailureModel }); Shapes.StorageUnit = PropTypes.shape({ - id: PropTypes.number.isRequired, - manufacturer: PropTypes.string.isRequired, - family: PropTypes.string.isRequired, - generation: PropTypes.string.isRequired, - model: PropTypes.string.isRequired, - speedMbPerS: PropTypes.number.isRequired, - sizeMb: PropTypes.number.isRequired, - energyConsumptionW: PropTypes.number.isRequired, - failureModelId: PropTypes.number.isRequired, - failureModel: Shapes.FailureModel, + id: PropTypes.number.isRequired, + manufacturer: PropTypes.string.isRequired, + family: PropTypes.string.isRequired, + generation: PropTypes.string.isRequired, + model: PropTypes.string.isRequired, + speedMbPerS: PropTypes.number.isRequired, + sizeMb: PropTypes.number.isRequired, + energyConsumptionW: PropTypes.number.isRequired, + failureModelId: PropTypes.number.isRequired, + failureModel: Shapes.FailureModel }); Shapes.Machine = PropTypes.shape({ - id: PropTypes.number.isRequired, - rackId: PropTypes.number.isRequired, - position: PropTypes.number.isRequired, - cpuIds: PropTypes.arrayOf(PropTypes.number.isRequired), - cpus: PropTypes.arrayOf(Shapes.ProcessingUnit), - gpuIds: PropTypes.arrayOf(PropTypes.number.isRequired), - gpus: PropTypes.arrayOf(Shapes.ProcessingUnit), - memoryIds: PropTypes.arrayOf(PropTypes.number.isRequired), - memories: PropTypes.arrayOf(Shapes.StorageUnit), - storageIds: PropTypes.arrayOf(PropTypes.number.isRequired), - storages: PropTypes.arrayOf(Shapes.StorageUnit), + id: PropTypes.number.isRequired, + rackId: PropTypes.number.isRequired, + position: PropTypes.number.isRequired, + cpuIds: PropTypes.arrayOf(PropTypes.number.isRequired), + cpus: PropTypes.arrayOf(Shapes.ProcessingUnit), + gpuIds: PropTypes.arrayOf(PropTypes.number.isRequired), + gpus: PropTypes.arrayOf(Shapes.ProcessingUnit), + memoryIds: PropTypes.arrayOf(PropTypes.number.isRequired), + memories: PropTypes.arrayOf(Shapes.StorageUnit), + storageIds: PropTypes.arrayOf(PropTypes.number.isRequired), + storages: PropTypes.arrayOf(Shapes.StorageUnit) }); Shapes.Rack = PropTypes.shape({ - id: PropTypes.number.isRequired, - name: PropTypes.string.isRequired, - capacity: PropTypes.number.isRequired, - powerCapacityW: PropTypes.number.isRequired, - machines: PropTypes.arrayOf(Shapes.Machine), + id: PropTypes.number.isRequired, + name: PropTypes.string.isRequired, + capacity: PropTypes.number.isRequired, + powerCapacityW: PropTypes.number.isRequired, + machines: PropTypes.arrayOf(Shapes.Machine) }); Shapes.CoolingItem = PropTypes.shape({ - id: PropTypes.number.isRequired, - energyConsumptionW: PropTypes.number.isRequired, - type: PropTypes.string.isRequired, - failureModelId: PropTypes.number.isRequired, - failureModel: Shapes.FailureModel, + id: PropTypes.number.isRequired, + energyConsumptionW: PropTypes.number.isRequired, + type: PropTypes.string.isRequired, + failureModelId: PropTypes.number.isRequired, + failureModel: Shapes.FailureModel }); Shapes.PSU = PropTypes.shape({ - id: PropTypes.number.isRequired, - energyKwh: PropTypes.number.isRequired, - type: PropTypes.string.isRequired, - failureModelId: PropTypes.number.isRequired, - failureModel: Shapes.FailureModel, + id: PropTypes.number.isRequired, + energyKwh: PropTypes.number.isRequired, + type: PropTypes.string.isRequired, + failureModelId: PropTypes.number.isRequired, + failureModel: Shapes.FailureModel }); Shapes.Tile = PropTypes.shape({ - id: PropTypes.number.isRequired, - roomId: PropTypes.number.isRequired, - positionX: PropTypes.number.isRequired, - positionY: PropTypes.number.isRequired, - objectId: PropTypes.number, - objectType: PropTypes.string, - rack: Shapes.Rack, - coolingItem: Shapes.CoolingItem, - psu: Shapes.PSU, + id: PropTypes.number.isRequired, + roomId: PropTypes.number.isRequired, + positionX: PropTypes.number.isRequired, + positionY: PropTypes.number.isRequired, + objectId: PropTypes.number, + objectType: PropTypes.string, + rack: Shapes.Rack, + coolingItem: Shapes.CoolingItem, + psu: Shapes.PSU }); Shapes.Room = PropTypes.shape({ - id: PropTypes.number.isRequired, - datacenterId: PropTypes.number.isRequired, - name: PropTypes.string.isRequired, - roomType: PropTypes.string.isRequired, - tiles: PropTypes.arrayOf(Shapes.Tile), + id: PropTypes.number.isRequired, + datacenterId: PropTypes.number.isRequired, + name: PropTypes.string.isRequired, + roomType: PropTypes.string.isRequired, + tiles: PropTypes.arrayOf(Shapes.Tile) }); Shapes.Datacenter = PropTypes.shape({ - id: PropTypes.number.isRequired, - rooms: PropTypes.arrayOf(Shapes.Room), + id: PropTypes.number.isRequired, + rooms: PropTypes.arrayOf(Shapes.Room) }); Shapes.Section = PropTypes.shape({ - id: PropTypes.number.isRequired, - pathId: PropTypes.number.isRequired, - startTick: PropTypes.number.isRequired, - datacenterId: PropTypes.number.isRequired, - datacenter: Shapes.Datacenter, + id: PropTypes.number.isRequired, + pathId: PropTypes.number.isRequired, + startTick: PropTypes.number.isRequired, + datacenterId: PropTypes.number.isRequired, + datacenter: Shapes.Datacenter }); Shapes.Path = PropTypes.shape({ - id: PropTypes.number.isRequired, - simulationId: PropTypes.number.isRequired, - name: PropTypes.string, - datetimeCreated: PropTypes.string.isRequired, - sections: PropTypes.arrayOf(Shapes.Section), + id: PropTypes.number.isRequired, + simulationId: PropTypes.number.isRequired, + name: PropTypes.string, + datetimeCreated: PropTypes.string.isRequired, + sections: PropTypes.arrayOf(Shapes.Section) }); Shapes.Scheduler = PropTypes.shape({ - name: PropTypes.string.isRequired, + name: PropTypes.string.isRequired }); Shapes.Task = PropTypes.shape({ - id: PropTypes.number.isRequired, - jobId: PropTypes.number.isRequired, - startTick: PropTypes.number.isRequired, - totalFlopCount: PropTypes.number.isRequired, + id: PropTypes.number.isRequired, + jobId: PropTypes.number.isRequired, + startTick: PropTypes.number.isRequired, + totalFlopCount: PropTypes.number.isRequired }); Shapes.Job = PropTypes.shape({ - id: PropTypes.number.isRequired, - name: PropTypes.string.isRequired, - traceId: PropTypes.number.isRequired, - taskIds: PropTypes.arrayOf(PropTypes.number), + id: PropTypes.number.isRequired, + name: PropTypes.string.isRequired, + traceId: PropTypes.number.isRequired, + taskIds: PropTypes.arrayOf(PropTypes.number) }); Shapes.Trace = PropTypes.shape({ - id: PropTypes.number.isRequired, - name: PropTypes.string.isRequired, - jobIds: PropTypes.arrayOf(PropTypes.number), + id: PropTypes.number.isRequired, + name: PropTypes.string.isRequired, + jobIds: PropTypes.arrayOf(PropTypes.number) }); Shapes.Experiment = PropTypes.shape({ - id: PropTypes.number.isRequired, - simulationId: PropTypes.number.isRequired, - traceId: PropTypes.number.isRequired, - trace: Shapes.Trace, - pathId: PropTypes.number.isRequired, - path: Shapes.Path, - schedulerName: PropTypes.string.isRequired, - scheduler: Shapes.Scheduler, - name: PropTypes.string.isRequired, + id: PropTypes.number.isRequired, + simulationId: PropTypes.number.isRequired, + traceId: PropTypes.number.isRequired, + trace: Shapes.Trace, + pathId: PropTypes.number.isRequired, + path: Shapes.Path, + schedulerName: PropTypes.string.isRequired, + scheduler: Shapes.Scheduler, + name: PropTypes.string.isRequired }); Shapes.WallSegment = PropTypes.shape({ - startPosX: PropTypes.number.isRequired, - startPosY: PropTypes.number.isRequired, - isHorizontal: PropTypes.bool.isRequired, - length: PropTypes.number.isRequired, + startPosX: PropTypes.number.isRequired, + startPosY: PropTypes.number.isRequired, + isHorizontal: PropTypes.bool.isRequired, + length: PropTypes.number.isRequired }); Shapes.InteractionLevel = PropTypes.shape({ - mode: PropTypes.string.isRequired, - roomId: PropTypes.number, - rackId: PropTypes.bool + mode: PropTypes.string.isRequired, + roomId: PropTypes.number, + rackId: PropTypes.bool }); export default Shapes; diff --git a/src/shortcuts/keymap.js b/src/shortcuts/keymap.js index 75986557..7bc24e83 100644 --- a/src/shortcuts/keymap.js +++ b/src/shortcuts/keymap.js @@ -1,10 +1,10 @@ const KeymapConfiguration = { - MAP: { - MOVE_LEFT: ["a", "left"], - MOVE_RIGHT: ["d", "right"], - MOVE_UP: ["w", "up"], - MOVE_DOWN: ["s", "down"], - }, + MAP: { + MOVE_LEFT: ["a", "left"], + MOVE_RIGHT: ["d", "right"], + MOVE_UP: ["w", "up"], + MOVE_DOWN: ["s", "down"] + } }; export default KeymapConfiguration; diff --git a/src/store/configure-store.js b/src/store/configure-store.js index 0c5baa0b..2c5f46fb 100644 --- a/src/store/configure-store.js +++ b/src/store/configure-store.js @@ -1,38 +1,35 @@ -import {applyMiddleware, compose, createStore} from "redux"; +import { applyMiddleware, compose, createStore } from "redux"; import persistState from "redux-localstorage"; -import {createLogger} from "redux-logger"; -import createSagaMiddleware from 'redux-saga'; +import { createLogger } from "redux-logger"; +import createSagaMiddleware from "redux-saga"; import thunk from "redux-thunk"; -import {authRedirectMiddleware} from "../auth/index"; +import { authRedirectMiddleware } from "../auth/index"; import rootReducer from "../reducers/index"; import rootSaga from "../sagas/index"; -import {dummyMiddleware} from "./middlewares/dummy-middleware"; -import {viewportAdjustmentMiddleware} from "./middlewares/viewport-adjustment"; +import { dummyMiddleware } from "./middlewares/dummy-middleware"; +import { viewportAdjustmentMiddleware } from "./middlewares/viewport-adjustment"; const sagaMiddleware = createSagaMiddleware(); let logger; -if (process.env.NODE_ENV !== 'production') { - logger = createLogger(); +if (process.env.NODE_ENV !== "production") { + logger = createLogger(); } const middlewares = [ - process.env.NODE_ENV === 'production' ? dummyMiddleware : logger, - thunk, - sagaMiddleware, - authRedirectMiddleware, - viewportAdjustmentMiddleware, + process.env.NODE_ENV === "production" ? dummyMiddleware : logger, + thunk, + sagaMiddleware, + authRedirectMiddleware, + viewportAdjustmentMiddleware ]; export default function configureStore() { - const store = createStore( - rootReducer, - compose( - persistState("auth"), - applyMiddleware(...middlewares) - ) - ); - sagaMiddleware.run(rootSaga); + const store = createStore( + rootReducer, + compose(persistState("auth"), applyMiddleware(...middlewares)) + ); + sagaMiddleware.run(rootSaga); - return store; + return store; } diff --git a/src/store/middlewares/dummy-middleware.js b/src/store/middlewares/dummy-middleware.js index eb87e713..468b15d1 100644 --- a/src/store/middlewares/dummy-middleware.js +++ b/src/store/middlewares/dummy-middleware.js @@ -1,3 +1,3 @@ export const dummyMiddleware = store => next => action => { - next(action); + next(action); }; diff --git a/src/store/middlewares/viewport-adjustment.js b/src/store/middlewares/viewport-adjustment.js index a0056ee5..132391f3 100644 --- a/src/store/middlewares/viewport-adjustment.js +++ b/src/store/middlewares/viewport-adjustment.js @@ -1,73 +1,90 @@ -import {SET_MAP_DIMENSIONS, setMapPosition, setMapScale} from "../../actions/map"; -import {SET_CURRENT_DATACENTER} from "../../actions/topology/building"; import { - MAP_MAX_SCALE, - MAP_MIN_SCALE, - SIDEBAR_WIDTH, - TILE_SIZE_IN_PIXELS, - VIEWPORT_PADDING + SET_MAP_DIMENSIONS, + setMapPosition, + setMapScale +} from "../../actions/map"; +import { SET_CURRENT_DATACENTER } from "../../actions/topology/building"; +import { + MAP_MAX_SCALE, + MAP_MIN_SCALE, + SIDEBAR_WIDTH, + TILE_SIZE_IN_PIXELS, + VIEWPORT_PADDING } from "../../components/app/map/MapConstants"; -import {calculateRoomListBounds} from "../../util/tile-calculations"; +import { calculateRoomListBounds } from "../../util/tile-calculations"; export const viewportAdjustmentMiddleware = store => next => action => { - const state = store.getState(); + const state = store.getState(); - let datacenterId = -1; - let mapDimensions = {}; - if (action.type === SET_CURRENT_DATACENTER && action.datacenterId !== -1) { - datacenterId = action.datacenterId; - mapDimensions = state.map.dimensions; - } else if (action.type === SET_MAP_DIMENSIONS && state.currentDatacenterId !== -1) { - datacenterId = state.currentDatacenterId; - mapDimensions = {width: action.width, height: action.height}; - } + let datacenterId = -1; + let mapDimensions = {}; + if (action.type === SET_CURRENT_DATACENTER && action.datacenterId !== -1) { + datacenterId = action.datacenterId; + mapDimensions = state.map.dimensions; + } else if ( + action.type === SET_MAP_DIMENSIONS && + state.currentDatacenterId !== -1 + ) { + datacenterId = state.currentDatacenterId; + mapDimensions = { width: action.width, height: action.height }; + } - if (datacenterId !== -1) { - const roomIds = state.objects.datacenter[datacenterId].roomIds; - const rooms = roomIds.map(id => Object.assign({}, state.objects.room[id])); - rooms.forEach(room => room.tiles = room.tileIds.map(tileId => state.objects.tile[tileId])); + if (datacenterId !== -1) { + const roomIds = state.objects.datacenter[datacenterId].roomIds; + const rooms = roomIds.map(id => Object.assign({}, state.objects.room[id])); + rooms.forEach( + room => + (room.tiles = room.tileIds.map(tileId => state.objects.tile[tileId])) + ); - let hasNoTiles = true; - for (let i in rooms) { - if (rooms[i].tiles.length > 0) { - hasNoTiles = false; - break; - } - } + let hasNoTiles = true; + for (let i in rooms) { + if (rooms[i].tiles.length > 0) { + hasNoTiles = false; + break; + } + } - if (!hasNoTiles) { - const viewportParams = calculateParametersToZoomInOnRooms(rooms, mapDimensions.width, mapDimensions.height); - store.dispatch(setMapPosition(viewportParams.newX, viewportParams.newY)); - store.dispatch(setMapScale(viewportParams.newScale)); - } + if (!hasNoTiles) { + const viewportParams = calculateParametersToZoomInOnRooms( + rooms, + mapDimensions.width, + mapDimensions.height + ); + store.dispatch(setMapPosition(viewportParams.newX, viewportParams.newY)); + store.dispatch(setMapScale(viewportParams.newScale)); } + } - next(action); + next(action); }; function calculateParametersToZoomInOnRooms(rooms, mapWidth, mapHeight) { - const bounds = calculateRoomListBounds(rooms); - const newScale = calculateNewScale(bounds, mapWidth, mapHeight); + const bounds = calculateRoomListBounds(rooms); + const newScale = calculateNewScale(bounds, mapWidth, mapHeight); - // Coordinates of the center of the room, relative to the global origin of the map - const roomCenterCoordinates = { - x: bounds.center.x * TILE_SIZE_IN_PIXELS * newScale, - y: bounds.center.y * TILE_SIZE_IN_PIXELS * newScale - }; + // Coordinates of the center of the room, relative to the global origin of the map + const roomCenterCoordinates = { + x: bounds.center.x * TILE_SIZE_IN_PIXELS * newScale, + y: bounds.center.y * TILE_SIZE_IN_PIXELS * newScale + }; - const newX = -roomCenterCoordinates.x + mapWidth / 2; - const newY = -roomCenterCoordinates.y + mapHeight / 2; + const newX = -roomCenterCoordinates.x + mapWidth / 2; + const newY = -roomCenterCoordinates.y + mapHeight / 2; - return {newScale, newX, newY}; + return { newScale, newX, newY }; } function calculateNewScale(bounds, mapWidth, mapHeight) { - const width = bounds.max.x - bounds.min.x; - const height = bounds.max.y - bounds.min.y; + const width = bounds.max.x - bounds.min.x; + const height = bounds.max.y - bounds.min.y; - const scaleX = (mapWidth - 2 * SIDEBAR_WIDTH) / (width * TILE_SIZE_IN_PIXELS + 2 * VIEWPORT_PADDING); - const scaleY = mapHeight / (height * TILE_SIZE_IN_PIXELS + 2 * VIEWPORT_PADDING); - const newScale = Math.min(scaleX, scaleY); + const scaleX = + (mapWidth - 2 * SIDEBAR_WIDTH) / + (width * TILE_SIZE_IN_PIXELS + 2 * VIEWPORT_PADDING); + const scaleY = + mapHeight / (height * TILE_SIZE_IN_PIXELS + 2 * VIEWPORT_PADDING); + const newScale = Math.min(scaleX, scaleY); - return Math.min(Math.max(MAP_MIN_SCALE, newScale), MAP_MAX_SCALE); + return Math.min(Math.max(MAP_MIN_SCALE, newScale), MAP_MAX_SCALE); } diff --git a/src/util/authorizations.js b/src/util/authorizations.js index 9a7d4e36..ef649c9c 100644 --- a/src/util/authorizations.js +++ b/src/util/authorizations.js @@ -1,11 +1,11 @@ export const AUTH_ICON_MAP = { - "OWN": "home", - "EDIT": "pencil", - "VIEW": "eye", + OWN: "home", + EDIT: "pencil", + VIEW: "eye" }; export const AUTH_DESCRIPTION_MAP = { - "OWN": "Own", - "EDIT": "Can Edit", - "VIEW": "Can View", + OWN: "Own", + EDIT: "Can Edit", + VIEW: "Can View" }; diff --git a/src/util/date-time.js b/src/util/date-time.js index e9d7664f..2664b8ca 100644 --- a/src/util/date-time.js +++ b/src/util/date-time.js @@ -7,7 +7,7 @@ * @returns {string} A human-friendly string version of that date and time. */ export function parseAndFormatDateTime(dateTimeString) { - return formatDateTime(parseDateTime(dateTimeString)); + return formatDateTime(parseDateTime(dateTimeString)); } /** @@ -19,27 +19,27 @@ export function parseAndFormatDateTime(dateTimeString) { * @returns {object} An rack with the parsed date and time information as content. */ export function parseDateTime(dateTimeString) { - const output = { - year: 0, - month: 0, - day: 0, - hour: 0, - minute: 0, - second: 0, - }; + const output = { + year: 0, + month: 0, + day: 0, + hour: 0, + minute: 0, + second: 0 + }; - const dateAndTime = dateTimeString.split("T"); - const dateComponents = dateAndTime[0].split("-"); - output.year = parseInt(dateComponents[0], 10); - output.month = parseInt(dateComponents[1], 10); - output.day = parseInt(dateComponents[2], 10); + const dateAndTime = dateTimeString.split("T"); + const dateComponents = dateAndTime[0].split("-"); + output.year = parseInt(dateComponents[0], 10); + output.month = parseInt(dateComponents[1], 10); + output.day = parseInt(dateComponents[2], 10); - const timeComponents = dateAndTime[1].split(":"); - output.hour = parseInt(timeComponents[0], 10); - output.minute = parseInt(timeComponents[1], 10); - output.second = parseInt(timeComponents[2], 10); + const timeComponents = dateAndTime[1].split(":"); + output.hour = parseInt(timeComponents[0], 10); + output.minute = parseInt(timeComponents[1], 10); + output.second = parseInt(timeComponents[2], 10); - return output; + return output; } /** @@ -49,25 +49,34 @@ export function parseDateTime(dateTimeString) { * @returns {string} A human-friendly string version of that date and time. */ export function formatDateTime(dateTime) { - let date; - const currentDate = new Date(); + let date; + const currentDate = new Date(); - date = addPaddingToTwo(dateTime.day) + "/" + - addPaddingToTwo(dateTime.month) + "/" + - addPaddingToTwo(dateTime.year); + date = + addPaddingToTwo(dateTime.day) + + "/" + + addPaddingToTwo(dateTime.month) + + "/" + + addPaddingToTwo(dateTime.year); - if (dateTime.year === currentDate.getFullYear() && - dateTime.month === currentDate.getMonth() + 1) { - if (dateTime.day === currentDate.getDate()) { - date = "Today"; - } else if (dateTime.day === currentDate.getDate() - 1) { - date = "Yesterday"; - } + if ( + dateTime.year === currentDate.getFullYear() && + dateTime.month === currentDate.getMonth() + 1 + ) { + if (dateTime.day === currentDate.getDate()) { + date = "Today"; + } else if (dateTime.day === currentDate.getDate() - 1) { + date = "Yesterday"; } + } - return date + ", " + - addPaddingToTwo(dateTime.hour) + ":" + - addPaddingToTwo(dateTime.minute); + return ( + date + + ", " + + addPaddingToTwo(dateTime.hour) + + ":" + + addPaddingToTwo(dateTime.minute) + ); } /** @@ -77,25 +86,27 @@ export function formatDateTime(dateTime) { * @returns {string} A string representation of that amount of second, in the from of HH:MM:SS. */ export function convertSecondsToFormattedTime(seconds) { - if (seconds <= 0) { - return "0s"; - } + if (seconds <= 0) { + return "0s"; + } - let hour = Math.floor(seconds / 3600); - let minute = Math.floor(seconds / 60) % 60; - let second = seconds % 60; + let hour = Math.floor(seconds / 3600); + let minute = Math.floor(seconds / 60) % 60; + let second = seconds % 60; - hour = isNaN(hour) ? 0 : hour; - minute = isNaN(minute) ? 0 : minute; - second = isNaN(second) ? 0 : second; + hour = isNaN(hour) ? 0 : hour; + minute = isNaN(minute) ? 0 : minute; + second = isNaN(second) ? 0 : second; - if (hour === 0 && minute === 0) { - return second + "s"; - } else if (hour === 0) { - return minute + "m" + addPaddingToTwo(second) + "s"; - } else { - return hour + "h" + addPaddingToTwo(minute) + "m" + addPaddingToTwo(second) + "s"; - } + if (hour === 0 && minute === 0) { + return second + "s"; + } else if (hour === 0) { + return minute + "m" + addPaddingToTwo(second) + "s"; + } else { + return ( + hour + "h" + addPaddingToTwo(minute) + "m" + addPaddingToTwo(second) + "s" + ); + } } /** @@ -105,9 +116,9 @@ export function convertSecondsToFormattedTime(seconds) { * @returns {string} A string containing the padded integer. */ function addPaddingToTwo(integer) { - if (integer < 10) { - return "0" + integer.toString(); - } else { - return integer.toString(); - } + if (integer < 10) { + return "0" + integer.toString(); + } else { + return integer.toString(); + } } diff --git a/src/util/date-time.test.js b/src/util/date-time.test.js index 9dce202b..958428af 100644 --- a/src/util/date-time.test.js +++ b/src/util/date-time.test.js @@ -1,35 +1,35 @@ -import {convertSecondsToFormattedTime, parseDateTime} from "./date-time"; +import { convertSecondsToFormattedTime, parseDateTime } from "./date-time"; describe("date-time parsing", () => { - it("reads components properly", () => { - const dateString = "2017-09-27T20:55:01"; - const parsedDate = parseDateTime(dateString); + it("reads components properly", () => { + const dateString = "2017-09-27T20:55:01"; + const parsedDate = parseDateTime(dateString); - expect(parsedDate.year).toEqual(2017); - expect(parsedDate.month).toEqual(9); - expect(parsedDate.day).toEqual(27); - expect(parsedDate.hour).toEqual(20); - expect(parsedDate.minute).toEqual(55); - expect(parsedDate.second).toEqual(1); - }); + expect(parsedDate.year).toEqual(2017); + expect(parsedDate.month).toEqual(9); + expect(parsedDate.day).toEqual(27); + expect(parsedDate.hour).toEqual(20); + expect(parsedDate.minute).toEqual(55); + expect(parsedDate.second).toEqual(1); + }); }); describe("tick formatting", () => { - it("returns '0s' for numbers <= 0", () => { - expect(convertSecondsToFormattedTime(-1)).toEqual("0s"); - expect(convertSecondsToFormattedTime(0)).toEqual("0s"); - }); - it("returns only seconds for values under a minute", () => { - expect(convertSecondsToFormattedTime(1)).toEqual("1s"); - expect(convertSecondsToFormattedTime(59)).toEqual("59s"); - }); - it("returns seconds and minutes for values under an hour", () => { - expect(convertSecondsToFormattedTime(60)).toEqual("1m00s"); - expect(convertSecondsToFormattedTime(61)).toEqual("1m01s"); - expect(convertSecondsToFormattedTime(3599)).toEqual("59m59s"); - }); - it("returns full time for values over an hour", () => { - expect(convertSecondsToFormattedTime(3600)).toEqual("1h00m00s"); - expect(convertSecondsToFormattedTime(3601)).toEqual("1h00m01s"); - }); + it("returns '0s' for numbers <= 0", () => { + expect(convertSecondsToFormattedTime(-1)).toEqual("0s"); + expect(convertSecondsToFormattedTime(0)).toEqual("0s"); + }); + it("returns only seconds for values under a minute", () => { + expect(convertSecondsToFormattedTime(1)).toEqual("1s"); + expect(convertSecondsToFormattedTime(59)).toEqual("59s"); + }); + it("returns seconds and minutes for values under an hour", () => { + expect(convertSecondsToFormattedTime(60)).toEqual("1m00s"); + expect(convertSecondsToFormattedTime(61)).toEqual("1m01s"); + expect(convertSecondsToFormattedTime(3599)).toEqual("59m59s"); + }); + it("returns full time for values over an hour", () => { + expect(convertSecondsToFormattedTime(3600)).toEqual("1h00m00s"); + expect(convertSecondsToFormattedTime(3601)).toEqual("1h00m01s"); + }); }); diff --git a/src/util/room-types.js b/src/util/room-types.js index ec0c4473..5cfe3887 100644 --- a/src/util/room-types.js +++ b/src/util/room-types.js @@ -1,7 +1,7 @@ export const ROOM_TYPE_TO_NAME_MAP = { - "SERVER": "Server room", - "HALLWAY": "Hallway", - "OFFICE": "Office", - "POWER": "Power room", - "COOLING": "Cooling room", + SERVER: "Server room", + HALLWAY: "Hallway", + OFFICE: "Office", + POWER: "Power room", + COOLING: "Cooling room" }; diff --git a/src/util/simulation-load.js b/src/util/simulation-load.js index 4b6233be..95e17fed 100644 --- a/src/util/simulation-load.js +++ b/src/util/simulation-load.js @@ -1,32 +1,37 @@ -import {SIM_HIGH_COLOR, SIM_LOW_COLOR, SIM_MID_HIGH_COLOR, SIM_MID_LOW_COLOR} from "./colors"; +import { + SIM_HIGH_COLOR, + SIM_LOW_COLOR, + SIM_MID_HIGH_COLOR, + SIM_MID_LOW_COLOR +} from "./colors"; export const LOAD_NAME_MAP = { - LOAD: "computational load", - TEMPERATURE: "temperature", - MEMORY: "memory use", + LOAD: "computational load", + TEMPERATURE: "temperature", + MEMORY: "memory use" }; export function convertLoadToSimulationColor(load) { - if (load <= 0.25) { - return SIM_LOW_COLOR; - } else if (load <= 0.5) { - return SIM_MID_LOW_COLOR; - } else if (load <= 0.75) { - return SIM_MID_HIGH_COLOR; - } else { - return SIM_HIGH_COLOR; - } + if (load <= 0.25) { + return SIM_LOW_COLOR; + } else if (load <= 0.5) { + return SIM_MID_LOW_COLOR; + } else if (load <= 0.75) { + return SIM_MID_HIGH_COLOR; + } else { + return SIM_HIGH_COLOR; + } } export function getStateLoad(loadMetric, state) { - switch (loadMetric) { - case "LOAD": - return state.loadFraction; - case "TEMPERATURE": - return state.temperatureC / 100.0; - case "MEMORY": - return state.inUseMemoryMb / 10000.0; - default: - return -1; - } + switch (loadMetric) { + case "LOAD": + return state.loadFraction; + case "TEMPERATURE": + return state.temperatureC / 100.0; + case "MEMORY": + return state.inUseMemoryMb / 10000.0; + default: + return -1; + } } diff --git a/src/util/tile-calculations.js b/src/util/tile-calculations.js index 31b5d8aa..9a1dc1c0 100644 --- a/src/util/tile-calculations.js +++ b/src/util/tile-calculations.js @@ -1,243 +1,253 @@ export function deriveWallLocations(tiles) { - const verticalWalls = {}; - const horizontalWalls = {}; - - // Determine wall segments - - tiles.forEach(tile => { - const x = tile.positionX, y = tile.positionY; - for (let dX = -1; dX <= 1; dX++) { - for (let dY = -1; dY <= 1; dY++) { - if (Math.abs(dX) === Math.abs(dY)) { - continue; - } - - let doInsert = true; - tiles.forEach(otherTile => { - if (otherTile.positionX === x + dX && otherTile.positionY === y + dY) { - doInsert = false; - } - }); - if (!doInsert) { - continue; - } - - if (dX === -1) { - if (verticalWalls[x] === undefined) { - verticalWalls[x] = []; - } - if (verticalWalls[x].indexOf(y) === -1) { - verticalWalls[x].push(y); - } - } else if (dX === 1) { - if (verticalWalls[x + 1] === undefined) { - verticalWalls[x + 1] = []; - } - if (verticalWalls[x + 1].indexOf(y) === -1) { - verticalWalls[x + 1].push(y); - } - } else if (dY === -1) { - if (horizontalWalls[y] === undefined) { - horizontalWalls[y] = []; - } - if (horizontalWalls[y].indexOf(x) === -1) { - horizontalWalls[y].push(x); - } - } else if (dY === 1) { - if (horizontalWalls[y + 1] === undefined) { - horizontalWalls[y + 1] = []; - } - if (horizontalWalls[y + 1].indexOf(x) === -1) { - horizontalWalls[y + 1].push(x); - } - } - } + const verticalWalls = {}; + const horizontalWalls = {}; + + // Determine wall segments + + tiles.forEach(tile => { + const x = tile.positionX, + y = tile.positionY; + for (let dX = -1; dX <= 1; dX++) { + for (let dY = -1; dY <= 1; dY++) { + if (Math.abs(dX) === Math.abs(dY)) { + continue; } - }); - - // Merge walls into longer segments - const result = []; - const walls = [verticalWalls, horizontalWalls]; - for (let i = 0; i < 2; i++) { - const wallList = walls[i]; - for (let a in wallList) { - a = parseInt(a, 10); - - wallList[a].sort((a, b) => { - return a - b; - }); + let doInsert = true; + tiles.forEach(otherTile => { + if ( + otherTile.positionX === x + dX && + otherTile.positionY === y + dY + ) { + doInsert = false; + } + }); + if (!doInsert) { + continue; + } - let startPos = wallList[a][0]; - const isHorizontal = i === 1; - - if (wallList[a].length === 1) { - const startPosX = isHorizontal ? startPos : a; - const startPosY = isHorizontal ? a : startPos; - result.push({ - startPosX, - startPosY, - isHorizontal, - length: 1 - }); - } else { - let consecutiveCount = 1; - for (let b = 0; b < wallList[a].length - 1; b++) { - if (b + 1 === wallList[a].length - 1) { - if (wallList[a][b + 1] - wallList[a][b] > 1) { - const startPosX = isHorizontal ? startPos : a; - const startPosY = isHorizontal ? a : startPos; - result.push({ - startPosX, - startPosY, - isHorizontal, - length: consecutiveCount - }); - consecutiveCount = 0; - startPos = wallList[a][b + 1]; - } - const startPosX = isHorizontal ? startPos : a; - const startPosY = isHorizontal ? a : startPos; - result.push({ - startPosX, - startPosY, - isHorizontal, - length: consecutiveCount + 1 - }); - break; - } else if (wallList[a][b + 1] - wallList[a][b] > 1) { - const startPosX = isHorizontal ? startPos : a; - const startPosY = isHorizontal ? a : startPos; - result.push({ - startPosX, - startPosY, - isHorizontal, - length: consecutiveCount - }); - startPos = wallList[a][b + 1]; - consecutiveCount = 0; - } - consecutiveCount++; - } + if (dX === -1) { + if (verticalWalls[x] === undefined) { + verticalWalls[x] = []; + } + if (verticalWalls[x].indexOf(y) === -1) { + verticalWalls[x].push(y); + } + } else if (dX === 1) { + if (verticalWalls[x + 1] === undefined) { + verticalWalls[x + 1] = []; + } + if (verticalWalls[x + 1].indexOf(y) === -1) { + verticalWalls[x + 1].push(y); + } + } else if (dY === -1) { + if (horizontalWalls[y] === undefined) { + horizontalWalls[y] = []; + } + if (horizontalWalls[y].indexOf(x) === -1) { + horizontalWalls[y].push(x); + } + } else if (dY === 1) { + if (horizontalWalls[y + 1] === undefined) { + horizontalWalls[y + 1] = []; + } + if (horizontalWalls[y + 1].indexOf(x) === -1) { + horizontalWalls[y + 1].push(x); + } + } + } + } + }); + + // Merge walls into longer segments + + const result = []; + const walls = [verticalWalls, horizontalWalls]; + for (let i = 0; i < 2; i++) { + const wallList = walls[i]; + for (let a in wallList) { + a = parseInt(a, 10); + + wallList[a].sort((a, b) => { + return a - b; + }); + + let startPos = wallList[a][0]; + const isHorizontal = i === 1; + + if (wallList[a].length === 1) { + const startPosX = isHorizontal ? startPos : a; + const startPosY = isHorizontal ? a : startPos; + result.push({ + startPosX, + startPosY, + isHorizontal, + length: 1 + }); + } else { + let consecutiveCount = 1; + for (let b = 0; b < wallList[a].length - 1; b++) { + if (b + 1 === wallList[a].length - 1) { + if (wallList[a][b + 1] - wallList[a][b] > 1) { + const startPosX = isHorizontal ? startPos : a; + const startPosY = isHorizontal ? a : startPos; + result.push({ + startPosX, + startPosY, + isHorizontal, + length: consecutiveCount + }); + consecutiveCount = 0; + startPos = wallList[a][b + 1]; } + const startPosX = isHorizontal ? startPos : a; + const startPosY = isHorizontal ? a : startPos; + result.push({ + startPosX, + startPosY, + isHorizontal, + length: consecutiveCount + 1 + }); + break; + } else if (wallList[a][b + 1] - wallList[a][b] > 1) { + const startPosX = isHorizontal ? startPos : a; + const startPosY = isHorizontal ? a : startPos; + result.push({ + startPosX, + startPosY, + isHorizontal, + length: consecutiveCount + }); + startPos = wallList[a][b + 1]; + consecutiveCount = 0; + } + consecutiveCount++; } + } } + } - return result; + return result; } export function deriveValidNextTilePositions(rooms, selectedTiles) { - const result = [], newPosition = {x: 0, y: 0}; - let isSurroundingTile; - - selectedTiles.forEach((tile) => { - const x = tile.positionX; - const y = tile.positionY; - result.push({x, y}); - - for (let dX = -1; dX <= 1; dX++) { - for (let dY = -1; dY <= 1; dY++) { - if (Math.abs(dX) === Math.abs(dY)) { - continue; - } - - newPosition.x = x + dX; - newPosition.y = y + dY; - - isSurroundingTile = true; - for (let index in selectedTiles) { - if (selectedTiles[index].positionX === newPosition.x - && selectedTiles[index].positionY === newPosition.y) { - isSurroundingTile = false; - break; - } - } - - if (isSurroundingTile && findPositionInRooms(rooms, newPosition.x, newPosition.y) === -1) { - result.push({x: newPosition.x, y: newPosition.y}); - } - } + const result = [], + newPosition = { x: 0, y: 0 }; + let isSurroundingTile; + + selectedTiles.forEach(tile => { + const x = tile.positionX; + const y = tile.positionY; + result.push({ x, y }); + + for (let dX = -1; dX <= 1; dX++) { + for (let dY = -1; dY <= 1; dY++) { + if (Math.abs(dX) === Math.abs(dY)) { + continue; } - }); - return result; + newPosition.x = x + dX; + newPosition.y = y + dY; + + isSurroundingTile = true; + for (let index in selectedTiles) { + if ( + selectedTiles[index].positionX === newPosition.x && + selectedTiles[index].positionY === newPosition.y + ) { + isSurroundingTile = false; + break; + } + } + + if ( + isSurroundingTile && + findPositionInRooms(rooms, newPosition.x, newPosition.y) === -1 + ) { + result.push({ x: newPosition.x, y: newPosition.y }); + } + } + } + }); + + return result; } export function findPositionInPositions(positions, positionX, positionY) { - for (let i = 0; i < positions.length; i++) { - const position = positions[i]; - if (positionX === position.x && positionY === position.y) { - return i; - } + for (let i = 0; i < positions.length; i++) { + const position = positions[i]; + if (positionX === position.x && positionY === position.y) { + return i; } + } - return -1; + return -1; } export function findPositionInRooms(rooms, positionX, positionY) { - for (let i = 0; i < rooms.length; i++) { - const room = rooms[i]; - if (findPositionInTiles(room.tiles, positionX, positionY) !== -1) { - return i; - } + for (let i = 0; i < rooms.length; i++) { + const room = rooms[i]; + if (findPositionInTiles(room.tiles, positionX, positionY) !== -1) { + return i; } + } - return -1; + return -1; } function findPositionInTiles(tiles, positionX, positionY) { - let index = -1; + let index = -1; - for (let i = 0; i < tiles.length; i++) { - const tile = tiles[i]; - if (positionX === tile.positionX && positionY === tile.positionY) { - index = i; - break; - } + for (let i = 0; i < tiles.length; i++) { + const tile = tiles[i]; + if (positionX === tile.positionX && positionY === tile.positionY) { + index = i; + break; } + } - return index; + return index; } export function findTileWithPosition(tiles, positionX, positionY) { - for (let i = 0; i < tiles.length; i++) { - if (tiles[i].positionX === positionX && tiles[i].positionY === positionY) { - return tiles[i]; - } + for (let i = 0; i < tiles.length; i++) { + if (tiles[i].positionX === positionX && tiles[i].positionY === positionY) { + return tiles[i]; } + } - return null; + return null; } export function calculateRoomListBounds(rooms) { - const min = {x: Number.MAX_VALUE, y: Number.MAX_VALUE}; - const max = {x: -1, y: -1}; - - rooms.forEach((room) => { - room.tiles.forEach((tile) => { - if (tile.positionX < min.x) { - min.x = tile.positionX; - } - if (tile.positionY < min.y) { - min.y = tile.positionY; - } - - if (tile.positionX > max.x) { - max.x = tile.positionX; - } - if (tile.positionY > max.y) { - max.y = tile.positionY; - } - }); + const min = { x: Number.MAX_VALUE, y: Number.MAX_VALUE }; + const max = { x: -1, y: -1 }; + + rooms.forEach(room => { + room.tiles.forEach(tile => { + if (tile.positionX < min.x) { + min.x = tile.positionX; + } + if (tile.positionY < min.y) { + min.y = tile.positionY; + } + + if (tile.positionX > max.x) { + max.x = tile.positionX; + } + if (tile.positionY > max.y) { + max.y = tile.positionY; + } }); + }); - max.x++; - max.y++; + max.x++; + max.y++; - const center = { - x: min.x + (max.x - min.x) / 2.0, - y: min.y + (max.y - min.y) / 2.0 - }; + const center = { + x: min.x + (max.x - min.x) / 2.0, + y: min.y + (max.y - min.y) / 2.0 + }; - return {min, center, max}; + return { min, center, max }; } diff --git a/src/util/timeline.js b/src/util/timeline.js index c6828ad7..e20d5823 100644 --- a/src/util/timeline.js +++ b/src/util/timeline.js @@ -1,19 +1,19 @@ export function convertTickToPercentage(tick, maxTick) { - if (maxTick === 0) { - return "0%"; - } else if (tick > maxTick) { - return ((maxTick / (maxTick + 1)) * 100) + "%"; - } + if (maxTick === 0) { + return "0%"; + } else if (tick > maxTick) { + return maxTick / (maxTick + 1) * 100 + "%"; + } - return ((tick / (maxTick + 1)) * 100) + "%"; + return tick / (maxTick + 1) * 100 + "%"; } export function getDatacenterIdOfTick(tick, sections) { - for (let i in sections.reverse()) { - if (tick >= sections[i].startTick) { - return sections[i].datacenterId; - } + for (let i in sections.reverse()) { + if (tick >= sections[i].startTick) { + return sections[i].datacenterId; } + } - return -1; + return -1; } |
