diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..4f0a173 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,3 @@ +node_modules/ +doc/ +npm-debug.log diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..b41d3eb --- /dev/null +++ b/.editorconfig @@ -0,0 +1,17 @@ +# EditorConfig is awesome: http://EditorConfig.org + +# top-most EditorConfig file +root = true + +# Unix-style newlines with a newline ending every file +[*] +end_of_line = lf +insert_final_newline = true + +# Matches multiple files with brace expansion notation +# Set default charset +[*.js] +charset = utf-8 +indent_style = space +indent_size = 2 +trim_trailing_whitespace=true diff --git a/.gitignore b/.gitignore index 86fceae..801e1dd 100644 --- a/.gitignore +++ b/.gitignore @@ -1,17 +1,19 @@ -# See http://help.github.com/ignore-files/ for more about ignoring files. - -# compiled output -/dist -/tmp +# See https://help.github.com/ignore-files/ for more about ignoring files. # dependencies /node_modules -/bower_components + +# testing +/coverage + +# production +/build # misc -/.sass-cache -/connect.lock -/coverage/* -/libpeerconnection.log -npm-debug.log -testem.log +.DS_Store +.env +npm-debug.log* +yarn-debug.log* +yarn-error.log* +.vscode/ +*.code-workspace diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml new file mode 100644 index 0000000..e9305b1 --- /dev/null +++ b/.gitlab-ci.yml @@ -0,0 +1,66 @@ +variables: + GIT_SUBMODULE_STRATEGY: normal + DOCKER_TAG: ${CI_COMMIT_REF_NAME} + DOCKER_IMAGE_DEV: villas/web-dev:${CI_COMMIT_REF_NAME} + +cache: + untracked: true + key: ${CI_PROJECT_ID} + paths: + - node_modules/ + - _site/vendor/ + - .bundled/ + - .yarn + +stages: + - prepare + - build + - test + - deploy + +prepare: + stage: prepare + script: + - docker build -t ${DOCKER_IMAGE_DEV} -f packaging/docker/Dockerfile.dev . + tags: + - linux + - shell + +build_job: + stage: build + before_script: + - mkdir -p build + script: + - npm install + - npm run build + image: ${DOCKER_IMAGE_DEV} + artifacts: + paths: + - build/ + expire_in: 1 week + tags: + - docker + +test_job: + stage: test + script: + - npm test + image: ${DOCKER_IMAGE_DEV} + dependencies: + - build_job + tags: + - docker + +deploy:docker: + stage: deploy + script: + - docker build -t ${DOCKER_IMAGE} -f packaging/docker/Dockerfile . + - docker tag villas/web:${DOCKER_TAG} villas/web:latest + - docker push villas/web:${DOCKER_TAG} + - docker push villas/web:latest + tags: + - shell + - linux + only: + refs: + - master diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..4f69051 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,236 @@ +# Contributing guidelines + +Thanks for taking the time to contribute to VILLASweb, every help is appreciated! + +> **Note:** This guidelines may seem much, but they just try to describe as good as possible to help with most common questions and problems. If you are unsure about anything feel free to **ask**. + +#### Table of contents + +[Quickstart](#quickstart) + * [How to report a bug or request a feature](#report-a-bug-or-request-a-feature) + * [Fix a bug](#fix-a-bug) + +[Issues](#issues) + * [Report bugs](#report-bugs) + * [Request features](#request-features) + * [Labels](#labels) + +[Development](#development) + * [Branches](#branches) + * [Style guidelines](#style-guidelines) + - [Code guidelines](#code-guidelines) + - [Comment guidelines](#comment-guidelines) + - [Git commit guidelines](#git-commit-guidelines) + * [Merge requests](#merge-requests) + * [Hotfix](#hotfix) + +## Quickstart + +### Report a bug or request a feature + +Simply create a new issue in gitlab with an appropriate title and description. For more information see [report bugs](#report-bugs). + +### Fix a bug + +Look at the list of bugs in the issue list. Pick the bug you want to work on, create a new branch with gitlab on that issue and start working in that branch. For more information see [Development](#development). + +## Issues + +All issues are tracked by the gitlab issue tracker. Every issue created will be read! + +### Report bugs + +Every issue related to a bug must follow this rules: + + - Add the `bug` label. + - Add the version, if known the exact commit. + - If existing, add log messages. + - If possible, add screenshots or animated GIFs of the bug. + +### Request features + +Every issue related to a feature or enhancement must follow this rules: + + - Add the `feature` or `enhancement` label. + - If possible, mockup pictures or animated GIFs to help understand the request. + +### Labels + +There are two types of labels: `type` and `state`. + +**Type labels** define what type the issue is about: + - **Bug:** The issue is related to an existing bug in the system. + + - **Feature:** The issue is requesting a **new** feature. + + - **Enhancement:** The issue is requesting change or improving an **existing** feature. + + - **Question:** The issue is asking a question about the system. + + - **Invalid:** The issue was declared invalid by a project administrator. + + - **Duplicate:** The reason the issue was created is already in the system, thus the issue is marked duplicated by a project administrator. + + - **Help wanted:** This label is optional to request help by others. + +**State labels** define in which state of development the issue is: + - **Backlog:** The issue was accepted by the project administrators but has not been worked on. + + - **Development:** The issue is in active development. + + - **Testing:** The development of the issue is (mostly) finished and it is tested to make sure everything works. + + - **Doc-and-review:** The development of the issue is finished but the documentation is still missing and the project administrator want to review it before merging it into main code. + +## Development + +Before starting to develop you want to have completed the [setup](README.md#quick-start) steps. + +### Branches + +This are the type of branches you will/might see in this project: + - **Master:** The *master* branch only contains **stable** release versions which must always be merged from the *develop* branch or *release-branches*. Each commit to this branch must contain a tag with at least the version. + + - **Develop:** The *develop* branch contains the current development version. Commits to this branch are prohibited (except [hotfixes](#hotfix)). See [merge requests](#merge-requests) on how to merge your working state into *develop*. + + - **Working branches:** *Working branches*, often also called *bug-fix/feature branches*, contain the active development state of features and bug-fixes. For each new feature or bug-fix you are working on, create a new *working branch*. To create new branch use gitlab's build-in feature to create a branch related to an issue. + + - **Legacy branches:** These branches must not be touched. The store legacy code from early development state. + + - **Release branches:** When preparing a *develop* version for release it is sometimes necessary to clean up before releasing it. Thus you first create a *release branch* of *develop*, do clean up on this branch and then release to *master*. + +For more information on branches and git usage see [Git workflow tutorial](https://www.atlassian.com/git/tutorials/comparing-workflows#gitflow-workflow). + +### Style guidelines + +#### Code guidelines + + - Use **camelcase** by default for everything with respect to upper-camelcase (e.g. class names start with an upper case letter). + + - File names are all in lower case and hyphen separated (e.g. sample-file.js). + + - End files with an empty line. + + - Use [ES6](http://es6-features.org/) (ES2015) features especially `const`, arrow functions and ES6 classes. + + - Use *self-explaining names* for variables, methods and classes. **Don't** shorten names like `let ArrStr` instead of `class ArrayString`. + + - Don't use `var` unless it can't be avoided. For more information see [const](http://es6-features.org/#Constants) and [let](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/let). + + - Use [ES6 arrow functions](http://es6-features.org/#ExpressionBodies) for callbacks. If only one variable is used, **don't** bracket it. + ```(javascript) + const increased = arr.map(v => v + 1); + const indexed = arr.map((v, index) => v += index); + ``` + + - Use [ES6 property shorthand](http://es6-features.org/#PropertyShorthand) whenever possible. + ```(javascript) + // Use + const obj = { x, y }; + + // Instead of + const obj = { x: x, y: y }; + ``` + + - Name *handler methods* `handleEventName` and *handler properties* `onEventName`. + ```(javascript) + + ``` + + - Use autobind for event handlers and callbacks. + ```(javascript) + handleClick = e => { + + } + ``` + + - Don't import react component (or similar) itself. Use `React.Component`. + ```(javascript) + import React from 'react'; + + class CustomComponent extends React.Component { + + } + ``` + + - Align and sort HTML properties properly. + ```(HTML) + // Do + + + + // Don't + + + ``` + +#### Comment guidelines + + - At the top of each file must be the following header: + ```(javascript) + /** + * File: + * Author: + * Date: + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + ``` + + - By default use `//` for comments. You may use `/* */` for uncommenting a block of code. + + - Comment as many as neccessary, but don't comment obvious code which is obviously self-explaining. + ```(javascript) + // self-explaining, don't do this: + // increase index + index++; + ``` + +#### Git commit guidelines + + - The first line should be a summary of the whole commit. The following lines should explain in detail what changed. + ``` + Add dynamic rendering + + Add queue for dynamic renderer + Change renderer to use queue for assets + Add render priority to asset properties + ``` + + - Use present tense in comments (add, fix, update, remove etc.). + +### Merge requests + +When finished working on a bug-fix or feature in your branch, create a merge request to merge your code into the *develop* branch. Before creating the request, make sure your changes meet the following requirements: + + - The *code*, *documentation* and *git commits* follow all [style guidelines](#style-guidelines). + + - All CI (Continues integration) tests, if existing, must succeed. + + - Add screenshots and animated GIFs when appropriated to show changes. + + - If the *develop* branch has newer commits the *working branch* **may** be rebased to catch-up these commits. + +### Hotfix + +Sometimes it is neccessary to patch an important, security relevant or system breaking bug as fast as possible. In this case it is allowed to commit directly in *master/develop*, as long as this commit is only relevant for the bug fix. It **must** follow all rules for [merge requests](#merge-requests). diff --git a/COPYING.md b/COPYING.md new file mode 100644 index 0000000..5f8b06f --- /dev/null +++ b/COPYING.md @@ -0,0 +1,675 @@ +### GNU GENERAL PUBLIC LICENSE + +Version 3, 29 June 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. + + +Everyone is permitted to copy and distribute verbatim copies of this +license document, but changing it is not allowed. + +### Preamble + +The GNU General Public License is a free, copyleft license for +software and other kinds of works. + +The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom +to share and change all versions of a program--to make sure it remains +free software for all its users. We, the Free Software Foundation, use +the GNU General Public License for most of our software; it applies +also to any other work released this way by its authors. You can apply +it to your programs, too. + +When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you +have certain responsibilities if you distribute copies of the +software, or if you modify it: responsibilities to respect the freedom +of others. + +For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + +Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + +Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the +manufacturer can do so. This is fundamentally incompatible with the +aim of protecting users' freedom to change the software. The +systematic pattern of such abuse occurs in the area of products for +individuals to use, which is precisely where it is most unacceptable. +Therefore, we have designed this version of the GPL to prohibit the +practice for those products. If such problems arise substantially in +other domains, we stand ready to extend this provision to those +domains in future versions of the GPL, as needed to protect the +freedom of users. + +Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish +to avoid the special danger that patents applied to a free program +could make it effectively proprietary. To prevent this, the GPL +assures that patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and +modification follow. + +### TERMS AND CONDITIONS + +#### 0. Definitions. + +"This License" refers to version 3 of the GNU General Public License. + +"Copyright" also means copyright-like laws that apply to other kinds +of works, such as semiconductor masks. + +"The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + +To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of +an exact copy. The resulting work is called a "modified version" of +the earlier work or a work "based on" the earlier work. + +A "covered work" means either the unmodified Program or a work based +on the Program. + +To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + +To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user +through a computer network, with no transfer of a copy, is not +conveying. + +An interactive user interface displays "Appropriate Legal Notices" to +the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + +#### 1. Source Code. + +The "source code" for a work means the preferred form of the work for +making modifications to it. "Object code" means any non-source form of +a work. + +A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + +The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + +The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can +regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same +work. + +#### 2. Basic Permissions. + +All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, +without conditions so long as your license otherwise remains in force. +You may convey covered works to others for the sole purpose of having +them make modifications exclusively for you, or provide you with +facilities for running those works, provided that you comply with the +terms of this License in conveying all material for which you do not +control copyright. Those thus making or running the covered works for +you must do so exclusively on your behalf, under your direction and +control, on terms that prohibit them from making any copies of your +copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the +conditions stated below. Sublicensing is not allowed; section 10 makes +it unnecessary. + +#### 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + +No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + +When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such +circumvention is effected by exercising rights under this License with +respect to the covered work, and you disclaim any intention to limit +operation or modification of the work as a means of enforcing, against +the work's users, your or third parties' legal rights to forbid +circumvention of technological measures. + +#### 4. Conveying Verbatim Copies. + +You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + +#### 5. Conveying Modified Source Versions. + +You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these +conditions: + +- a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. +- b) The work must carry prominent notices stating that it is + released under this License and any conditions added under + section 7. This requirement modifies the requirement in section 4 + to "keep intact all notices". +- c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. +- d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + +A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + +#### 6. Conveying Non-Source Forms. + +You may convey a covered work in object code form under the terms of +sections 4 and 5, provided that you also convey the machine-readable +Corresponding Source under the terms of this License, in one of these +ways: + +- a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. +- b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the Corresponding + Source from a network server at no charge. +- c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. +- d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. +- e) Convey the object code using peer-to-peer transmission, + provided you inform other peers where the object code and + Corresponding Source of the work are being offered to the general + public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + +A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, +family, or household purposes, or (2) anything designed or sold for +incorporation into a dwelling. In determining whether a product is a +consumer product, doubtful cases shall be resolved in favor of +coverage. For a particular product received by a particular user, +"normally used" refers to a typical or common use of that class of +product, regardless of the status of the particular user or of the way +in which the particular user actually uses, or expects or is expected +to use, the product. A product is a consumer product regardless of +whether the product has substantial commercial, industrial or +non-consumer uses, unless such uses represent the only significant +mode of use of the product. + +"Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to +install and execute modified versions of a covered work in that User +Product from a modified version of its Corresponding Source. The +information must suffice to ensure that the continued functioning of +the modified object code is in no case prevented or interfered with +solely because modification has been made. + +If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + +The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or +updates for a work that has been modified or installed by the +recipient, or for the User Product in which it has been modified or +installed. Access to a network may be denied when the modification +itself materially and adversely affects the operation of the network +or violates the rules and protocols for communication across the +network. + +Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + +#### 7. Additional Terms. + +"Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders +of that material) supplement the terms of this License with terms: + +- a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or +- b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or +- c) Prohibiting misrepresentation of the origin of that material, + or requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or +- d) Limiting the use for publicity purposes of names of licensors + or authors of the material; or +- e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or +- f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions + of it) with contractual assumptions of liability to the recipient, + for any liability that these contractual assumptions directly + impose on those licensors and authors. + +All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; the +above requirements apply either way. + +#### 8. Termination. + +You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + +However, if you cease all violation of this License, then your license +from a particular copyright holder is reinstated (a) provisionally, +unless and until the copyright holder explicitly and finally +terminates your license, and (b) permanently, if the copyright holder +fails to notify you of the violation by some reasonable means prior to +60 days after the cessation. + +Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + +Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + +#### 9. Acceptance Not Required for Having Copies. + +You are not required to accept this License in order to receive or run +a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + +#### 10. Automatic Licensing of Downstream Recipients. + +Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + +An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + +#### 11. Patents. + +A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + +A contributor's "essential patent claims" are all patent claims owned +or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + +In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + +If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + +A patent license is "discriminatory" if it does not include within the +scope of its coverage, prohibits the exercise of, or is conditioned on +the non-exercise of one or more of the rights that are specifically +granted under this License. You may not convey a covered work if you +are a party to an arrangement with a third party that is in the +business of distributing software, under which you make payment to the +third party based on the extent of your activity of conveying the +work, and under which the third party grants, to any of the parties +who would receive the covered work from you, a discriminatory patent +license (a) in connection with copies of the covered work conveyed by +you (or copies made from those copies), or (b) primarily for and in +connection with specific products or compilations that contain the +covered work, unless you entered into that arrangement, or that patent +license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + +#### 12. No Surrender of Others' Freedom. + +If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under +this License and any other pertinent obligations, then as a +consequence you may not convey it at all. For example, if you agree to +terms that obligate you to collect a royalty for further conveying +from those to whom you convey the Program, the only way you could +satisfy both those terms and this License would be to refrain entirely +from conveying the Program. + +#### 13. Use with the GNU Affero General Public License. + +Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + +#### 14. Revised Versions of this License. + +The Free Software Foundation may publish revised and/or new versions +of the GNU General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in +detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies that a certain numbered version of the GNU General Public +License "or any later version" applies to it, you have the option of +following the terms and conditions either of that numbered version or +of any later version published by the Free Software Foundation. If the +Program does not specify a version number of the GNU General Public +License, you may choose any version ever published by the Free +Software Foundation. + +If the Program specifies that a proxy can decide which future versions +of the GNU General Public License can be used, that proxy's public +statement of acceptance of a version permanently authorizes you to +choose that version for the Program. + +Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + +#### 15. Disclaimer of Warranty. + +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT +WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND +PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE +DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR +CORRECTION. + +#### 16. Limitation of Liability. + +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR +CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES +ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT +NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR +LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM +TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER +PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +#### 17. Interpretation of Sections 15 and 16. + +If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + +### How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these +terms. + +To do so, attach the following notices to the program. It is safest to +attach them to the start of each source file to most effectively state +the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper +mail. + +If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands \`show w' and \`show c' should show the +appropriate parts of the General Public License. Of course, your +program's commands might be different; for a GUI interface, you would +use an "about box". + +You should also get your employer (if you work as a programmer) or +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. For more information on this, and how to apply and follow +the GNU GPL, see . + +The GNU General Public License does not permit incorporating your +program into proprietary programs. If your program is a subroutine +library, you may consider it more useful to permit linking proprietary +applications with the library. If this is what you want to do, use the +GNU Lesser General Public License instead of this License. But first, +please read . diff --git a/Dockerfile b/Dockerfile new file mode 120000 index 0000000..30004e8 --- /dev/null +++ b/Dockerfile @@ -0,0 +1 @@ +packaging/docker/Dockerfile \ No newline at end of file diff --git a/REACT.md b/REACT.md new file mode 100644 index 0000000..e290b93 --- /dev/null +++ b/REACT.md @@ -0,0 +1,1572 @@ +This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app). + +Below you will find some information on how to perform common tasks.
+You can find the most recent version of this guide [here](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md). + +## Table of Contents + +- [Updating to New Releases](#updating-to-new-releases) +- [Sending Feedback](#sending-feedback) +- [Folder Structure](#folder-structure) +- [Available Scripts](#available-scripts) + - [npm start](#npm-start) + - [npm test](#npm-test) + - [npm run build](#npm-run-build) + - [npm run eject](#npm-run-eject) +- [Supported Language Features and Polyfills](#supported-language-features-and-polyfills) +- [Syntax Highlighting in the Editor](#syntax-highlighting-in-the-editor) +- [Displaying Lint Output in the Editor](#displaying-lint-output-in-the-editor) +- [Debugging in the Editor](#debugging-in-the-editor) +- [Changing the Page ``](#changing-the-page-title) +- [Installing a Dependency](#installing-a-dependency) +- [Importing a Component](#importing-a-component) +- [Adding a Stylesheet](#adding-a-stylesheet) +- [Post-Processing CSS](#post-processing-css) +- [Adding a CSS Preprocessor (Sass, Less etc.)](#adding-a-css-preprocessor-sass-less-etc) +- [Adding Images and Fonts](#adding-images-and-fonts) +- [Using the `public` Folder](#using-the-public-folder) + - [Changing the HTML](#changing-the-html) + - [Adding Assets Outside of the Module System](#adding-assets-outside-of-the-module-system) + - [When to Use the `public` Folder](#when-to-use-the-public-folder) +- [Using Global Variables](#using-global-variables) +- [Adding Bootstrap](#adding-bootstrap) + - [Using a Custom Theme](#using-a-custom-theme) +- [Adding Flow](#adding-flow) +- [Adding Custom Environment Variables](#adding-custom-environment-variables) + - [Referencing Environment Variables in the HTML](#referencing-environment-variables-in-the-html) + - [Adding Temporary Environment Variables In Your Shell](#adding-temporary-environment-variables-in-your-shell) + - [Adding Development Environment Variables In `.env`](#adding-development-environment-variables-in-env) +- [Can I Use Decorators?](#can-i-use-decorators) +- [Integrating with an API Backend](#integrating-with-an-api-backend) + - [Node](#node) + - [Ruby on Rails](#ruby-on-rails) +- [Proxying API Requests in Development](#proxying-api-requests-in-development) +- [Using HTTPS in Development](#using-https-in-development) +- [Generating Dynamic `<meta>` Tags on the Server](#generating-dynamic-meta-tags-on-the-server) +- [Pre-Rendering into Static HTML Files](#pre-rendering-into-static-html-files) +- [Injecting Data from the Server into the Page](#injecting-data-from-the-server-into-the-page) +- [Running Tests](#running-tests) + - [Filename Conventions](#filename-conventions) + - [Command Line Interface](#command-line-interface) + - [Version Control Integration](#version-control-integration) + - [Writing Tests](#writing-tests) + - [Testing Components](#testing-components) + - [Using Third Party Assertion Libraries](#using-third-party-assertion-libraries) + - [Initializing Test Environment](#initializing-test-environment) + - [Focusing and Excluding Tests](#focusing-and-excluding-tests) + - [Coverage Reporting](#coverage-reporting) + - [Continuous Integration](#continuous-integration) + - [Disabling jsdom](#disabling-jsdom) + - [Snapshot Testing](#snapshot-testing) + - [Editor Integration](#editor-integration) +- [Developing Components in Isolation](#developing-components-in-isolation) +- [Making a Progressive Web App](#making-a-progressive-web-app) +- [Deployment](#deployment) + - [Serving Apps with Client-Side Routing](#serving-apps-with-client-side-routing) + - [Building for Relative Paths](#building-for-relative-paths) + - [Azure](#azure) + - [Firebase](#firebase) + - [GitHub Pages](#github-pages) + - [Heroku](#heroku) + - [Modulus](#modulus) + - [Netlify](#netlify) + - [Now](#now) + - [S3 and CloudFront](#s3-and-cloudfront) + - [Surge](#surge) +- [Advanced Configuration](#advanced-configuration) +- [Troubleshooting](#troubleshooting) + - [`npm start` doesn’t detect changes](#npm-start-doesnt-detect-changes) + - [`npm test` hangs on macOS Sierra](#npm-test-hangs-on-macos-sierra) + - [`npm run build` silently fails](#npm-run-build-silently-fails) + - [`npm run build` fails on Heroku](#npm-run-build-fails-on-heroku) +- [Something Missing?](#something-missing) + +## Updating to New Releases + +Create React App is divided into two packages: + +* `create-react-app` is a global command-line utility that you use to create new projects. +* `react-scripts` is a development dependency in the generated projects (including this one). + +You almost never need to update `create-react-app` itself: it delegates all the setup to `react-scripts`. + +When you run `create-react-app`, it always creates the project with the latest version of `react-scripts` so you’ll get all the new features and improvements in newly created apps automatically. + +To update an existing project to a new version of `react-scripts`, [open the changelog](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md), find the version you’re currently on (check `package.json` in this folder if you’re not sure), and apply the migration instructions for the newer versions. + +In most cases bumping the `react-scripts` version in `package.json` and running `npm install` in this folder should be enough, but it’s good to consult the [changelog](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md) for potential breaking changes. + +We commit to keeping the breaking changes minimal so you can upgrade `react-scripts` painlessly. + +## Sending Feedback + +We are always open to [your feedback](https://github.com/facebookincubator/create-react-app/issues). + +## Folder Structure + +After creation, your project should look like this: + +``` +my-app/ + README.md + node_modules/ + package.json + public/ + index.html + favicon.ico + src/ + App.css + App.js + App.test.js + index.css + index.js + logo.svg +``` + +For the project to build, **these files must exist with exact filenames**: + +* `public/index.html` is the page template; +* `src/index.js` is the JavaScript entry point. + +You can delete or rename the other files. + +You may create subdirectories inside `src`. For faster rebuilds, only files inside `src` are processed by Webpack.<br> +You need to **put any JS and CSS files inside `src`**, or Webpack won’t see them. + +Only files inside `public` can be used from `public/index.html`.<br> +Read instructions below for using assets from JavaScript and HTML. + +You can, however, create more top-level directories.<br> +They will not be included in the production build so you can use them for things like documentation. + +## Available Scripts + +In the project directory, you can run: + +### `npm start` + +Runs the app in the development mode.<br> +Open [http://localhost:3000](http://localhost:3000) to view it in the browser. + +The page will reload if you make edits.<br> +You will also see any lint errors in the console. + +### `npm test` + +Launches the test runner in the interactive watch mode.<br> +See the section about [running tests](#running-tests) for more information. + +### `npm run build` + +Builds the app for production to the `build` folder.<br> +It correctly bundles React in production mode and optimizes the build for the best performance. + +The build is minified and the filenames include the hashes.<br> +Your app is ready to be deployed! + +See the section about [deployment](#deployment) for more information. + +### `npm run eject` + +**Note: this is a one-way operation. Once you `eject`, you can’t go back!** + +If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. + +Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. + +You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. + +## Supported Language Features and Polyfills + +This project supports a superset of the latest JavaScript standard.<br> +In addition to [ES6](https://github.com/lukehoban/es6features) syntax features, it also supports: + +* [Exponentiation Operator](https://github.com/rwaldron/exponentiation-operator) (ES2016). +* [Async/await](https://github.com/tc39/ecmascript-asyncawait) (ES2017). +* [Object Rest/Spread Properties](https://github.com/sebmarkbage/ecmascript-rest-spread) (stage 3 proposal). +* [Class Fields and Static Properties](https://github.com/tc39/proposal-class-public-fields) (stage 2 proposal). +* [JSX](https://facebook.github.io/react/docs/introducing-jsx.html) and [Flow](https://flowtype.org/) syntax. + +Learn more about [different proposal stages](https://babeljs.io/docs/plugins/#presets-stage-x-experimental-presets-). + +While we recommend to use experimental proposals with some caution, Facebook heavily uses these features in the product code, so we intend to provide [codemods](https://medium.com/@cpojer/effective-javascript-codemods-5a6686bb46fb) if any of these proposals change in the future. + +Note that **the project only includes a few ES6 [polyfills](https://en.wikipedia.org/wiki/Polyfill)**: + +* [`Object.assign()`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) via [`object-assign`](https://github.com/sindresorhus/object-assign). +* [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) via [`promise`](https://github.com/then/promise). +* [`fetch()`](https://developer.mozilla.org/en/docs/Web/API/Fetch_API) via [`whatwg-fetch`](https://github.com/github/fetch). + +If you use any other ES6+ features that need **runtime support** (such as `Array.from()` or `Symbol`), make sure you are including the appropriate polyfills manually, or that the browsers you are targeting already support them. + +## Syntax Highlighting in the Editor + +To configure the syntax highlighting in your favorite text editor, head to the [relevant Babel documentation page](https://babeljs.io/docs/editors) and follow the instructions. Some of the most popular editors are covered. + +## Displaying Lint Output in the Editor + +>Note: this feature is available with `react-scripts@0.2.0` and higher. + +Some editors, including Sublime Text, Atom, and Visual Studio Code, provide plugins for ESLint. + +They are not required for linting. You should see the linter output right in your terminal as well as the browser console. However, if you prefer the lint results to appear right in your editor, there are some extra steps you can do. + +You would need to install an ESLint plugin for your editor first. + +>**A note for Atom `linter-eslint` users** + +>If you are using the Atom `linter-eslint` plugin, make sure that **Use global ESLint installation** option is checked: + +><img src="http://i.imgur.com/yVNNHJM.png" width="300"> + + +>**For Visual Studio Code users** + +>VS Code ESLint plugin automatically detects Create React App's configuration file. So you do not need to create `eslintrc.json` at the root directory, except when you want to add your own rules. In that case, you should include CRA's config by adding this line: + +>```js +{ + // ... + "extends": "react-app" +} +``` + +Then add this block to the `package.json` file of your project: + +```js +{ + // ... + "eslintConfig": { + "extends": "react-app" + } +} +``` + +Finally, you will need to install some packages *globally*: + +```sh +npm install -g eslint-config-react-app@0.3.0 eslint@3.8.1 babel-eslint@7.0.0 eslint-plugin-react@6.4.1 eslint-plugin-import@2.0.1 eslint-plugin-jsx-a11y@2.2.3 eslint-plugin-flowtype@2.21.0 +``` + +We recognize that this is suboptimal, but it is currently required due to the way we hide the ESLint dependency. The ESLint team is already [working on a solution to this](https://github.com/eslint/eslint/issues/3458) so this may become unnecessary in a couple of months. + +## Debugging in the Editor + +**This feature is currently only supported by [Visual Studio Code](https://code.visualstudio.com) editor.** + +Visual Studio Code supports live-editing and debugging out of the box with Create React App. This enables you as a developer to write and debug your React code without leaving the editor, and most importantly it enables you to have a continuous development workflow, where context switching is minimal, as you don’t have to switch between tools. + +You would need to have the latest version of [VS Code](https://code.visualstudio.com) and VS Code [Chrome Debugger Extension](https://marketplace.visualstudio.com/items?itemName=msjsdiag.debugger-for-chrome) installed. + +Then add the block below to your `launch.json` file and put it inside the `.vscode` folder in your app’s root directory. + +```json +{ + "version": "0.2.0", + "configurations": [{ + "name": "Chrome", + "type": "chrome", + "request": "launch", + "url": "http://localhost:3000", + "webRoot": "${workspaceRoot}/src", + "userDataDir": "${workspaceRoot}/.vscode/chrome", + "sourceMapPathOverrides": { + "webpack:///src/*": "${webRoot}/*" + } + }] +} +``` + +Start your app by running `npm start`, and start debugging in VS Code by pressing `F5` or by clicking the green debug icon. You can now write code, set breakpoints, make changes to the code, and debug your newly modified code—all from your editor. + +## Changing the Page `<title>` + +You can find the source HTML file in the `public` folder of the generated project. You may edit the `<title>` tag in it to change the title from “React App” to anything else. + +Note that normally you wouldn’t edit files in the `public` folder very often. For example, [adding a stylesheet](#adding-a-stylesheet) is done without touching the HTML. + +If you need to dynamically update the page title based on the content, you can use the browser [`document.title`](https://developer.mozilla.org/en-US/docs/Web/API/Document/title) API. For more complex scenarios when you want to change the title from React components, you can use [React Helmet](https://github.com/nfl/react-helmet), a third party library. + +If you use a custom server for your app in production and want to modify the title before it gets sent to the browser, you can follow advice in [this section](#generating-dynamic-meta-tags-on-the-server). Alternatively, you can pre-build each page as a static HTML file which then loads the JavaScript bundle, which is covered [here](#pre-rendering-into-static-html-files). + +## Installing a Dependency + +The generated project includes React and ReactDOM as dependencies. It also includes a set of scripts used by Create React App as a development dependency. You may install other dependencies (for example, React Router) with `npm`: + +``` +npm install --save <library-name> +``` + +## Importing a Component + +This project setup supports ES6 modules thanks to Babel.<br> +While you can still use `require()` and `module.exports`, we encourage you to use [`import` and `export`](http://exploringjs.com/es6/ch_modules.html) instead. + +For example: + +### `Button.js` + +```js +import React, { Component } from 'react'; + +class Button extends Component { + render() { + // ... + } +} + +export default Button; // Don’t forget to use export default! +``` + +### `DangerButton.js` + + +```js +import React, { Component } from 'react'; +import Button from './Button'; // Import a component from another file + +class DangerButton extends Component { + render() { + return <Button color="red" />; + } +} + +export default DangerButton; +``` + +Be aware of the [difference between default and named exports](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281). It is a common source of mistakes. + +We suggest that you stick to using default imports and exports when a module only exports a single thing (for example, a component). That’s what you get when you use `export default Button` and `import Button from './Button'`. + +Named exports are useful for utility modules that export several functions. A module may have at most one default export and as many named exports as you like. + +Learn more about ES6 modules: + +* [When to use the curly braces?](http://stackoverflow.com/questions/36795819/react-native-es-6-when-should-i-use-curly-braces-for-import/36796281#36796281) +* [Exploring ES6: Modules](http://exploringjs.com/es6/ch_modules.html) +* [Understanding ES6: Modules](https://leanpub.com/understandinges6/read#leanpub-auto-encapsulating-code-with-modules) + +## Adding a Stylesheet + +This project setup uses [Webpack](https://webpack.github.io/) for handling all assets. Webpack offers a custom way of “extending” the concept of `import` beyond JavaScript. To express that a JavaScript file depends on a CSS file, you need to **import the CSS from the JavaScript file**: + +### `Button.css` + +```css +.Button { + padding: 20px; +} +``` + +### `Button.js` + +```js +import React, { Component } from 'react'; +import './Button.css'; // Tell Webpack that Button.js uses these styles + +class Button extends Component { + render() { + // You can use them as regular CSS styles + return <div className="Button" />; + } +} +``` + +**This is not required for React** but many people find this feature convenient. You can read about the benefits of this approach [here](https://medium.com/seek-ui-engineering/block-element-modifying-your-javascript-components-d7f99fcab52b). However you should be aware that this makes your code less portable to other build tools and environments than Webpack. + +In development, expressing dependencies this way allows your styles to be reloaded on the fly as you edit them. In production, all CSS files will be concatenated into a single minified `.css` file in the build output. + +If you are concerned about using Webpack-specific semantics, you can put all your CSS right into `src/index.css`. It would still be imported from `src/index.js`, but you could always remove that import if you later migrate to a different build tool. + +## Post-Processing CSS + +This project setup minifies your CSS and adds vendor prefixes to it automatically through [Autoprefixer](https://github.com/postcss/autoprefixer) so you don’t need to worry about it. + +For example, this: + +```css +.App { + display: flex; + flex-direction: row; + align-items: center; +} +``` + +becomes this: + +```css +.App { + display: -webkit-box; + display: -ms-flexbox; + display: flex; + -webkit-box-orient: horizontal; + -webkit-box-direction: normal; + -ms-flex-direction: row; + flex-direction: row; + -webkit-box-align: center; + -ms-flex-align: center; + align-items: center; +} +``` + +If you need to disable autoprefixing for some reason, [follow this section](https://github.com/postcss/autoprefixer#disabling). + +## Adding a CSS Preprocessor (Sass, Less etc.) + +Generally, we recommend that you don’t reuse the same CSS classes across different components. For example, instead of using a `.Button` CSS class in `<AcceptButton>` and `<RejectButton>` components, we recommend creating a `<Button>` component with its own `.Button` styles, that both `<AcceptButton>` and `<RejectButton>` can render (but [not inherit](https://facebook.github.io/react/docs/composition-vs-inheritance.html)). + +Following this rule often makes CSS preprocessors less useful, as features like mixins and nesting are replaced by component composition. You can, however, integrate a CSS preprocessor if you find it valuable. In this walkthrough, we will be using Sass, but you can also use Less, or another alternative. + +First, let’s install the command-line interface for Sass: + +``` +npm install node-sass --save-dev +``` + +Then in `package.json`, add the following lines to `scripts`: + +```diff + "scripts": { ++ "build-css": "node-sass src/ -o src/", ++ "watch-css": "npm run build-css && node-sass src/ -o src/ --watch", + "start": "react-scripts start", + "build": "react-scripts build", + "test": "react-scripts test --env=jsdom", +``` + +>Note: To use a different preprocessor, replace `build-css` and `watch-css` commands according to your preprocessor’s documentation. + +Now you can rename `src/App.css` to `src/App.scss` and run `npm run watch-css`. The watcher will find every Sass file in `src` subdirectories, and create a corresponding CSS file next to it, in our case overwriting `src/App.css`. Since `src/App.js` still imports `src/App.css`, the styles become a part of your application. You can now edit `src/App.scss`, and `src/App.css` will be regenerated. + +To share variables between Sass files, you can use Sass imports. For example, `src/App.scss` and other component style files could include `@import "./shared.scss";` with variable definitions. + +At this point you might want to remove all CSS files from the source control, and add `src/**/*.css` to your `.gitignore` file. It is generally a good practice to keep the build products outside of the source control. + +As a final step, you may find it convenient to run `watch-css` automatically with `npm start`, and run `build-css` as a part of `npm run build`. You can use the `&&` operator to execute two scripts sequentially. However, there is no cross-platform way to run two scripts in parallel, so we will install a package for this: + +``` +npm install --save-dev npm-run-all +``` + +Then we can change `start` and `build` scripts to include the CSS preprocessor commands: + +```diff + "scripts": { + "build-css": "node-sass src/ -o src/", + "watch-css": "npm run build-css && node-sass src/ -o src/ --watch --recursive", +- "start": "react-scripts start", +- "build": "react-scripts build", ++ "start-js": "react-scripts start", ++ "start": "npm-run-all -p watch-css start-js", ++ "build": "npm run build-css && react-scripts build", + "test": "react-scripts test --env=jsdom", + "eject": "react-scripts eject" + } +``` + +Now running `npm start` and `npm run build` also builds Sass files. Note that `node-sass` seems to have an [issue recognizing newly created files on some systems](https://github.com/sass/node-sass/issues/1891) so you might need to restart the watcher when you create a file until it’s resolved. + +## Adding Images and Fonts + +With Webpack, using static assets like images and fonts works similarly to CSS. + +You can **`import` an image right in a JavaScript module**. This tells Webpack to include that image in the bundle. Unlike CSS imports, importing an image or a font gives you a string value. This value is the final image path you can reference in your code. + +Here is an example: + +```js +import React from 'react'; +import logo from './logo.png'; // Tell Webpack this JS file uses this image + +console.log(logo); // /logo.84287d09.png + +function Header() { + // Import result is the URL of your image + return <img src={logo} alt="Logo" />; +} + +export default Header; +``` + +This ensures that when the project is built, Webpack will correctly move the images into the build folder, and provide us with correct paths. + +This works in CSS too: + +```css +.Logo { + background-image: url(./logo.png); +} +``` + +Webpack finds all relative module references in CSS (they start with `./`) and replaces them with the final paths from the compiled bundle. If you make a typo or accidentally delete an important file, you will see a compilation error, just like when you import a non-existent JavaScript module. The final filenames in the compiled bundle are generated by Webpack from content hashes. If the file content changes in the future, Webpack will give it a different name in production so you don’t need to worry about long-term caching of assets. + +Please be advised that this is also a custom feature of Webpack. + +**It is not required for React** but many people enjoy it (and React Native uses a similar mechanism for images).<br> +An alternative way of handling static assets is described in the next section. + +## Using the `public` Folder + +>Note: this feature is available with `react-scripts@0.5.0` and higher. + +### Changing the HTML + +The `public` folder contains the HTML file so you can tweak it, for example, to [set the page title](#changing-the-page-title). +The `<script>` tag with the compiled code will be added to it automatically during the build process. + +### Adding Assets Outside of the Module System + +You can also add other assets to the `public` folder. + +Note that we normally encourage you to `import` assets in JavaScript files instead. +For example, see the sections on [adding a stylesheet](#adding-a-stylesheet) and [adding images and fonts](#adding-images-and-fonts). +This mechanism provides a number of benefits: + +* Scripts and stylesheets get minified and bundled together to avoid extra network requests. +* Missing files cause compilation errors instead of 404 errors for your users. +* Result filenames include content hashes so you don’t need to worry about browsers caching their old versions. + +However there is an **escape hatch** that you can use to add an asset outside of the module system. + +If you put a file into the `public` folder, it will **not** be processed by Webpack. Instead it will be copied into the build folder untouched. To reference assets in the `public` folder, you need to use a special variable called `PUBLIC_URL`. + +Inside `index.html`, you can use it like this: + +```html +<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> +``` + +Only files inside the `public` folder will be accessible by `%PUBLIC_URL%` prefix. If you need to use a file from `src` or `node_modules`, you’ll have to copy it there to explicitly specify your intention to make this file a part of the build. + +When you run `npm run build`, Create React App will substitute `%PUBLIC_URL%` with a correct absolute path so your project works even if you use client-side routing or host it at a non-root URL. + +In JavaScript code, you can use `process.env.PUBLIC_URL` for similar purposes: + +```js +render() { + // Note: this is an escape hatch and should be used sparingly! + // Normally we recommend using `import` for getting asset URLs + // as described in “Adding Images and Fonts” above this section. + return <img src={process.env.PUBLIC_URL + '/img/logo.png'} />; +} +``` + +Keep in mind the downsides of this approach: + +* None of the files in `public` folder get post-processed or minified. +* Missing files will not be called at compilation time, and will cause 404 errors for your users. +* Result filenames won’t include content hashes so you’ll need to add query arguments or rename them every time they change. + +### When to Use the `public` Folder + +Normally we recommend importing [stylesheets](#adding-a-stylesheet), [images, and fonts](#adding-images-and-fonts) from JavaScript. +The `public` folder is useful as a workaround for a number of less common cases: + +* You need a file with a specific name in the build output, such as [`manifest.webmanifest`](https://developer.mozilla.org/en-US/docs/Web/Manifest). +* You have thousands of images and need to dynamically reference their paths. +* You want to include a small script like [`pace.js`](http://github.hubspot.com/pace/docs/welcome/) outside of the bundled code. +* Some library may be incompatible with Webpack and you have no other option but to include it as a `<script>` tag. + +Note that if you add a `<script>` that declares global variables, you also need to read the next section on using them. + +## Using Global Variables + +When you include a script in the HTML file that defines global variables and try to use one of these variables in the code, the linter will complain because it cannot see the definition of the variable. + +You can avoid this by reading the global variable explicitly from the `window` object, for example: + +```js +const $ = window.$; +``` + +This makes it obvious you are using a global variable intentionally rather than because of a typo. + +Alternatively, you can force the linter to ignore any line by adding `// eslint-disable-line` after it. + +## Adding Bootstrap + +You don’t have to use [React Bootstrap](https://react-bootstrap.github.io) together with React but it is a popular library for integrating Bootstrap with React apps. If you need it, you can integrate it with Create React App by following these steps: + +Install React Bootstrap and Bootstrap from npm. React Bootstrap does not include Bootstrap CSS so this needs to be installed as well: + +``` +npm install react-bootstrap --save +npm install bootstrap@3 --save +``` + +Import Bootstrap CSS and optionally Bootstrap theme CSS in the beginning of your ```src/index.js``` file: + +```js +import 'bootstrap/dist/css/bootstrap.css'; +import 'bootstrap/dist/css/bootstrap-theme.css'; +// Put any other imports below so that CSS from your +// components takes precedence over default styles. +``` + +Import required React Bootstrap components within ```src/App.js``` file or your custom component files: + +```js +import { Navbar, Jumbotron, Button } from 'react-bootstrap'; +``` + +Now you are ready to use the imported React Bootstrap components within your component hierarchy defined in the render method. Here is an example [`App.js`](https://gist.githubusercontent.com/gaearon/85d8c067f6af1e56277c82d19fd4da7b/raw/6158dd991b67284e9fc8d70b9d973efe87659d72/App.js) redone using React Bootstrap. + +### Using a Custom Theme + +Sometimes you might need to tweak the visual styles of Bootstrap (or equivalent package).<br> +We suggest the following approach: + +* Create a new package that depends on the package you wish to customize, e.g. Bootstrap. +* Add the necessary build steps to tweak the theme, and publish your package on npm. +* Install your own theme npm package as a dependency of your app. + +Here is an example of adding a [customized Bootstrap](https://medium.com/@tacomanator/customizing-create-react-app-aa9ffb88165) that follows these steps. + +## Adding Flow + +Flow is a static type checker that helps you write code with fewer bugs. Check out this [introduction to using static types in JavaScript](https://medium.com/@preethikasireddy/why-use-static-types-in-javascript-part-1-8382da1e0adb) if you are new to this concept. + +Recent versions of [Flow](http://flowtype.org/) work with Create React App projects out of the box. + +To add Flow to a Create React App project, follow these steps: + +1. Run `npm install --save-dev flow-bin`. +2. Add `"flow": "flow"` to the `scripts` section of your `package.json`. +3. Run `npm run flow -- init` to create a [`.flowconfig` file](https://flowtype.org/docs/advanced-configuration.html) in the root directory. +4. Add `// @flow` to any files you want to type check (for example, to `src/App.js`). + +Now you can run `npm run flow` to check the files for type errors. +You can optionally use an IDE like [Nuclide](https://nuclide.io/docs/languages/flow/) for a better integrated experience. +In the future we plan to integrate it into Create React App even more closely. + +To learn more about Flow, check out [its documentation](https://flowtype.org/). + +## Adding Custom Environment Variables + +>Note: this feature is available with `react-scripts@0.2.3` and higher. + +Your project can consume variables declared in your environment as if they were declared locally in your JS files. By +default you will have `NODE_ENV` defined for you, and any other environment variables starting with +`REACT_APP_`. + +**The environment variables are embedded during the build time**. Since Create React App produces a static HTML/CSS/JS bundle, it can’t possibly read them at runtime. To read them at runtime, you would need to load HTML into memory on the server and replace placeholders in runtime, just like [described here](#injecting-data-from-the-server-into-the-page). Alternatively you can rebuild the app on the server anytime you change them. + +>Note: You must create custom environment variables beginning with `REACT_APP_`. Any other variables except `NODE_ENV` will be ignored to avoid accidentally [exposing a private key on the machine that could have the same name](https://github.com/facebookincubator/create-react-app/issues/865#issuecomment-252199527). Changing any environment variables will require you to restart the development server if it is running. + +These environment variables will be defined for you on `process.env`. For example, having an environment +variable named `REACT_APP_SECRET_CODE` will be exposed in your JS as `process.env.REACT_APP_SECRET_CODE`. + +There is also a special built-in environment variable called `NODE_ENV`. You can read it from `process.env.NODE_ENV`. When you run `npm start`, it is always equal to `'development'`, when you run `npm test` it is always equal to `'test'`, and when you run `npm run build` to make a production bundle, it is always equal to `'production'`. **You cannot override `NODE_ENV` manually.** This prevents developers from accidentally deploying a slow development build to production. + +These environment variables can be useful for displaying information conditionally based on where the project is +deployed or consuming sensitive data that lives outside of version control. + +First, you need to have environment variables defined. For example, let’s say you wanted to consume a secret defined +in the environment inside a `<form>`: + +```jsx +render() { + return ( + <div> + <small>You are running this application in <b>{process.env.NODE_ENV}</b> mode.</small> + <form> + <input type="hidden" defaultValue={process.env.REACT_APP_SECRET_CODE} /> + </form> + </div> + ); +} +``` + +During the build, `process.env.REACT_APP_SECRET_CODE` will be replaced with the current value of the `REACT_APP_SECRET_CODE` environment variable. Remember that the `NODE_ENV` variable will be set for you automatically. + +When you load the app in the browser and inspect the `<input>`, you will see its value set to `abcdef`, and the bold text will show the environment provided when using `npm start`: + +```html +<div> + <small>You are running this application in <b>development</b> mode.</small> + <form> + <input type="hidden" value="abcdef" /> + </form> +</div> +``` + +The above form is looking for a variable called `REACT_APP_SECRET_CODE` from the environment. In order to consume this +value, we need to have it defined in the environment. This can be done using two ways: either in your shell or in +a `.env` file. Both of these ways are described in the next few sections. + +Having access to the `NODE_ENV` is also useful for performing actions conditionally: + +```js +if (process.env.NODE_ENV !== 'production') { + analytics.disable(); +} +``` + +When you compile the app with `npm run build`, the minification step will strip out this condition, and the resulting bundle will be smaller. + +### Referencing Environment Variables in the HTML + +>Note: this feature is available with `react-scripts@0.9.0` and higher. + +You can also access the environment variables starting with `REACT_APP_` in the `public/index.html`. For example: + +```html +<title>%REACT_APP_WEBSITE_NAME% +``` + +Note that the caveats from the above section apply: + +* Apart from a few built-in variables (`NODE_ENV` and `PUBLIC_URL`), variable names must start with `REACT_APP_` to work. +* The environment variables are injected at build time. If you need to inject them at runtime, [follow this approach instead](#generating-dynamic-meta-tags-on-the-server). + +### Adding Temporary Environment Variables In Your Shell + +Defining environment variables can vary between OSes. It’s also important to know that this manner is temporary for the +life of the shell session. + +#### Windows (cmd.exe) + +```cmd +set REACT_APP_SECRET_CODE=abcdef&&npm start +``` + +(Note: the lack of whitespace is intentional.) + +#### Linux, macOS (Bash) + +```bash +REACT_APP_SECRET_CODE=abcdef npm start +``` + +### Adding Development Environment Variables In `.env` + +>Note: this feature is available with `react-scripts@0.5.0` and higher. + +To define permanent environment variables, create a file called `.env` in the root of your project: + +``` +REACT_APP_SECRET_CODE=abcdef +``` + +These variables will act as the defaults if the machine does not explicitly set them.
+Please refer to the [dotenv documentation](https://github.com/motdotla/dotenv) for more details. + +>Note: If you are defining environment variables for development, your CI and/or hosting platform will most likely need +these defined as well. Consult their documentation how to do this. For example, see the documentation for [Travis CI](https://docs.travis-ci.com/user/environment-variables/) or [Heroku](https://devcenter.heroku.com/articles/config-vars). + +## Can I Use Decorators? + +Many popular libraries use [decorators](https://medium.com/google-developers/exploring-es7-decorators-76ecb65fb841) in their documentation.
+Create React App doesn’t support decorator syntax at the moment because: + +* It is an experimental proposal and is subject to change. +* The current specification version is not officially supported by Babel. +* If the specification changes, we won’t be able to write a codemod because we don’t use them internally at Facebook. + +However in many cases you can rewrite decorator-based code without decorators just as fine.
+Please refer to these two threads for reference: + +* [#214](https://github.com/facebookincubator/create-react-app/issues/214) +* [#411](https://github.com/facebookincubator/create-react-app/issues/411) + +Create React App will add decorator support when the specification advances to a stable stage. + +## Integrating with an API Backend + +These tutorials will help you to integrate your app with an API backend running on another port, +using `fetch()` to access it. + +### Node +Check out [this tutorial](https://www.fullstackreact.com/articles/using-create-react-app-with-a-server/). +You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo). + +### Ruby on Rails + +Check out [this tutorial](https://www.fullstackreact.com/articles/how-to-get-create-react-app-to-work-with-your-rails-api/). +You can find the companion GitHub repository [here](https://github.com/fullstackreact/food-lookup-demo-rails). + +## Proxying API Requests in Development + +>Note: this feature is available with `react-scripts@0.2.3` and higher. + +People often serve the front-end React app from the same host and port as their backend implementation.
+For example, a production setup might look like this after the app is deployed: + +``` +/ - static server returns index.html with React app +/todos - static server returns index.html with React app +/api/todos - server handles any /api/* requests using the backend implementation +``` + +Such setup is **not** required. However, if you **do** have a setup like this, it is convenient to write requests like `fetch('/api/todos')` without worrying about redirecting them to another host or port during development. + +To tell the development server to proxy any unknown requests to your API server in development, add a `proxy` field to your `package.json`, for example: + +```js + "proxy": "http://localhost:4000", +``` + +This way, when you `fetch('/api/todos')` in development, the development server will recognize that it’s not a static asset, and will proxy your request to `http://localhost:4000/api/todos` as a fallback. The development server will only attempt to send requests without a `text/html` accept header to the proxy. + +Conveniently, this avoids [CORS issues](http://stackoverflow.com/questions/21854516/understanding-ajax-cors-and-security-considerations) and error messages like this in development: + +``` +Fetch API cannot load http://localhost:4000/api/todos. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. +``` + +Keep in mind that `proxy` only has effect in development (with `npm start`), and it is up to you to ensure that URLs like `/api/todos` point to the right thing in production. You don’t have to use the `/api` prefix. Any unrecognized request without a `text/html` accept header will be redirected to the specified `proxy`. + +The `proxy` option supports HTTP, HTTPS and WebSocket connections.
+If the `proxy` option is **not** flexible enough for you, alternatively you can: + +* Enable CORS on your server ([here’s how to do it for Express](http://enable-cors.org/server_expressjs.html)). +* Use [environment variables](#adding-custom-environment-variables) to inject the right server host and port into your app. + +## Using HTTPS in Development + +>Note: this feature is available with `react-scripts@0.4.0` and higher. + +You may require the dev server to serve pages over HTTPS. One particular case where this could be useful is when using [the "proxy" feature](#proxying-api-requests-in-development) to proxy requests to an API server when that API server is itself serving HTTPS. + +To do this, set the `HTTPS` environment variable to `true`, then start the dev server as usual with `npm start`: + +#### Windows (cmd.exe) + +```cmd +set HTTPS=true&&npm start +``` + +(Note: the lack of whitespace is intentional.) + +#### Linux, macOS (Bash) + +```bash +HTTPS=true npm start +``` + +Note that the server will use a self-signed certificate, so your web browser will almost definitely display a warning upon accessing the page. + +## Generating Dynamic `` Tags on the Server + +Since Create React App doesn’t support server rendering, you might be wondering how to make `` tags dynamic and reflect the current URL. To solve this, we recommend to add placeholders into the HTML, like this: + +```html + + + + + +``` + +Then, on the server, regardless of the backend you use, you can read `index.html` into memory and replace `__OG_TITLE__`, `__OG_DESCRIPTION__`, and any other placeholders with values depending on the current URL. Just make sure to sanitize and escape the interpolated values so that they are safe to embed into HTML! + +If you use a Node server, you can even share the route matching logic between the client and the server. However duplicating it also works fine in simple cases. + +## Pre-Rendering into Static HTML Files + +If you’re hosting your `build` with a static hosting provider you can use [react-snapshot](https://www.npmjs.com/package/react-snapshot) to generate HTML pages for each route, or relative link, in your application. These pages will then seamlessly become active, or “hydrated”, when the JavaScript bundle has loaded. + +There are also opportunities to use this outside of static hosting, to take the pressure off the server when generating and caching routes. + +The primary benefit of pre-rendering is that you get the core content of each page _with_ the HTML payload—regardless of whether or not your JavaScript bundle successfully downloads. It also increases the likelihood that each route of your application will be picked up by search engines. + +You can read more about [zero-configuration pre-rendering (also called snapshotting) here](https://medium.com/superhighfives/an-almost-static-stack-6df0a2791319). + +## Injecting Data from the Server into the Page + +Similarly to the previous section, you can leave some placeholders in the HTML that inject global variables, for example: + +```js + + + + +``` + +Then, on the server, you can replace `__SERVER_DATA__` with a JSON of real data right before sending the response. The client code can then read `window.SERVER_DATA` to use it. **Make sure to [sanitize the JSON before sending it to the client](https://medium.com/node-security/the-most-common-xss-vulnerability-in-react-js-applications-2bdffbcc1fa0) as it makes your app vulnerable to XSS attacks.** + +## Running Tests + +>Note: this feature is available with `react-scripts@0.3.0` and higher.
+>[Read the migration guide to learn how to enable it in older projects!](https://github.com/facebookincubator/create-react-app/blob/master/CHANGELOG.md#migrating-from-023-to-030) + +Create React App uses [Jest](https://facebook.github.io/jest/) as its test runner. To prepare for this integration, we did a [major revamp](https://facebook.github.io/jest/blog/2016/09/01/jest-15.html) of Jest so if you heard bad things about it years ago, give it another try. + +Jest is a Node-based runner. This means that the tests always run in a Node environment and not in a real browser. This lets us enable fast iteration speed and prevent flakiness. + +While Jest provides browser globals such as `window` thanks to [jsdom](https://github.com/tmpvar/jsdom), they are only approximations of the real browser behavior. Jest is intended to be used for unit tests of your logic and your components rather than the DOM quirks. + +We recommend that you use a separate tool for browser end-to-end tests if you need them. They are beyond the scope of Create React App. + +### Filename Conventions + +Jest will look for test files with any of the following popular naming conventions: + +* Files with `.js` suffix in `__tests__` folders. +* Files with `.test.js` suffix. +* Files with `.spec.js` suffix. + +The `.test.js` / `.spec.js` files (or the `__tests__` folders) can be located at any depth under the `src` top level folder. + +We recommend to put the test files (or `__tests__` folders) next to the code they are testing so that relative imports appear shorter. For example, if `App.test.js` and `App.js` are in the same folder, the test just needs to `import App from './App'` instead of a long relative path. Colocation also helps find tests more quickly in larger projects. + +### Command Line Interface + +When you run `npm test`, Jest will launch in the watch mode. Every time you save a file, it will re-run the tests, just like `npm start` recompiles the code. + +The watcher includes an interactive command-line interface with the ability to run all tests, or focus on a search pattern. It is designed this way so that you can keep it open and enjoy fast re-runs. You can learn the commands from the “Watch Usage” note that the watcher prints after every run: + +![Jest watch mode](http://facebook.github.io/jest/img/blog/15-watch.gif) + +### Version Control Integration + +By default, when you run `npm test`, Jest will only run the tests related to files changed since the last commit. This is an optimization designed to make your tests runs fast regardless of how many tests you have. However it assumes that you don’t often commit the code that doesn’t pass the tests. + +Jest will always explicitly mention that it only ran tests related to the files changed since the last commit. You can also press `a` in the watch mode to force Jest to run all tests. + +Jest will always run all tests on a [continuous integration](#continuous-integration) server or if the project is not inside a Git or Mercurial repository. + +### Writing Tests + +To create tests, add `it()` (or `test()`) blocks with the name of the test and its code. You may optionally wrap them in `describe()` blocks for logical grouping but this is neither required nor recommended. + +Jest provides a built-in `expect()` global function for making assertions. A basic test could look like this: + +```js +import sum from './sum'; + +it('sums numbers', () => { + expect(sum(1, 2)).toEqual(3); + expect(sum(2, 2)).toEqual(4); +}); +``` + +All `expect()` matchers supported by Jest are [extensively documented here](http://facebook.github.io/jest/docs/expect.html).
+You can also use [`jest.fn()` and `expect(fn).toBeCalled()`](http://facebook.github.io/jest/docs/expect.html#tohavebeencalled) to create “spies” or mock functions. + +### Testing Components + +There is a broad spectrum of component testing techniques. They range from a “smoke test” verifying that a component renders without throwing, to shallow rendering and testing some of the output, to full rendering and testing component lifecycle and state changes. + +Different projects choose different testing tradeoffs based on how often components change, and how much logic they contain. If you haven’t decided on a testing strategy yet, we recommend that you start with creating simple smoke tests for your components: + +```js +import React from 'react'; +import ReactDOM from 'react-dom'; +import App from './App'; + +it('renders without crashing', () => { + const div = document.createElement('div'); + ReactDOM.render(, div); +}); +``` + +This test mounts a component and makes sure that it didn’t throw during rendering. Tests like this provide a lot value with very little effort so they are great as a starting point, and this is the test you will find in `src/App.test.js`. + +When you encounter bugs caused by changing components, you will gain a deeper insight into which parts of them are worth testing in your application. This might be a good time to introduce more specific tests asserting specific expected output or behavior. + +If you’d like to test components in isolation from the child components they render, we recommend using [`shallow()` rendering API](http://airbnb.io/enzyme/docs/api/shallow.html) from [Enzyme](http://airbnb.io/enzyme/). You can write a smoke test with it too: + +```sh +npm install --save-dev enzyme react-addons-test-utils +``` + +```js +import React from 'react'; +import { shallow } from 'enzyme'; +import App from './App'; + +it('renders without crashing', () => { + shallow(); +}); +``` + +Unlike the previous smoke test using `ReactDOM.render()`, this test only renders `` and doesn’t go deeper. For example, even if `` itself renders a ` + + + ; + } +} + +export default DeleteDialog; diff --git a/src/components/dialogs/dialog.js b/src/components/dialogs/dialog.js new file mode 100644 index 0000000..db4c6a4 --- /dev/null +++ b/src/components/dialogs/dialog.js @@ -0,0 +1,71 @@ +/** + * File: dialog.js + * Author: Markus Grigull + * Date: 03.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { Modal, Button } from 'react-bootstrap'; + +class Dialog extends React.Component { + closeModal = (event) => { + this.props.onClose(false); + } + + cancelModal = (event) => { + this.props.onClose(true); + } + + /** + * To prevent Enter hanlding user onKeyPress={this.handleKeyIgnore} in that form element + * and the following handler in the corresponding file: + * + * //this function prevents a keystroke from beeing handled by dialog.js + * handleKeyIgnore(event){ + * event.stopPropagation(); + * } + */ + onKeyPress = (event) => { + if (event.key === 'Enter') { + // prevent input from submitting + event.preventDefault(); + this.closeModal(false); + } + } + + render() { + return ( + + + {this.props.title} + + + + {this.props.children} + + + + + + + + ); + } +} + +export default Dialog; diff --git a/src/components/dialogs/edit-project.js b/src/components/dialogs/edit-project.js new file mode 100644 index 0000000..2b960b6 --- /dev/null +++ b/src/components/dialogs/edit-project.js @@ -0,0 +1,101 @@ +/** + * File: edit-project.js + * Author: Markus Grigull + * Date: 07.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { FormGroup, FormControl, ControlLabel } from 'react-bootstrap'; + +import Dialog from './dialog'; + +class EditProjectDialog extends React.Component { + valid: true; + + constructor(props) { + super(props); + + this.state = { + name: '', + simulation: '', + _id: '' + } + } + + onClose(canceled) { + if (canceled === false) { + if (this.valid) { + this.props.onClose(this.state); + } + } else { + this.props.onClose(); + } + } + + handleChange(e) { + this.setState({ [e.target.id]: e.target.value }); + } + + resetState() { + this.setState({ + name: this.props.project.name, + simulation: this.props.project.simulation, + _id: this.props.project._id + }); + } + + validateForm(target) { + // check all controls + var name = true; + + if (this.state.name === '') { + name = false; + } + + this.valid = name; + + // return state to control + if (target === 'name') return name ? "success" : "error"; + + return "success"; + } + + render() { + return ( + this.onClose(c)} onReset={() => this.resetState()} valid={this.valid}> +
+ + Name + this.handleChange(e)} /> + + + + Simulation + this.handleChange(e)}> + {this.props.simulations.map(simulation => ( + + ))} + + +
+
+ ); + } +} + +export default EditProjectDialog; diff --git a/src/components/dialogs/edit-simulation.js b/src/components/dialogs/edit-simulation.js new file mode 100644 index 0000000..0b1c87e --- /dev/null +++ b/src/components/dialogs/edit-simulation.js @@ -0,0 +1,103 @@ +/** + * File: new-simulation.js + * Author: Markus Grigull + * Date: 04.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { FormGroup, FormControl, ControlLabel } from 'react-bootstrap'; + +import Dialog from './dialog'; +import ParametersEditor from '../parameters-editor'; + +class EditSimulationDialog extends React.Component { + valid = true; + + constructor(props) { + super(props); + + this.state = { + name: '', + _id: '', + startParameters: {} + }; + } + + onClose = canceled => { + if (canceled) { + if (this.props.onClose != null) { + this.props.onClose(); + } + + return; + } + + if (this.valid && this.props.onClose != null) { + this.props.onClose(this.state); + } + } + + handleChange = event => { + this.setState({ [event.target.id]: event.target.value }); + } + + resetState = () => { + this.setState({ + name: this.props.simulation.name, + _id: this.props.simulation._id, + startParameters: this.props.simulation.startParameters || {} + }); + } + + handleStartParametersChange = startParameters => { + this.setState({ startParameters }); + } + + validateForm(target) { + let name = true; + + if (this.state.name === '') { + name = false; + } + + this.valid = name; + + // return state to control + if (target === 'name') return name ? 'success' : 'error'; + } + + render() { + return +
+ + Name + + + + + + Start Parameters + + + +
+
; + } +} + +export default EditSimulationDialog; diff --git a/src/components/dialogs/edit-simulator.js b/src/components/dialogs/edit-simulator.js new file mode 100644 index 0000000..346fb2a --- /dev/null +++ b/src/components/dialogs/edit-simulator.js @@ -0,0 +1,96 @@ +/** + * File: new-simulator.js + * Author: Markus Grigull + * Date: 02.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { FormGroup, FormControl, ControlLabel } from 'react-bootstrap'; +import _ from 'lodash'; + +import Dialog from './dialog'; +import ParametersEditor from '../parameters-editor'; + +class EditSimulatorDialog extends React.Component { + valid = true; + + constructor(props) { + super(props); + + this.state = { + name: '', + endpoint: '' + }; + } + + onClose(canceled) { + if (canceled === false) { + if (this.valid) { + let data = {}; + + if (this.state.name != null && this.state.name !== "" && this.state.name !== _.get(this.props.simulator, 'rawProperties.name')) { + data.name = this.state.name; + } + + if (this.state.endpoint != null && this.state.endpoint !== "" && this.state.endpoint !== "http://" && this.state.endpoint !== _.get(this.props.simulator, 'rawProperties.endpoint')) { + data.endpoint = this.state.endpoint; + } + + this.props.onClose(data); + } + } else { + this.props.onClose(); + } + } + + handleChange(e) { + this.setState({ [e.target.id]: e.target.value }); + } + + resetState() { + this.setState({ + name: _.get(this.props.simulator, 'properties.name') || _.get(this.props.simulator, 'rawProperties.name'), + endpoint: _.get(this.props.simulator, 'properties.endpoint') || _.get(this.props.simulator, 'rawProperties.endpoint') + }); + } + + render() { + return ( + this.onClose(c)} onReset={() => this.resetState()} valid={this.valid}> +
+ + Name + this.handleChange(e)} /> + + + + Endpoint + this.handleChange(e)} /> + + + + Properties + + +
+
+ ); + } +} + +export default EditSimulatorDialog; diff --git a/src/components/dialogs/edit-user.js b/src/components/dialogs/edit-user.js new file mode 100644 index 0000000..e518b7d --- /dev/null +++ b/src/components/dialogs/edit-user.js @@ -0,0 +1,107 @@ +/** + * File: edit-user.js + * Author: Ricardo Hernandez-Montoya + * Date: 02.05.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { FormGroup, FormControl, ControlLabel } from 'react-bootstrap'; + +import Dialog from './dialog'; + +class EditUserDialog extends React.Component { + valid: true; + + constructor(props) { + super(props); + + this.state = { + username: '', + mail: '', + role: '', + _id: '' + } + } + + onClose(canceled) { + if (canceled === false) { + if (this.valid) { + this.props.onClose(this.state); + } + } else { + this.props.onClose(); + } + } + + handleChange(e) { + this.setState({ [e.target.id]: e.target.value }); + } + + resetState() { + this.setState({ + username: this.props.user.username, + mail: this.props.user.mail, + role: this.props.user.role, + _id: this.props.user._id + }); + } + + validateForm(target) { + // check all controls + var username = true; + + if (this.state.username === '') { + username = false; + } + + this.valid = username; + + // return state to control + if (target === 'username') return username ? "success" : "error"; + + return "success"; + } + + render() { + return ( + this.onClose(c)} onReset={() => this.resetState()} valid={this.valid}> +
+ + Username + this.handleChange(e)} /> + + + + E-mail + this.handleChange(e)} /> + + + Role + this.handleChange(e)}> + + + + + +
+
+ ); + } +} + +export default EditUserDialog; diff --git a/src/components/dialogs/edit-visualization.js b/src/components/dialogs/edit-visualization.js new file mode 100644 index 0000000..ccd8578 --- /dev/null +++ b/src/components/dialogs/edit-visualization.js @@ -0,0 +1,91 @@ +/** + * File: new-visualization.js + * Author: Markus Grigull + * Date: 03.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { FormGroup, FormControl, ControlLabel } from 'react-bootstrap'; + +import Dialog from './dialog'; + +class EditVisualizationDialog extends React.Component { + valid: false; + + constructor(props) { + super(props); + + this.state = { + name: '', + _id: '' + } + } + + onClose(canceled) { + if (canceled === false) { + if (this.valid) { + this.props.onClose(this.state); + } + } else { + this.props.onClose(); + } + } + + handleChange(e) { + this.setState({ [e.target.id]: e.target.value }); + } + + resetState() { + this.setState({ + name: this.props.visualization.name, + _id: this.props.visualization._id + }); + } + + validateForm(target) { + // check all controls + var name = true; + + if (this.state.name === '') { + name = false; + } + + this.valid = name; + + // return state to control + if (target === 'name') return name ? "success" : "error"; + + return "success"; + } + + render() { + return ( + this.onClose(c)} onReset={() => this.resetState()} valid={this.valid}> +
+ + Name + this.handleChange(e)} /> + + +
+
+ ); + } +} + +export default EditVisualizationDialog; diff --git a/src/components/dialogs/edit-widget-aspect-control.js b/src/components/dialogs/edit-widget-aspect-control.js new file mode 100644 index 0000000..2e4d4d8 --- /dev/null +++ b/src/components/dialogs/edit-widget-aspect-control.js @@ -0,0 +1,49 @@ +/** + * File: edit-widget-aspect-control.js + * Author: Markus Grigull + * Date: 29.07.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { FormGroup, Checkbox } from 'react-bootstrap'; + +class EditWidgetAspectControl extends React.Component { + constructor(props) { + super(props); + + this.state = { + widget: { + lockAspect: true + } + }; + } + + componentWillReceiveProps(nextProps) { + this.setState({ widget: nextProps.widget }); + } + + render() { + return ( + + this.props.handleChange(e)}>Lock Aspect + + ); + } +} + +export default EditWidgetAspectControl; \ No newline at end of file diff --git a/src/components/dialogs/edit-widget-checkbox-control.js b/src/components/dialogs/edit-widget-checkbox-control.js new file mode 100644 index 0000000..9c063fb --- /dev/null +++ b/src/components/dialogs/edit-widget-checkbox-control.js @@ -0,0 +1,45 @@ +/** + * File: edit-widget-checkbox-control.js + * Author: Markus Grigull + * Date: 19.08.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { FormGroup, Checkbox } from 'react-bootstrap'; + +class EditWidgetCheckboxControl extends React.Component { + constructor(props) { + super(props); + + this.state = { + widget: {} + }; + } + + componentWillReceiveProps(nextProps) { + this.setState({ widget: nextProps.widget }); + } + + render() { + return + this.props.handleChange(e)}>{this.props.text} + ; + } +} + +export default EditWidgetCheckboxControl; \ No newline at end of file diff --git a/src/components/dialogs/edit-widget-color-control.js b/src/components/dialogs/edit-widget-color-control.js new file mode 100644 index 0000000..6a44e3d --- /dev/null +++ b/src/components/dialogs/edit-widget-color-control.js @@ -0,0 +1,83 @@ +/** + * File: edit-widget-color-control.js + * Author: Ricardo Hernandez-Montoya + * Date: 24.04.2017 + * Copyright: 2018, Institute for Automation of Complex Power Systems, EONERC + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React, { Component } from 'react'; +import { FormGroup, Col, Row, Radio, ControlLabel } from 'react-bootstrap'; +import classNames from 'classnames'; +import { scaleOrdinal, schemeCategory20 } from 'd3-scale'; + +class EditWidgetColorControl extends Component { + + static get ColorPalette() { + let colorCount = 0; + const colors = []; + const colorScale = scaleOrdinal(schemeCategory20); + while (colorCount < 20) { colors.push(colorScale(colorCount)); colorCount++; } + colors.unshift('#000', '#FFF'); // include black and white + + return colors; + } + + constructor(props) { + super(props); + + this.state = { + widget: {} + }; + } + + componentWillReceiveProps(nextProps) { + // Update state's widget with props + this.setState({ widget: nextProps.widget }); + } + + render() { + + return ( + + + + { this.props.label } + + + { + EditWidgetColorControl.ColorPalette.map( (color, idx ) => { + let colorStyle = { + background: color, + borderColor: color + }; + + let checkedClass = classNames({ + 'checked': idx === this.state.widget[this.props.controlId] + }); + + return ( this.props.handleChange({target: { id: this.props.controlId, value: idx}})} />) + } + ) + } + + + ) + } +} + +export default EditWidgetColorControl; diff --git a/src/components/dialogs/edit-widget-color-zones-control.js b/src/components/dialogs/edit-widget-color-zones-control.js new file mode 100644 index 0000000..3367218 --- /dev/null +++ b/src/components/dialogs/edit-widget-color-zones-control.js @@ -0,0 +1,133 @@ +/** + * File: edit-widget-color-zones-control.js + * Author: Markus Grigull + * Date: 20.08.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { FormGroup, ControlLabel, Button } from 'react-bootstrap'; + + +import Icon from '../icon'; +import Table from '../table'; +import TableColumn from '../table-column'; + +class EditWidgetColorZonesControl extends React.Component { + constructor(props) { + super(props); + + this.state = { + widget: { + zones: [] + }, + selectedZones: [] + }; + } + + componentWillReceiveProps(nextProps) { + this.setState({ widget: nextProps.widget }); + } + + addZone = () => { + // add row + const widget = this.state.widget; + widget.zones.push({ strokeStyle: 'ffffff', min: 0, max: 100 }); + + this.setState({ widget }); + + this.sendEvent(widget); + } + + removeZones = () => { + // remove zones + const widget = this.state.widget; + + this.state.selectedZones.forEach(row => { + widget.zones.splice(row, 1); + }); + + this.setState({ selectedZones: [], widget }); + + this.sendEvent(widget); + } + + changeCell = (event, row, column) => { + // change row + const widget = this.state.widget; + + if (column === 1) { + widget.zones[row].strokeStyle = event.target.value; + } else if (column === 2) { + widget.zones[row].min = event.target.value; + } else if (column === 3) { + widget.zones[row].max = event.target.value; + } + + this.setState({ widget }); + + this.sendEvent(widget); + } + + sendEvent(widget) { + // create event + const event = { + target: { + id: 'zones', + value: widget.zones + } + }; + + this.props.handleChange(event); + } + + checkedCell = (row, event) => { + // update selected rows + const selectedZones = this.state.selectedZones; + + if (event.target.checked) { + if (selectedZones.indexOf(row) === -1) { + selectedZones.push(row); + } + } else { + let index = selectedZones.indexOf(row); + if (row > -1) { + selectedZones.splice(index, 1); + } + } + + this.setState({ selectedZones }); + } + + render() { + return + Color zones + + + + + + +
+ + + +
; + } +} + +export default EditWidgetColorZonesControl; diff --git a/src/components/dialogs/edit-widget-control-creator.js b/src/components/dialogs/edit-widget-control-creator.js new file mode 100644 index 0000000..fdce7e5 --- /dev/null +++ b/src/components/dialogs/edit-widget-control-creator.js @@ -0,0 +1,202 @@ +/** + * File: edit-widget-control-creator.js + * Author: Ricardo Hernandez-Montoya + * Date: 23.05.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + **********************************************************************************/ + +import React from 'react'; + +import EditWidgetTextControl from './edit-widget-text-control'; +import EditWidgetNumberControl from './edit-widget-number-control'; +import EditWidgetColorControl from './edit-widget-color-control'; +import EditWidgetTimeControl from './edit-widget-time-control'; +import EditImageWidgetControl from './edit-widget-image-control'; +import EditWidgetSimulationControl from './edit-widget-simulation-control'; +import EditWidgetSignalControl from './edit-widget-signal-control'; +import EditWidgetSignalsControl from './edit-widget-signals-control'; +import EditWidgetOrientation from './edit-widget-orientation'; +import EditWidgetAspectControl from './edit-widget-aspect-control'; +import EditWidgetTextSizeControl from './edit-widget-text-size-control'; +import EditWidgetCheckboxControl from './edit-widget-checkbox-control'; +import EditWidgetColorZonesControl from './edit-widget-color-zones-control'; +import EditWidgetMinMaxControl from './edit-widget-min-max-control'; +import EditWidgetHTMLContent from './edit-widget-html-content'; +import EditWidgetParametersControl from './edit-widget-parameters-control'; + +export default function createControls(widgetType = null, widget = null, sessionToken = null, files = null, validateForm, simulationModels, handleChange) { + // Use a list to concatenate the controls according to the widget type + var dialogControls = []; + + switch(widgetType) { + case 'CustomAction': + dialogControls.push( + validateForm(id)} handleChange={e => handleChange(e)} />, + validateForm(id)} handleChange={e => handleChange(e)} />, + validateForm(id)} simulationModels={simulationModels} handleChange={(e) => handleChange(e)} />, + handleChange(e)} /> + ) + break; + case 'Action': + dialogControls.push( + validateForm(id)} simulationModels={simulationModels} handleChange={(e) => handleChange(e)} /> + ) + break; + case 'Value': + let valueBoundOnChange = (e) => { + handleChange([e, {target: {id: 'signal', value: 0}}]); + } + dialogControls.push( + validateForm(id)} handleChange={e => handleChange(e)} />, + validateForm(id)} simulationModels={simulationModels} handleChange={(e) => valueBoundOnChange(e)} />, + validateForm(id)} simulationModels={simulationModels} handleChange={(e) => handleChange(e)} />, + handleChange(e)} />, + handleChange(e)} /> + ); + break; + case 'Lamp': + let lampBoundOnChange = (e) => { + handleChange([e, {target: {id: 'signal', value: 0}}]); + } + dialogControls.push( + validateForm(id)} simulationModels={simulationModels} handleChange={(e) => lampBoundOnChange(e)} />, + validateForm(id)} simulationModels={simulationModels} handleChange={(e) => handleChange(e)} />, + validateForm(id)} handleChange={e => handleChange(e)} />, + validateForm(id)} handleChange={(e) => handleChange(e)} />, + validateForm(id)} handleChange={(e) => handleChange(e)} />, + ); + break; + case 'Plot': + let plotBoundOnChange = (e) => { + handleChange([e, {target: {id: 'signals', value: []}}]); + } + dialogControls.push( + validateForm(id)} simulationModels={simulationModels} handleChange={(e) => handleChange(e)} />, + validateForm(id)} simulationModels={simulationModels} handleChange={(e) => plotBoundOnChange(e)} />, + validateForm(id)} simulationModels={simulationModels} handleChange={(e) => handleChange(e)} />, + handleChange(e)} />, + handleChange(e)} /> + ); + break; + case 'Table': + dialogControls.push( + validateForm(id)} simulationModels={simulationModels} handleChange={(e) => handleChange(e)} />, + handleChange(e)} /> + ); + break; + case 'Image': + // Restrict to only image file types (MIME) + let imageControlFiles = files == null? [] : files.filter(file => file.type.includes('image')); + dialogControls.push( + validateForm(id)} simulationModels={simulationModels} handleChange={(e) => handleChange(e)} />, + handleChange(e)} /> + ); + break; + case 'Gauge': + let gaugeBoundOnChange = (e) => { + handleChange([e, {target: {id: 'signal', value: ''}}]); + } + dialogControls.push( + validateForm(id)} handleChange={e => handleChange(e)} />, + validateForm(id)} simulationModels={simulationModels} handleChange={(e) => gaugeBoundOnChange(e) } />, + validateForm(id)} simulationModels={simulationModels} handleChange={(e) => handleChange(e)} />, + handleChange(e)} />, + handleChange(e)} />, + handleChange(e)} /> + ); + break; + case 'PlotTable': + let plotTableBoundOnChange = (e) => { + handleChange([e, {target: {id: 'preselectedSignals', value: []}}]); + } + dialogControls.push( + validateForm(id)} simulationModels={simulationModels} handleChange={(e) => plotTableBoundOnChange(e)} />, + validateForm(id)} simulationModels={simulationModels} handleChange={(e) => handleChange(e)} />, + handleChange(e)} />, + validateForm(id)} simulationModels={simulationModels} handleChange={(e) => handleChange(e)} />, + handleChange(e)} /> + ); + break; + case 'Slider': + dialogControls.push( + handleChange(e)} validate={id => validateForm(id)} />, + validateForm(id)} simulationModels={simulationModels} handleChange={(e) => handleChange(e)} />, + validateForm(id)} simulationModels={simulationModels} handleChange={(e) => handleChange(e)} />, + validateForm(id)} simulationModels={simulationModels} handleChange={(e) => handleChange(e)} />, + handleChange(e)} />, + handleChange(e)} />, + handleChange(e)} />, + handleChange(e)} />, + handleChange(e)} /> + ); + break; + case 'Button': + let buttonBoundOnChange = (e) => { + handleChange([e, {target: {id: 'signal', value: 0}}]); + } + dialogControls.push( + handleChange(e)} validate={id => validateForm(id)} />, + validateForm(id)} simulationModels={simulationModels} handleChange={(e) => buttonBoundOnChange(e)} />, + validateForm(id)} simulationModels={simulationModels} handleChange={(e) => handleChange(e)} />, + handleChange(e)} />, + handleChange(e)} />, + handleChange(e)} /> + ); + break; + case 'Box': + dialogControls.push( + validateForm(id)} handleChange={(e) => handleChange(e)} />, + handleChange(e)} /> + ); + break; + case 'Label': + dialogControls.push( + handleChange(e)} validate={id => validateForm(id)} />, + handleChange(e)} />, + handleChange(e)} /> + ); + break; + case 'HTML': + dialogControls.push( + handleChange(e)} /> + ); + break; + case 'Topology': + // Restrict to only xml files (MIME) + let topologyControlFiles = files == null? [] : files.filter( file => file.type.includes('xml')); + dialogControls.push( + validateForm(id)} simulationModels={simulationModels} handleChange={(e) => handleChange(e)} /> + ); + break; + + case 'Input': + let inputBoundOnChange = (e) => { + handleChange([e, {target: {id: 'signal', value: 0}}]); + } + dialogControls.push( + validateForm(id)} handleChange={e => handleChange(e)} />, + validateForm(id)} simulationModels={simulationModels} handleChange={(e) => inputBoundOnChange(e)} />, + validateForm(id)} simulationModels={simulationModels} handleChange={(e) => handleChange(e)} /> + ); + break; + + default: + console.log('Non-valid widget type: ' + widgetType); + } + + return dialogControls; +} diff --git a/src/components/dialogs/edit-widget-html-content.js b/src/components/dialogs/edit-widget-html-content.js new file mode 100644 index 0000000..3b02bc3 --- /dev/null +++ b/src/components/dialogs/edit-widget-html-content.js @@ -0,0 +1,52 @@ +/** + * File: edit-widget-html-content.js + * Author: Ricardo Hernandez-Montoya + * Date: 03.09.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + **********************************************************************************/ + +import React from 'react'; +import { FormGroup, FormControl, ControlLabel } from 'react-bootstrap'; + +class EditWidgetHTMLContent extends React.Component { + constructor(props) { + super(props); + + this.state = { + widget: {} + }; + } + + handleKeyIgnore(event){ + // This function prevents a keystroke from beeing handled by dialog.js + event.stopPropagation(); + } + + componentWillReceiveProps(nextProps) { + // Update state's widget with props + this.setState({ widget: nextProps.widget }); + } + + render() { + return + HTML Content + this.props.handleChange(e)} /> + ; + } +} + +export default EditWidgetHTMLContent; diff --git a/src/components/dialogs/edit-widget-image-control.js b/src/components/dialogs/edit-widget-image-control.js new file mode 100644 index 0000000..9db27ac --- /dev/null +++ b/src/components/dialogs/edit-widget-image-control.js @@ -0,0 +1,101 @@ +/** + * File: edit-widget-image-control.js + * Author: Markus Grigull + * Date: 04.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { FormGroup, FormControl, ControlLabel, Button, ProgressBar } from 'react-bootstrap'; + +import AppDispatcher from '../../app-dispatcher'; + +class EditImageWidgetControl extends React.Component { + constructor(props) { + super(props); + + this.state = { + widget: { + file: '' + }, + fileList: null, + progress: 0 + }; + } + + componentWillReceiveProps(nextProps) { + this.setState({ widget: nextProps.widget }); + } + + startFileUpload = () => { + // get selected file + let formData = new FormData(); + + for (let key in this.state.fileList) { + if (this.state.fileList.hasOwnProperty(key) && this.state.fileList[key] instanceof File) { + formData.append(key, this.state.fileList[key]); + } + } + + // upload files + AppDispatcher.dispatch({ + type: 'files/start-upload', + data: formData, + token: this.props.sessionToken, + progressCallback: this.uploadProgress, + finishedCallback: this.clearProgress + }); + } + + uploadProgress = (e) => { + this.setState({ progress: Math.round(e.percent) }); + } + + clearProgress = () => { + this.setState({ progress: 0 }); + } + + render() { + return
+ + Image + this.props.handleChange(e)}> + {this.props.files.length === 0 ? ( + + ) : ( + this.props.files.reduce((entries, file, index) => { + entries.push(); + return entries; + }, [ + + ]) + )} + + + + + Upload + this.setState({ fileList: e.target.files }) } /> + + + + +
; + } +} + +export default EditImageWidgetControl; diff --git a/src/components/dialogs/edit-widget-min-max-control.js b/src/components/dialogs/edit-widget-min-max-control.js new file mode 100644 index 0000000..39218bf --- /dev/null +++ b/src/components/dialogs/edit-widget-min-max-control.js @@ -0,0 +1,64 @@ +/** + * File: edit-widget-min-max-control.js + * Author: Markus Grigull + * Date: 30.08.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { FormGroup, FormControl, ControlLabel, Checkbox, Table } from 'react-bootstrap'; + +class EditWidgetMinMaxControl extends React.Component { + constructor(props) { + super(props); + + const widget = {}; + widget[props.controlID + "UseMinMax"] = false; + widget[props.controlId + "Min"] = 0; + widget[props.controlId + "Max"] = 100; + + this.state = { + widget + }; + } + + componentWillReceiveProps(nextProps) { + this.setState({ widget: nextProps.widget }); + } + + render() { + return + {this.props.label} + this.props.handleChange(e)}>Enable min-max + + + + + + + + +
+ Min: this.props.handleChange(e)} /> + + Max: this.props.handleChange(e)} /> +
+
; + } +} + +export default EditWidgetMinMaxControl; diff --git a/src/components/dialogs/edit-widget-number-control.js b/src/components/dialogs/edit-widget-number-control.js new file mode 100644 index 0000000..07de491 --- /dev/null +++ b/src/components/dialogs/edit-widget-number-control.js @@ -0,0 +1,49 @@ +/** + * File: edit-widget-text-control.js + * Author: Ricardo Hernandez-Montoya + * Date: 21.04.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + **********************************************************************************/ + +import React, { Component } from 'react'; +import { FormGroup, FormControl, ControlLabel } from 'react-bootstrap'; + +class EditWidgetNumberControl extends Component { + constructor(props) { + super(props); + + this.state = { + widget: {} + }; + } + + componentWillReceiveProps(nextProps) { + // Update state's widget with props + this.setState({ widget: nextProps.widget }); + } + + render() { + return ( + + {this.props.label} + this.props.handleChange(e)} /> + + ); + } +} + +export default EditWidgetNumberControl; diff --git a/src/components/dialogs/edit-widget-orientation.js b/src/components/dialogs/edit-widget-orientation.js new file mode 100644 index 0000000..737aaef --- /dev/null +++ b/src/components/dialogs/edit-widget-orientation.js @@ -0,0 +1,73 @@ +/** + * File: edit-widget-orientation.js + * Author: Ricardo Hernandez-Montoya + * Date: 10.04.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + **********************************************************************************/ + +import React, { Component } from 'react'; +import { FormGroup, Col, Row, Radio, ControlLabel } from 'react-bootstrap'; + +import WidgetSlider from '../widgets/slider'; + +class EditWidgetOrientation extends Component { + constructor(props) { + super(props); + + this.state = { + widget: {} + }; + } + + componentWillReceiveProps(nextProps) { + // Update state's widget with props + this.setState({ widget: nextProps.widget }); + } + + handleOrientationChange(orientation) { + this.props.handleChange({ target: { id: 'orientation', value: orientation } }); + } + + render() { + + // The tag shouldn't be necessary, but it gives height to the row while combining horizontal and vertical forms + return ( + + + + Orientation + + + { + Object.keys(WidgetSlider.OrientationTypes).map( (type) => { + let value = WidgetSlider.OrientationTypes[type].value; + let name = WidgetSlider.OrientationTypes[type].name; + + return ( + this.handleOrientationChange(value)}> + { name } + ) + }) + } + + + + ); + } +} + +export default EditWidgetOrientation; diff --git a/src/components/dialogs/edit-widget-parameters-control.js b/src/components/dialogs/edit-widget-parameters-control.js new file mode 100644 index 0000000..8cf454b --- /dev/null +++ b/src/components/dialogs/edit-widget-parameters-control.js @@ -0,0 +1,59 @@ +/** + * File: edit-widget-text-control.js + * Author: Ricardo Hernandez-Montoya + * Date: 21.04.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + **********************************************************************************/ + +import React, { Component } from 'react'; +import { FormGroup, ControlLabel } from 'react-bootstrap'; +import ParametersEditor from '../parameters-editor'; + +class EditWidgetParametersControl extends Component { + constructor(props) { + super(props); + + this.state = { + widget: {} + }; + } + + componentWillReceiveProps(nextProps) { + // Update state's widget with props + this.setState({ widget: nextProps.widget }); + } + + handleChange(value) { + this.props.handleChange({ + target: { + id: this.props.controlId, + value: value + } + }); + } + + render() { + return ( + + {this.props.label} + this.handleChange(v)} /> + + ); + } +} + +export default EditWidgetParametersControl; diff --git a/src/components/dialogs/edit-widget-signal-control.js b/src/components/dialogs/edit-widget-signal-control.js new file mode 100644 index 0000000..4664936 --- /dev/null +++ b/src/components/dialogs/edit-widget-signal-control.js @@ -0,0 +1,73 @@ +/** + * File: edit-widget-signal-control.js + * Author: Ricardo Hernandez-Montoya + * Date: 03.04.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + **********************************************************************************/ + +import React, { Component } from 'react'; +import { FormGroup, FormControl, ControlLabel } from 'react-bootstrap'; + +class EditWidgetSignalControl extends Component { + constructor(props) { + super(props); + + this.state = { + widget: { + simulationModel: '' + } + }; + } + + componentWillReceiveProps(nextProps) { + // Update state's widget with props + this.setState({ widget: nextProps.widget }); + } + + render() { + const simulationModel = this.props.simulationModels.find(m => m._id === this.state.widget.simulationModel); + + let signalsToRender = []; + + if (simulationModel != null) { + if (this.props.input) { + signalsToRender = simulationModel ? simulationModel.inputMapping : []; + } else { + signalsToRender = simulationModel ? simulationModel.outputMapping : []; + } + } + + return ( + + Signal + this.props.handleChange(e)}> + { + signalsToRender.length === 0 ? ( + + ) : ( + signalsToRender.map((signal, index) => ( + + )) + ) + } + + + ); + } +} + +export default EditWidgetSignalControl; diff --git a/src/components/dialogs/edit-widget-signals-control.js b/src/components/dialogs/edit-widget-signals-control.js new file mode 100644 index 0000000..0b55312 --- /dev/null +++ b/src/components/dialogs/edit-widget-signals-control.js @@ -0,0 +1,83 @@ +/** + * File: edit-widget-signals-control.js + * Author: Ricardo Hernandez-Montoya + * Date: 03.04.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + **********************************************************************************/ + +import React, { Component } from 'react'; +import { FormGroup, Checkbox, ControlLabel, FormControl } from 'react-bootstrap'; + +class EditWidgetSignalsControl extends Component { + constructor(props) { + super(props); + + this.state = { + widget: { + simulator: {} + } + }; + } + + componentWillReceiveProps(nextProps) { + // Update state's widget with props + this.setState({ widget: nextProps.widget }); + } + + handleSignalChange(checked, index) { + var signals = this.state.widget[this.props.controlId]; + var new_signals; + + if (checked) { + // add signal + new_signals = signals.concat(index); + } else { + // remove signal + new_signals = signals.filter( (idx) => idx !== index ); + } + + this.props.handleChange({ target: { id: this.props.controlId, value: new_signals } }); + } + + render() { + const simulationModel = this.props.simulationModels.find(m => m._id === this.state.widget.simulationModel); + + let signalsToRender = []; + + if (simulationModel != null) { + // If simulation model update the signals to render + signalsToRender = simulationModel ? simulationModel.outputMapping : []; + } + + return ( + + Signals + { + signalsToRender.length === 0 || !this.state.widget.hasOwnProperty(this.props.controlId)? ( + No signals available. + ) : ( + signalsToRender.map((signal, index) => ( + this.handleSignalChange(e.target.checked, index)}>{signal.name} + )) + ) + } + + ); + } +} + +export default EditWidgetSignalsControl; diff --git a/src/components/dialogs/edit-widget-simulation-control.js b/src/components/dialogs/edit-widget-simulation-control.js new file mode 100644 index 0000000..3ad0642 --- /dev/null +++ b/src/components/dialogs/edit-widget-simulation-control.js @@ -0,0 +1,60 @@ +/** + * File: edit-widget-simulation-control.js + * Author: Ricardo Hernandez-Montoya + * Date: 03.04.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + **********************************************************************************/ + +import React, { Component } from 'react'; +import { FormGroup, FormControl, ControlLabel } from 'react-bootstrap'; + +class EditWidgetSimulationControl extends Component { + constructor(props) { + super(props); + + this.state = { + widget: { + simulationModel: '' + } + }; + } + + componentWillReceiveProps(nextProps) { + // Update state's widget with props + this.setState({ widget: nextProps.widget }); + } + + render() { + return ( + + Simulation Model + this.props.handleChange(e)}> + { + this.props.simulationModels.length === 0 ? ( + + ) : ( + this.props.simulationModels.map((model, index) => ( + + ))) + } + + + ); + } +} + +export default EditWidgetSimulationControl; diff --git a/src/components/dialogs/edit-widget-text-control.js b/src/components/dialogs/edit-widget-text-control.js new file mode 100644 index 0000000..d46b98a --- /dev/null +++ b/src/components/dialogs/edit-widget-text-control.js @@ -0,0 +1,50 @@ +/** + * File: edit-widget-text-control.js + * Author: Ricardo Hernandez-Montoya + * Date: 21.04.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + **********************************************************************************/ + +import React, { Component } from 'react'; +import { FormGroup, FormControl, ControlLabel } from 'react-bootstrap'; + +class EditWidgetTextControl extends Component { + constructor(props) { + super(props); + + this.state = { + widget: {} + }; + } + + componentWillReceiveProps(nextProps) { + // Update state's widget with props + this.setState({ widget: nextProps.widget }); + } + + render() { + return ( + + {this.props.label} + this.props.handleChange(e)} /> + + + ); + } +} + +export default EditWidgetTextControl; diff --git a/src/components/dialogs/edit-widget-text-size-control.js b/src/components/dialogs/edit-widget-text-size-control.js new file mode 100644 index 0000000..0c66ebb --- /dev/null +++ b/src/components/dialogs/edit-widget-text-size-control.js @@ -0,0 +1,42 @@ +/** + * File: edit-widget-text-size-control.js + * Author: Ricardo Hernandez-Montoya + * Date: 29.07.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + **********************************************************************************/ + +import React from 'react'; +import { FormGroup, FormControl, ControlLabel } from 'react-bootstrap'; + +class EditWidgetTextSizeControl extends React.Component { + render() { + const sizes = [11, 12, 14, 16, 18, 20, 22, 24, 28, 32, 36, 40, 46, 52, 60, 72]; + + return ( + + Text size + this.props.handleChange(e)}> + {sizes.map((size, index) => ( + + ))} + + + ); + } +} + +export default EditWidgetTextSizeControl; \ No newline at end of file diff --git a/src/components/dialogs/edit-widget-time-control.js b/src/components/dialogs/edit-widget-time-control.js new file mode 100644 index 0000000..8f6434d --- /dev/null +++ b/src/components/dialogs/edit-widget-time-control.js @@ -0,0 +1,52 @@ +/** + * File: edit-widget-time-control.js + * Author: Ricardo Hernandez-Montoya + * Date: 13.04.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + **********************************************************************************/ + +import React, { Component } from 'react'; +import { FormGroup, FormControl, ControlLabel, HelpBlock } from 'react-bootstrap'; + +class EditWidgetTimeControl extends Component { + constructor(props) { + super(props); + + this.state = { + widget: { + time: 0 + } + }; + } + + componentWillReceiveProps(nextProps) { + this.setState({ widget: nextProps.widget }); + } + + render() { + + return ( + + Time + this.props.handleChange(e)} /> + Time in seconds + + ); + } +} + +export default EditWidgetTimeControl; diff --git a/src/components/dialogs/edit-widget.js b/src/components/dialogs/edit-widget.js new file mode 100644 index 0000000..95e20c7 --- /dev/null +++ b/src/components/dialogs/edit-widget.js @@ -0,0 +1,146 @@ +/** + * File: edit-widget.js + * Author: Markus Grigull + * Date: 08.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +//import { FormGroup, FormControl, ControlLabel } from 'react-bootstrap'; + +import Dialog from './dialog'; + +import createControls from './edit-widget-control-creator'; + +class EditWidgetDialog extends React.Component { + valid = true; + + constructor(props) { + super(props); + + this.state = { + temporal: { + name: '', + simulationModel: '', + signal: 0 + } + }; + } + + onClose(canceled) { + if (canceled === false) { + if (this.valid) { + this.props.onClose(this.state.temporal); + } + } else { + this.props.onClose(); + } + } + + assignAspectRatio(changeObject, fileId) { + // get aspect ratio of file + const file = this.props.files.find(element => element._id === fileId); + + // scale width to match aspect + const aspectRatio = file.dimensions.width / file.dimensions.height; + changeObject.width = this.state.temporal.height * aspectRatio; + + return changeObject; + } + + handleChange(e) { + if (e.constructor === Array) { + // Every property in the array will be updated + let changes = e.reduce( (changesObject, event) => { + changesObject[event.target.id] = event.target.value; + + return changesObject; + }, {}); + + this.setState({ temporal: Object.assign({}, this.state.temporal, changes ) }); + } else { + let changeObject = {}; + if (e.target.id === 'lockAspect') { + changeObject[e.target.id] = e.target.checked; + + // correct image aspect if turned on + if (e.target.checked) { + changeObject = this.assignAspectRatio(changeObject, this.state.temporal.file); + } + } else if (e.target.id === 'file') { + changeObject[e.target.id] = e.target.value; + + // get file and update size (if it's an image) + if ('lockAspect' in this.state.temporal && this.state.temporal.lockAspect) { + changeObject = this.assignAspectRatio(changeObject, e.target.value); + } + } else if (e.target.type === 'checkbox') { + changeObject[e.target.id] = e.target.checked; + } else if (e.target.type === 'number') { + changeObject[e.target.id] = Number(e.target.value); + } else { + changeObject[e.target.id] = e.target.value; + } + + this.setState({ temporal: Object.assign({}, this.state.temporal, changeObject ) }); + } + } + + resetState() { + var widget_data = Object.assign({}, this.props.widget); + this.setState({ temporal: widget_data }); + } + + validateForm(target) { + // check all controls + var name = true; + + if (this.state.name === '') { + name = false; + } + + //this.valid = name; + this.valid = true; + + // return state to control + if (target === 'name') return name ? "success" : "error"; + } + + render() { + let controls = null; + if (this.props.widget) { + controls = createControls( + this.props.widget.type, + this.state.temporal, + this.props.sessionToken, + this.props.files, + (id) => this.validateForm(id), + this.props.simulationModels, + (e) => this.handleChange(e)); + } + + return ( + this.onClose(c)} onReset={() => this.resetState()} valid={this.valid}> +
+ { controls || '' } +
+
+ ); + } +} + +export default EditWidgetDialog; diff --git a/src/components/dialogs/import-simulation-model.js b/src/components/dialogs/import-simulation-model.js new file mode 100644 index 0000000..137dfe9 --- /dev/null +++ b/src/components/dialogs/import-simulation-model.js @@ -0,0 +1,112 @@ +/** + * File: import-simulation-model.js + * Author: Markus Grigull + * Date: 03.09.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { FormGroup, FormControl, ControlLabel } from 'react-bootstrap'; +import _ from 'lodash'; + +import Dialog from './dialog'; + +class ImportSimulationModelDialog extends React.Component { + imported = false; + + constructor(props) { + super(props); + + this.state = { + model: {} + }; + } + + onClose = canceled => { + if (canceled) { + this.props.onClose(); + + return; + } + + this.props.onClose(this.state.model); + } + + resetState = () => { + this.setState({ + model: {} + }); + + this.imported = false; + } + + loadFile = event => { + // get file + const file = event.target.files[0]; + if (file.type.match('application/json') === false) { + return; + } + + // create file reader + const reader = new FileReader(); + const self = this; + + reader.onload = event => { + const model = JSON.parse(event.target.result); + + model.simulator = this.props.simulators.length > 0 ? this.props.simulators[0]._id : null; + + self.imported = true; + + this.setState({ model }); + }; + + reader.readAsText(file); + } + + handleSimulatorChange = event => { + const model = this.state.model; + + model.simulator = event.target.value; + + this.setState({ model }); + } + + render() { + return ( + +
+ + Simulation Model File + + + + + Simulator + + {this.props.simulators.map(simulator => ( + + ))} + + +
+
+ ); + } +} + +export default ImportSimulationModelDialog; diff --git a/src/components/dialogs/import-simulation.js b/src/components/dialogs/import-simulation.js new file mode 100644 index 0000000..e14eada --- /dev/null +++ b/src/components/dialogs/import-simulation.js @@ -0,0 +1,155 @@ +/** + * File: import-simulation.js + * Author: Markus Grigull + * Date: 03.09.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { FormGroup, FormControl, ControlLabel } from 'react-bootstrap'; + +import Dialog from './dialog'; +import ParametersEditor from '../parameters-editor'; + +class ImportSimulationDialog extends React.Component { + valid = false; + imported = false; + + constructor(props) { + super(props); + + this.state = { + name: '', + models: [], + startParameters: {} + }; + } + + onClose = canceled => { + if (canceled) { + if (this.props.onClose != null) { + this.props.onClose(); + } + + return; + } + + if (this.valid && this.props.onClose != null) { + this.props.onClose(this.state); + } + } + + handleChange(e, index) { + if (e.target.id === 'simulator') { + const models = this.state.models; + models[index].simulator = JSON.parse(e.target.value); + + this.setState({ models }); + + return; + } + + this.setState({ [e.target.id]: e.target.value }); + } + + resetState = () => { + this.setState({ name: '', models: [], startParameters: {} }); + + this.imported = false; + } + + loadFile = event => { + const file = event.target.files[0]; + + if (!file.type.match('application/json')) { + return; + } + + // create file reader + const reader = new FileReader(); + const self = this; + + reader.onload = onloadEvent => { + const simulation = JSON.parse(onloadEvent.target.result); + + // simulation.models.forEach(model => { + // model.simulator = { + // node: self.props.nodes[0]._id, + // simulator: 0 + // }; + // }); + + self.imported = true; + self.valid = true; + self.setState({ name: simulation.name, models: simulation.models, startParameters: simulation.startParameters }); + }; + + reader.readAsText(file); + } + + validateForm(target) { + // check all controls + let name = true; + + if (this.state.name === '') { + name = false; + } + + this.valid = name; + + // return state to control + if (target === 'name') return name ? "success" : "error"; + } + + render() { + return +
+ + Simulation File + + + + + Name + this.handleChange(e)} /> + + + + + Start Parameters + + + + + {/* {this.state.models.map((model, index) => ( + + {model.name} - Simulator + this.handleChange(e, index)}> + {this.props.nodes.map(node => ( + node.simulators.map((simulator, index) => ( + + )) + ))} + + + ))} */} +
+
; + } +} + +export default ImportSimulationDialog; diff --git a/src/components/dialogs/import-simulator.js b/src/components/dialogs/import-simulator.js new file mode 100644 index 0000000..8320572 --- /dev/null +++ b/src/components/dialogs/import-simulator.js @@ -0,0 +1,146 @@ +/** + * File: new-simulator.js + * Author: Markus Grigull + * Date: 27.03.2018 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { FormGroup, FormControl, ControlLabel } from 'react-bootstrap'; +import _ from 'lodash'; + +import Dialog from './dialog'; + +class ImportSimulatorDialog extends React.Component { + valid = false; + imported = false; + + constructor(props) { + super(props); + + this.state = { + name: '', + endpoint: '', + uuid: '' + }; + } + + onClose(canceled) { + if (canceled === false) { + if (this.valid) { + const data = { + properties: { + name: this.state.name + }, + uuid: this.state.uuid + }; + + if (this.state.endpoint != null && this.state.endpoint !== "" && this.state.endpoint !== 'http://') { + data.properties.endpoint = this.state.endpoint; + } + + this.props.onClose(data); + } + } else { + this.props.onClose(); + } + } + + handleChange(e) { + this.setState({ [e.target.id]: e.target.value }); + } + + resetState() { + this.setState({ name: '', endpoint: 'http://', uuid: '' }); + } + + loadFile(fileList) { + // get file + const file = fileList[0]; + if (!file.type.match('application/json')) { + return; + } + + // create file reader + const reader = new FileReader(); + const self = this; + + reader.onload = function(event) { + // read simulator + const simulator = JSON.parse(event.target.result); + self.imported = true; + self.setState({ + name: _.get(simulator, 'properties.name') || _.get(simulator, 'rawProperties.name'), + endpoint: _.get(simulator, 'properties.endpoint') || _.get(simulator, 'rawProperties.endpoint'), + uuid: simulator.uuid + }); + }; + + reader.readAsText(file); + } + + validateForm(target) { + // check all controls + let name = true; + let uuid = true; + + if (this.state.name === '') { + name = false; + } + + if (this.state.uuid === '') { + uuid = false; + } + + this.valid = name || uuid; + + // return state to control + if (target === 'name') return name ? "success" : "error"; + if (target === 'uuid') return uuid ? "success" : "error"; + } + + render() { + return ( + this.onClose(c)} onReset={() => this.resetState()} valid={this.valid}> +
+ + Simulator File + this.loadFile(e.target.files)} /> + + + + Name + this.handleChange(e)} /> + + + + Endpoint + this.handleChange(e)} /> + + + + UUID + this.handleChange(e)} /> + + +
+
+ ); + } +} + +export default ImportSimulatorDialog; \ No newline at end of file diff --git a/src/components/dialogs/import-visualization.js b/src/components/dialogs/import-visualization.js new file mode 100644 index 0000000..5d276f9 --- /dev/null +++ b/src/components/dialogs/import-visualization.js @@ -0,0 +1,136 @@ +/** + * File: import-simulator.js + * Author: Markus Grigull + * Date: 04.04.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { FormGroup, FormControl, ControlLabel } from 'react-bootstrap'; + +import Dialog from './dialog'; + +class ImportVisualizationDialog extends React.Component { + valid = false; + imported = false; + + constructor(props) { + super(props); + + this.state = { + name: '', + widgets: [], + grid: 0 + }; + } + + onClose(canceled) { + if (canceled === false) { + this.props.onClose(this.state); + } else { + this.props.onClose(); + } + } + + handleChange(e, index) { + this.setState({ [e.target.id]: e.target.value }); + } + + resetState() { + this.setState({ name: '', widgets: [], grid: 0 }); + + this.imported = false; + } + + loadFile(fileList) { + // get file + const file = fileList[0]; + if (!file.type.match('application/json')) { + return; + } + + // create file reader + var reader = new FileReader(); + var self = this; + + reader.onload = function(event) { + // read simulator + const visualization = JSON.parse(event.target.result); + + let defaultSimulator = ""; + if (self.props.simulation.models != null) { + defaultSimulator = self.props.simulation.models[0].simulator; + } + + visualization.widgets.forEach(widget => { + switch (widget.type) { + case 'Value': + case 'Plot': + case 'Table': + case 'PlotTable': + case 'Gauge': + widget.simulator = defaultSimulator; + break; + + default: + break; + } + }); + + self.imported = true; + self.valid = true; + self.setState({ name: visualization.name, widgets: visualization.widgets, grid: visualization.grid }); + }; + + reader.readAsText(file); + } + + validateForm(target) { + // check all controls + let name = true; + + if (this.state.name === '') { + name = false; + } + + this.valid = name; + + // return state to control + if (target === 'name') return name ? "success" : "error"; + } + + render() { + return ( + this.onClose(c)} onReset={() => this.resetState()} valid={this.valid}> +
+ + Visualization File + this.loadFile(e.target.files)} /> + + + + Name + this.handleChange(e)} /> + + +
+
+ ); + } +} + +export default ImportVisualizationDialog; diff --git a/src/components/dialogs/new-project.js b/src/components/dialogs/new-project.js new file mode 100644 index 0000000..babcf77 --- /dev/null +++ b/src/components/dialogs/new-project.js @@ -0,0 +1,103 @@ +/** + * File: new-project.js + * Author: Markus Grigull + * Date: 07.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { FormGroup, FormControl, ControlLabel } from 'react-bootstrap'; + +import Dialog from './dialog'; + +class NewProjectDialog extends React.Component { + valid: false; + + constructor(props) { + super(props); + + this.state = { + name: '', + simulation: '' + }; + } + + onClose(canceled) { + if (canceled === false) { + if (this.valid) { + this.props.onClose(this.state); + } + } else { + this.props.onClose(); + } + } + + handleChange(e) { + this.setState({ [e.target.id]: e.target.value }); + } + + resetState() { + this.setState({ + name: '', + simulation: this.props.simulations[0] != null ? this.props.simulations[0]._id : '' + }); + } + + validateForm(target) { + // check all controls + var name = true; + var simulation = true; + + if (this.state.name === '') { + name = false; + } + + if (this.state.simulation === '') { + simulation = false; + } + + this.valid = name && simulation; + + // return state to control + if (target === 'name') return name ? "success" : "error"; + else if (target === 'simulation') return simulation ? "success" : "error"; + } + + render() { + return ( + this.onClose(c)} onReset={() => this.resetState()} valid={this.valid}> +
+ + Name + this.handleChange(e)} /> + + + + Simulation + this.handleChange(e)}> + {this.props.simulations.map(simulation => ( + + ))} + + +
+
+ ); + } +} + +export default NewProjectDialog; diff --git a/src/components/dialogs/new-simulation.js b/src/components/dialogs/new-simulation.js new file mode 100644 index 0000000..b09559c --- /dev/null +++ b/src/components/dialogs/new-simulation.js @@ -0,0 +1,99 @@ +/** + * File: new-simulation.js + * Author: Markus Grigull + * Date: 04.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { FormGroup, FormControl, ControlLabel } from 'react-bootstrap'; + +import Dialog from './dialog'; +import ParametersEditor from '../parameters-editor'; + +class NewSimulationDialog extends React.Component { + valid = false; + + constructor(props) { + super(props); + + this.state = { + name: '', + startParameters: {} + }; + } + + onClose = canceled => { + if (canceled) { + if (this.props.onClose != null) { + this.props.onClose(); + } + + return; + } + + if (this.valid && this.props.onClose != null) { + this.props.onClose(this.state); + } + } + + handleChange = event => { + this.setState({ [event.target.id]: event.target.value }); + } + + resetState = () => { + this.setState({ name: '', startParameters: {} }); + } + + handleStartParametersChange = startParameters => { + this.setState({ startParameters }); + } + + validateForm(target) { + // check all controls + let name = true; + + if (this.state.name === '') { + name = false; + } + + this.valid = name; + + // return state to control + if (target === 'name') return name ? "success" : "error"; + } + + render() { + return +
+ + Name + + + + + + Start Parameters + + + +
+
; + } +} + +export default NewSimulationDialog; diff --git a/src/components/dialogs/new-simulator.js b/src/components/dialogs/new-simulator.js new file mode 100644 index 0000000..1eb5b34 --- /dev/null +++ b/src/components/dialogs/new-simulator.js @@ -0,0 +1,122 @@ +/** + * File: new-simulator.js + * Author: Markus Grigull + * Date: 02.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { FormGroup, FormControl, ControlLabel } from 'react-bootstrap'; + +import Dialog from './dialog'; + +class NewSimulatorDialog extends React.Component { + valid = false; + + constructor(props) { + super(props); + + this.state = { + name: '', + endpoint: '', + uuid: '' + }; + } + + onClose(canceled) { + if (canceled === false) { + if (this.valid) { + const data = { + properties: { + name: this.state.name + }, + uuid: this.state.uuid + }; + + if (this.state.endpoint != null && this.state.endpoint !== "" && this.state.endpoint !== 'http://') { + data.properties.endpoint = this.state.endpoint; + } + + this.props.onClose(data); + } + } else { + this.props.onClose(); + } + } + + handleChange(e) { + this.setState({ [e.target.id]: e.target.value }); + } + + resetState() { + this.setState({ name: '', endpoint: 'http://', uuid: this.uuidv4()}); + } + + validateForm(target) { + // check all controls + let name = true; + let uuid = true; + + if (this.state.name === '') { + name = false; + } + + if (this.state.uuid === '') { + uuid = false; + } + + this.valid = name && uuid; + + // return state to control + if (target === 'name') return name ? "success" : "error"; + if (target === 'uuid') return uuid ? "success" : "error"; + } + + uuidv4() { + return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { + // eslint-disable-next-line + var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8); + return v.toString(16); + }); + } + + render() { + return ( + this.onClose(c)} onReset={() => this.resetState()} valid={this.valid}> +
+ + Name + this.handleChange(e)} /> + + + + Endpoint + this.handleChange(e)} /> + + + + UUID + this.handleChange(e)} /> + + +
+
+ ); + } +} + +export default NewSimulatorDialog; diff --git a/src/components/dialogs/new-user.js b/src/components/dialogs/new-user.js new file mode 100644 index 0000000..f3cf20d --- /dev/null +++ b/src/components/dialogs/new-user.js @@ -0,0 +1,116 @@ +/** + * File: new-user.js + * Author: Ricardo Hernandez-Montoya + * Date: 02.05.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { FormGroup, FormControl, ControlLabel, HelpBlock } from 'react-bootstrap'; + +import Dialog from './dialog'; + +class NewUserDialog extends React.Component { + valid: false; + + constructor(props) { + super(props); + + this.state = { + username: '', + mail: '', + role: 'admin', + password: '' + }; + } + + onClose(canceled) { + if (canceled === false) { + if (this.valid) { + this.props.onClose(this.state); + } + } else { + this.props.onClose(); + } + } + + handleChange(e) { + this.setState({ [e.target.id]: e.target.value }); + } + + resetState() { + this.setState({ + username: '', + mail: '', + role: 'admin', + password: '' + }); + } + + validateForm(target) { + // check all controls + let username = this.state.username !== '' && this.state.username.length >= 3; + let password = this.state.password !== ''; + + this.valid = username && password; + + // return state to control + switch(target) { + case 'username': + return username ? "success" : "error"; + case 'password': + return password ? "success" : "error"; + default: + return "success"; + } + } + + render() { + return ( + this.onClose(c)} onReset={() => this.resetState()} valid={this.valid}> +
+ + Username + this.handleChange(e)} /> + + Min 3 characters. + + + E-mail + this.handleChange(e)} /> + + + + Password + this.handleChange(e)} /> + + + + Role + this.handleChange(e)}> + + + + + +
+
+ ); + } +} + +export default NewUserDialog; diff --git a/src/components/dialogs/new-visualization.js b/src/components/dialogs/new-visualization.js new file mode 100644 index 0000000..70b45ec --- /dev/null +++ b/src/components/dialogs/new-visualization.js @@ -0,0 +1,87 @@ +/** + * File: new-visualization.js + * Author: Markus Grigull + * Date: 03.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { FormGroup, FormControl, ControlLabel } from 'react-bootstrap'; + +import Dialog from './dialog'; + +class NewVisualzationDialog extends React.Component { + valid: false; + + constructor(props) { + super(props); + + this.state = { + name: '' + } + } + + onClose(canceled) { + if (canceled === false) { + if (this.valid) { + this.props.onClose(this.state); + } + } else { + this.props.onClose(); + } + } + + handleChange(e) { + this.setState({ [e.target.id]: e.target.value }); + } + + resetState() { + this.setState({ name: '' }); + } + + validateForm(target) { + // check all controls + var name = true; + + if (this.state.name === '') { + name = false; + } + + this.valid = name; + + // return state to control + if (target === 'name') return name ? "success" : "error"; + + return "success"; + } + + render() { + return ( + this.onClose(c)} onReset={() => this.resetState()} valid={this.valid}> +
+ + Name + this.handleChange(e)} /> + + +
+
+ ); + } +} + +export default NewVisualzationDialog; diff --git a/src/components/dropzone.js b/src/components/dropzone.js new file mode 100644 index 0000000..7a9af88 --- /dev/null +++ b/src/components/dropzone.js @@ -0,0 +1,79 @@ +/** + * File: dropzone.js + * Author: Markus Grigull + * Date: 02.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { DropTarget } from 'react-dnd'; +import classNames from 'classnames'; + +const dropzoneTarget = { + drop(props, monitor, component) { + // get drop position + var position = monitor.getSourceClientOffset(); + var dropzoneRect = component.wrapper.getBoundingClientRect(); + position.x -= dropzoneRect.left; + position.y -= dropzoneRect.top; + + // Z-Index is one more the top most children + let foundZ = props.children.reduce( (maxZ, currentChildren) => { + if (currentChildren.props != null) { + // Is there a simpler way? Is not easy to expose a getter in a Container.create(Component) + let widget = currentChildren.props.data; + if (widget && widget.z) { + if (widget.z > maxZ) { + return widget.z; + } + } + } + + return maxZ; + }, 0); + position.z = foundZ >= 100? foundZ : ++foundZ; + + props.onDrop(monitor.getItem(), position); + } +}; + +function collect(connect, monitor) { + return { + connectDropTarget: connect.dropTarget(), + isOver: monitor.isOver(), + canDrop: monitor.canDrop() + }; +} + +class Dropzone extends React.Component { + render() { + var toolboxClass = classNames({ + 'box-content': true, + 'toolbox-dropzone': true, + 'toolbox-dropzone-active': this.props.isOver && this.props.canDrop && this.props.editing, + 'toolbox-dropzone-editing': this.props.editing + }); + + return this.props.connectDropTarget( +
this.wrapper = wrapper}> + {this.props.children} +
+ ); + } +} + +export default DropTarget('widget', dropzoneTarget, collect)(Dropzone); diff --git a/src/components/editable-header.js b/src/components/editable-header.js new file mode 100644 index 0000000..ff15d11 --- /dev/null +++ b/src/components/editable-header.js @@ -0,0 +1,108 @@ +/** + * File: header.js + * Author: Markus Grigull + * Date: 25.05.2018 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import PropTypes from 'prop-types'; +import { FormControl, Button } from 'react-bootstrap'; +import Icon from './icon'; + +class EditableHeader extends React.Component { + titleInput = null; + + constructor(props) { + super(props); + + this.state = { + editing: false, + title: props.title + }; + } + + componentWillReceiveProps(nextProps) { + this.setState({ title: nextProps.title }); + } + + edit = () => { + this.setState({ editing: true }); + } + + save = () => { + this.setState({ editing: false }); + + if (this.props.onChange != null) { + this.props.onChange(this.state.title); + } + } + + cancel = () => { + this.setState({ editing: false, title: this.props.title }); + } + + onChange = event => { + this.setState({ title: event.target.value }); + } + + render() { + const wrapperStyle= { + float: 'left' + }; + + const iconStyle = { + float: 'left', + + marginLeft: '10px', + marginTop: '25px', + marginBottom: '20px' + }; + + if (this.state.editing) { + const editStyle = { + maxWidth: '500px', + + marginTop: '10px' + }; + + return
+
+ + + + + +
; + } + + return
+

+ {this.state.title} +

+ + +
; + } +} + +EditableHeader.propTypes = { + title: PropTypes.string.isRequired, + onChange: PropTypes.func +}; + +export default EditableHeader; diff --git a/src/components/footer.js b/src/components/footer.js new file mode 100644 index 0000000..e036516 --- /dev/null +++ b/src/components/footer.js @@ -0,0 +1,34 @@ +/** + * File: footer.js + * Author: Markus Grigull + * Date: 02.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React, { Component } from 'react'; + +class Footer extends Component { + render() { + return ( + + ); + } +} + +export default Footer; diff --git a/src/components/grid.js b/src/components/grid.js new file mode 100644 index 0000000..16e8fa5 --- /dev/null +++ b/src/components/grid.js @@ -0,0 +1,42 @@ +/** + * File: grid.js + * Author: Markus Grigull + * Date: 27.07.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; + +class Grid extends React.Component { + render() { + if (this.props.disabled) return false; + + return ( + + + + + + + + + + ); + } +} + +export default Grid; diff --git a/src/components/header-menu.js b/src/components/header-menu.js new file mode 100644 index 0000000..b2daf0e --- /dev/null +++ b/src/components/header-menu.js @@ -0,0 +1,43 @@ +/** + * File: header-menu.js + * Author: Markus Grigull + * Date: 17.08.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { Button } from 'react-bootstrap'; +import { NavLink } from 'react-router-dom'; + +export default class HeaderMenu extends React.Component { + render() { + return
+ + +
    +
  • Home
  • +
  • Projects
  • +
  • Simulations
  • +
  • Simulators
  • + { this.props.currentRole === 'admin' ? +
  • User Management
  • : '' + } +
  • Logout
  • +
+
; + } +} diff --git a/src/components/header.js b/src/components/header.js new file mode 100644 index 0000000..710ea9b --- /dev/null +++ b/src/components/header.js @@ -0,0 +1,43 @@ +/** + * File: header.js + * Author: Markus Grigull + * Date: 02.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { Col, Button } from 'react-bootstrap'; +import Icon from './icon'; + +class Header extends React.Component { + render() { + return ( +
+ +

VILLASweb

+ + + {this.props.showMenuButton && + + } + +
+ ); + } +} + +export default Header; diff --git a/src/components/home.js b/src/components/home.js new file mode 100644 index 0000000..86ea56b --- /dev/null +++ b/src/components/home.js @@ -0,0 +1,92 @@ +/** + * File: home.js + * Author: Markus Grigull + * Date: 02.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; + +import { Link } from 'react-router-dom'; + +import RestAPI from '../api/rest-api'; + +import config from '../config'; + +class Home extends React.Component { + constructor(props) { + super(props); + this.state = {}; + } + + getCounts(type) { + if (this.state.hasOwnProperty('counts')) + return this.state.counts[type]; + else + return '?'; + } + + componentWillMount() { + RestAPI.get('/api/v1/counts').then(response => { + this.setState({ counts: response }); + }); + } + + render() { + return ( +
+ Logo VILLASweb +

Home

+

+ Welcome to {config.instance}!
+ VILLASweb is a frontend for distributed real-time simulation hosted by {config.admin.name}. +

+

+ This instance is hosting {this.getCounts('projects')} projects consisting of {this.getCounts('simulators')} simulators, {this.getCounts('visualizations')} visualizations and {this.getCounts('simulations')} simulations. + A total of {this.getCounts('users')} users are registered.
+

+

Credits

+

VILLASweb is developed by the Institute for Automation of Complex Power Systems at the RWTH Aachen University.

+ +

Links

+ +

Funding

+

The development of VILLASframework projects have received funding from

+
    +
  • RESERVE a European Union’s Horizon 2020 research and innovation programme under grant agreement No 727481
  • +
  • JARA-ENERGY. Jülich-Aachen Research Alliance (JARA) is an initiative of RWTH Aachen University and Forschungszentrum Jülich.
  • +
+ Logo EU + Logo EU + Logo ACS + { + //Logo JARA + } +
+ ); + } +} + +export default Home; diff --git a/src/components/icon.js b/src/components/icon.js new file mode 100644 index 0000000..1cff82a --- /dev/null +++ b/src/components/icon.js @@ -0,0 +1,39 @@ +/** + * File: icon.js + * Author: Steffen Vogel + * Date: 09.06.2018 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; + +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' + +import { library } from '@fortawesome/fontawesome-svg-core'; +import { fas } from '@fortawesome/free-solid-svg-icons'; +//import '@fortawesome/free-regular-svg-icons'; + +library.add(fas); + +class Icon extends React.Component { + + render() { + return + } +} + +export default Icon; diff --git a/src/components/login-form.js b/src/components/login-form.js new file mode 100644 index 0000000..7e09091 --- /dev/null +++ b/src/components/login-form.js @@ -0,0 +1,101 @@ +/** + * File: login-form.js + * Author: Markus Grigull + * Date: 15.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React, { Component } from 'react'; +import { Form, Button, FormGroup, FormControl, ControlLabel, Col } from 'react-bootstrap'; + +import AppDispatcher from '../app-dispatcher'; + +class LoginForm extends Component { + constructor(props) { + super(props); + + this.state = { + username: '', + password: '', + disableLogin: true + } + } + + login(event) { + // prevent from submitting the form since we send an action + event.preventDefault(); + + // send login action + AppDispatcher.dispatch({ + type: 'users/login', + username: this.state.username, + password: this.state.password + }); + } + + handleChange(event) { + let disableLogin = this.state.disableLogin; + + if (event.target.id === 'username') { + disableLogin = this.state.password.length === 0 || event.target.value.length === 0; + } else if (event.target.id === 'password') { + disableLogin = this.state.username.length === 0 || event.target.value.length === 0; + } + + this.setState({ [event.target.id]: event.target.value, disableLogin }); + } + + render() { + return ( +
+ + + Username + + + this.handleChange(e)} /> + + + + + + Password + + + this.handleChange(e)} /> + + + + {this.props.loginMessage && +
+ + Error: {this.props.loginMessage} + +
+ } + + + + + + +
+ ); + } +} + +export default LoginForm; diff --git a/src/components/menu-sidebar.js b/src/components/menu-sidebar.js new file mode 100644 index 0000000..51d7d83 --- /dev/null +++ b/src/components/menu-sidebar.js @@ -0,0 +1,46 @@ +/** + * File: menu-sidebar.js + * Author: Markus Grigull + * Date: 02.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { NavLink } from 'react-router-dom'; + +class SidebarMenu extends React.Component { + render() { + return ( +
+

Menu

+ +
    +
  • Home
  • +
  • Projects
  • +
  • Simulations
  • +
  • Simulators
  • + { this.props.currentRole === 'admin' ? +
  • Users
  • : '' + } +
  • Logout
  • +
+
+ ); + } +} + +export default SidebarMenu; diff --git a/src/components/parameters-editor.js b/src/components/parameters-editor.js new file mode 100644 index 0000000..9f17e7e --- /dev/null +++ b/src/components/parameters-editor.js @@ -0,0 +1,82 @@ +/** + * File: header.js + * Author: Markus Grigull + * Date: 06.06.2018 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import PropTypes from 'prop-types'; +import JsonView from 'react-json-view'; + +class ParametersEditor extends React.Component { + onAdd = event => { + if (this.props.onChange != null) { + this.props.onChange(JSON.parse(JSON.stringify(event.updated_src))); + } + } + + onEdit = event => { + if (this.props.onChange != null) { + this.props.onChange(JSON.parse(JSON.stringify(event.updated_src))); + } + } + + onDelete = event => { + if (this.props.onChange != null) { + this.props.onChange(JSON.parse(JSON.stringify(event.updated_src))); + } + } + + render() { + const containerStyle = { + minHeight: '100px', + + paddingTop: '5px', + paddingBottom: '5px', + paddingLeft: '8px', + + border: '1px solid lightgray' + }; + + return
+ +
; + } +} + +ParametersEditor.propTypes = { + content: PropTypes.object, + onChange: PropTypes.func, + disabled: PropTypes.bool +}; + +ParametersEditor.defaultProps = { + content: {}, + disabled: false +}; + +export default ParametersEditor; diff --git a/src/components/signal-mapping.js b/src/components/signal-mapping.js new file mode 100644 index 0000000..815d90c --- /dev/null +++ b/src/components/signal-mapping.js @@ -0,0 +1,131 @@ +/** + * File: signalMapping.js + * Author: Markus Grigull + * Date: 10.08.2018 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import PropTypes from 'prop-types'; +import { FormGroup, FormControl, ControlLabel, HelpBlock } from 'react-bootstrap'; +import validator from 'validator'; + +import Table from './table'; +import TableColumn from './table-column'; + +class SignalMapping extends React.Component { + constructor(props) { + super(props); + + var length = props.length; + if (length === undefined) + length = 1; + + this.state = { + length: length, + signals: props.signals + }; + } + + componentWillReceiveProps(nextProps) { + if (nextProps.length === this.state.length && nextProps.signals === this.state.signals) { + return; + } + + this.setState({ length: nextProps.length, signals: nextProps.signals }); + } + + validateLength(){ + const valid = validator.isInt(this.state.length + '', { min: 1, max: 100 }); + + return valid ? 'success' : 'error'; + } + + handleLengthChange = event => { + const length = event.target.value; + + // update signals to represent length + const signals = this.state.signals; + + if (this.state.length < length) { + while (signals.length < length) { + signals.push({ name: 'Signal', type: 'Type' }); + } + } else { + signals.splice(length, signals.length - length); + } + + // save updated state + this.setState({ length, signals }); + + if (this.props.onChange != null) { + this.props.onChange(length, signals); + } + } + + handleMappingChange = (event, row, column) => { + const signals = this.state.signals; + + const length = this.state.length; + + if (column === 1) { + signals[row].name = event.target.value; + } else if (column === 2) { + signals[row].type = event.target.value; + } + + this.setState({ length, signals }); + + if (this.props.onChange != null) { + this.props.onChange(this.state.length, signals); + } + } + + render() { + return
+ + {this.props.name} Length + + + + + + {this.props.name} Mapping + Click name or type cell to edit + + + + +
+
+
; + } +} + +SignalMapping.propTypes = { + name: PropTypes.string, + length: PropTypes.number, + signals: PropTypes.arrayOf( + PropTypes.shape({ + name: PropTypes.string.isRequired, + type: PropTypes.string.isRequired + }) + ), + onChange: PropTypes.func +}; + +export default SignalMapping; diff --git a/src/components/simulator-action.js b/src/components/simulator-action.js new file mode 100644 index 0000000..aef6625 --- /dev/null +++ b/src/components/simulator-action.js @@ -0,0 +1,68 @@ +/** + * File: simulator-actionm.js + * Author: Markus Grigull + * Date: 12.04.2018 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { Button, DropdownButton, MenuItem } from 'react-bootstrap'; + +class SimulatorAction extends React.Component { + constructor(props) { + super(props); + + this.state = { + selectedAction: null + }; + } + + componentWillReceiveProps(nextProps) { + if (this.state.selectedAction == null) { + if (nextProps.actions != null && nextProps.actions.length > 0) { + this.setState({ selectedAction: nextProps.actions[0] }); + } + } + } + + setAction = id => { + // search action + for (let action of this.props.actions) { + if (action.id === id) { + this.setState({ selectedAction: action }); + } + } + } + + render() { + const actionList = this.props.actions.map(action => ( + + {action.title} + + )); + + return
+ + {actionList} + + + +
; + } +} + +export default SimulatorAction; diff --git a/src/components/table-column.js b/src/components/table-column.js new file mode 100644 index 0000000..1aafc2e --- /dev/null +++ b/src/components/table-column.js @@ -0,0 +1,51 @@ +/** + * File: table-column.js + * Author: Markus Grigull + * Date: 06.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React, { Component } from 'react'; + +class TableColumn extends Component { + static defaultProps = { + title: '', + modifier: null, + width: null, + editButton: false, + deleteButton: false, + exportButton: false, + link: '/', + linkKey: '', + dataIndex: false, + inlineEditable: false, + clickable: false, + labelKey: null, + checkbox: false, + checkboxKey: '' + }; + + render() { + return ( + + {this.props.title} + + ); + } +} + +export default TableColumn; diff --git a/src/components/table.js b/src/components/table.js new file mode 100644 index 0000000..0eaac85 --- /dev/null +++ b/src/components/table.js @@ -0,0 +1,222 @@ +/** + * File: table.js + * Author: Markus Grigull + * Date: 02.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React, { Component } from 'react'; +import _ from 'lodash'; +import { Table, Button, FormControl, Label, Checkbox } from 'react-bootstrap'; +import { Link } from 'react-router-dom'; +import Icon from './icon'; + +class CustomTable extends Component { + constructor(props) { + super(props); + + this.activeInput = null; + + this.state = { + rows: this.getRows(props), + editCell: [ -1, -1 ] + }; + } + + static defaultProps = { + width: null + }; + + onClick(event, row, column) { + this.setState({ editCell: [ column, row ]}); // x, y + } + + addCell(data, index, child) { + // add data to cell + let content = null; + + if ('dataKeys' in child.props) { + for (let key of child.props.dataKeys) { + if (_.get(data, key) != null) { + content = _.get(data, key); + break; + } + } + } else if ('dataKey' in child.props) { + content = _.get(data, child.props.dataKey); + } + + const modifier = child.props.modifier; + if (modifier && content != null) { + content = modifier(content); + } + + let cell = []; + if (content != null) { + content = content.toString(); + + // check if cell should be a link + const linkKey = child.props.linkKey; + if (linkKey && data[linkKey] != null) { + cell.push({content}); + } else if (child.props.clickable) { + cell.push(); + } else { + cell.push(content); + } + } + + // add label to content + const labelKey = child.props.labelKey; + if (labelKey && data[labelKey] != null) { + var labelContent = data[labelKey]; + + if (child.props.labelModifier) { + labelContent = child.props.labelModifier(labelContent, data); + } + + cell.push( ); + } + + if (child.props.dataIndex) { + cell.push(index); + } + + // add buttons + if (child.props.editButton) { + cell.push(); + } + + if (child.props.deleteButton) { + cell.push(); + } + + if (child.props.checkbox) { + const checkboxKey = this.props.checkboxKey; + + cell.push( child.props.onChecked(index, e)} />); + } + + if (child.props.exportButton) { + cell.push(); + } + + return cell; + } + + componentWillReceiveProps(nextProps) { + const rows = this.getRows(nextProps); + + this.setState({ rows }); + } + + componentDidUpdate() { + // A cell will not be selected at initial render, hence no need to call this in 'componentDidMount' + if (this.activeInput) { + this.activeInput.focus(); + } + } + + onCellFocus(index) { + // When a cell focus is detected, update the current state in order to uncover the input element + this.setState({ editCell: [ index.cell, index.row ]}); + } + + cellLostFocus() { + // Reset cell selection state + this.setState({ editCell: [ -1, -1 ] }); + } + + getRows(props) { + if (props.data == null) { + return []; + } + + return props.data.map((data, index) => { + // check if multiple columns + if (Array.isArray(props.children) === false) { + // table only has a single column + return [ this.addCell(data, index, props.children) ]; + } + + const row = []; + + for (let child of props.children) { + row.push(this.addCell(data, index, child)); + } + + return row; + }); + } + + render() { + // get children + let children = this.props.children; + if (Array.isArray(this.props.children) === false) { + children = [ children ]; + } + + return ( + + + + {this.props.children} + + + + { + this.state.rows.map((row, rowIndex) => ( + + { + row.map((cell, cellIndex) => { + + let isCellInlineEditable = children[cellIndex].props.inlineEditable === true; + + let tabIndex = isCellInlineEditable? 0 : -1; + + let evtHdls = isCellInlineEditable ? { + onCellClick: (event) => this.onClick(event, rowIndex, cellIndex), + onCellFocus: () => this.onCellFocus({cell: cellIndex, row: rowIndex}), + onCellBlur: () => this.cellLostFocus() + } : { + onCellClick: () => {}, + onCellFocus: () => {}, + onCellBlur: () => {} + }; + + return () + }) + } + )) + } + +
+ {(this.state.editCell[0] === cellIndex && this.state.editCell[1] === rowIndex ) ? ( + children[cellIndex].props.onInlineChange(event, rowIndex, cellIndex)} inputRef={ref => { this.activeInput = ref; }} /> + ) : ( + + {cell.map((element, elementIndex) => ( + {element} + ))} + + )} +
+ ); + } +} + +export default CustomTable; diff --git a/src/components/toolbox-item.js b/src/components/toolbox-item.js new file mode 100644 index 0000000..a4f5b14 --- /dev/null +++ b/src/components/toolbox-item.js @@ -0,0 +1,78 @@ +/** + * File: toolbox-item.js + * Author: Markus Grigull + * Date: 02.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { DragSource } from 'react-dnd'; +import classNames from 'classnames'; +import Icon from './icon'; + +const toolboxItemSource = { + beginDrag(props) { + return { + name: props.name + }; + } +}; + +function collect(connect, monitor) { + return { + connectDragSource: connect.dragSource(), + isDragging: monitor.isDragging() + } +} + +class ToolboxItem extends React.Component { + static defaultProps = { + disabled: false + }; + + render() { + var itemClass = classNames({ + 'toolbox-item': true, + 'toolbox-item-dragging': this.props.isDragging, + 'toolbox-item-disabled': this.props.disabled + }); + var dropEffect = 'copy'; + + if (this.props.disabled === false) { + return this.props.connectDragSource( +
+ + {this.props.icon && } + {this.props.name} + +
+ , {dropEffect}); + } + else { + return ( +
+ + {this.props.icon && } + {this.props.name} + +
+ ); + } + } +} + +export default DragSource('widget', toolboxItemSource, collect)(ToolboxItem); diff --git a/src/components/widget-factory.js b/src/components/widget-factory.js new file mode 100644 index 0000000..4ab6731 --- /dev/null +++ b/src/components/widget-factory.js @@ -0,0 +1,202 @@ +/** + * File: widget-factory.js + * Description: A factory to create and pre-configure widgets + * Author: Ricardo Hernandez-Montoya + * Date: 02.03.2017 + * Copyright: 2018, Institute for Automation of Complex Power Systems, EONERC + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import WidgetSlider from './widgets/slider'; + +class WidgetFactory { + + static createWidgetOfType(type, position, defaultSimulationModel = null) { + + let widget = { + name: 'Name', + type: type, + width: 100, + height: 100, + x: position.x, + y: position.y, + z: position.z, + locked: false + }; + + // set type specific properties + switch(type) { + case 'CustomAction': + widget.actions = [ + { + action: 'stop' + }, + { + action: 'pause', + model: { + url: 'ftp://user:pass@example.com/projectA/model.zip' + }, + parameters: { + timestep: 50e-6 + } + } + ]; + widget.name = 'Action'; + widget.icon = 'star'; + widget.width = 100; + widget.height = 50; + widget.simulationModel = defaultSimulationModel; + break; + case 'Action': + widget.simulationModel = defaultSimulationModel; + break; + case 'Lamp': + widget.simulationModel = defaultSimulationModel; + widget.signal = 0; + widget.minWidth = 5; + widget.minHeight = 5; + widget.width = 20; + widget.height = 20; + widget.on_color = 6; + widget.off_color = 8; + widget.threshold = 0.5; + break; + case 'Value': + widget.simulationModel = defaultSimulationModel; + widget.signal = 0; + widget.minWidth = 70; + widget.minHeight = 20; + widget.width = 120; + widget.height = 30; + widget.textSize = 16; + widget.name = 'Value'; + widget.showUnit = false; + break; + case 'Plot': + widget.simulationModel = defaultSimulationModel; + widget.signals = [ 0 ]; + widget.ylabel = ''; + widget.time = 60; + widget.minWidth = 400; + widget.minHeight = 200; + widget.width = 400; + widget.height = 200; + widget.yMin = 0; + widget.yMax = 10; + widget.yUseMinMax = false; + break; + case 'Table': + widget.simulationModel = defaultSimulationModel; + widget.minWidth = 200; + widget.width = 300; + widget.height = 200; + break; + case 'Label': + widget.minWidth = 20; + widget.minHeight = 20; + widget.width = 100; + widget.height = 35; + widget.name = 'Label'; + widget.textSize = 32; + widget.fontColor = 0; + break; + case 'PlotTable': + widget.simulationModel = defaultSimulationModel; + widget.preselectedSignals = []; + widget.signals = []; // initialize selected signals + widget.ylabel = ''; + widget.minWidth = 200; + widget.minHeight = 100; + widget.width = 600; + widget.height = 300; + widget.time = 60; + widget.yMin = 0; + widget.yMax = 10; + widget.yUseMinMax = false; + break; + case 'Image': + widget.minWidth = 20; + widget.minHeight = 20; + widget.width = 200; + widget.height = 200; + widget.lockAspect = true; + break; + case 'Button': + widget.minWidth = 100; + widget.minHeight = 50; + widget.width = 100; + widget.height = 100; + widget.background_color = 1; + widget.font_color = 0; + widget.simulationModel = defaultSimulationModel; + widget.signal = 0; + break; + case 'Input': + widget.minWidth = 200; + widget.minHeight = 50; + widget.width = 200; + widget.height = 50; + widget.simulationModel = defaultSimulationModel; + widget.signal = 0; + break; + case 'Slider': + widget.minWidth = 380; + widget.minHeight = 30; + widget.width = 400; + widget.height = 50; + widget.orientation = WidgetSlider.OrientationTypes.HORIZONTAL.value; // Assign default orientation + widget.simulationModel = defaultSimulationModel; + widget.signal = 0; + break; + case 'Gauge': + widget.simulationModel = defaultSimulationModel; + widget.signal = 0; + widget.minWidth = 100; + widget.minHeight = 150; + widget.width = 150; + widget.height = 150; + widget.colorZones = false; + widget.zones = []; + widget.valueMin = 0; + widget.valueMax = 1; + widget.valueUseMinMax = false; + break; + case 'Box': + widget.minWidth = 50; + widget.minHeight = 50; + widget.width = 100; + widget.height = 100; + widget.border_color = 0; + widget.z = 0; + break; + case 'HTML': + widget.content = 'Hello World'; + break; + case 'Topology': + widget.width = 600; + widget.height = 400; + break; + + default: + widget.width = 100; + widget.height = 100; + } + return widget; + } +} + +export default WidgetFactory; diff --git a/src/components/widget-plot/plot-legend.js b/src/components/widget-plot/plot-legend.js new file mode 100644 index 0000000..4bde597 --- /dev/null +++ b/src/components/widget-plot/plot-legend.js @@ -0,0 +1,43 @@ +/** + * File: plot-legend.js + * Author: Ricardo Hernandez-Montoya + * Date: 10.04.2017 + * Copyright: 2018, Institute for Automation of Complex Power Systems, EONERC + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { scaleOrdinal, schemeCategory10 } from 'd3-scale'; + +class PlotLegend extends React.Component { + render() { + const colorScale = scaleOrdinal(schemeCategory10); + + return
+
    + {this.props.signals.map(signal => +
  • + {signal.name} + {signal.type} +
  • + )} +
+
; + } +} + +export default PlotLegend; diff --git a/src/components/widget-plot/plot.js b/src/components/widget-plot/plot.js new file mode 100644 index 0000000..a3f6d37 --- /dev/null +++ b/src/components/widget-plot/plot.js @@ -0,0 +1,211 @@ +/** + * File: plot.js + * Author: Ricardo Hernandez-Montoya + * Date: 10.04.2017 + * Copyright: 2018, Institute for Automation of Complex Power Systems, EONERC + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { scaleLinear, scaleTime, scaleOrdinal, schemeCategory10 } from 'd3-scale'; +import { extent } from 'd3-array'; +import { line } from 'd3-shape'; +import { axisBottom, axisLeft } from 'd3-axis'; +import { select } from 'd3-selection'; +import { timeFormat } from 'd3-time-format'; +import { format } from 'd3'; + +const topMargin = 10; +const bottomMargin = 25; +const leftMargin = 40; +const rightMargin = 10; + +let uniqueIdentifier = 0; + +class Plot extends React.Component { + constructor(props) { + super(props); + + // create dummy axes + let labelMargin = 0; + if (props.yLabel !== '') { + labelMargin = 30; + } + + const xScale = scaleTime().domain([Date.now() - props.time * 1000, Date.now()]).range([0, props.width - leftMargin - labelMargin - rightMargin]); + let yScale; + + if (props.yUseMinMax) { + yScale = scaleLinear().domain([props.yMin, props.yMax]).range([props.height + topMargin - bottomMargin, topMargin]); + } else { + yScale = scaleLinear().domain([0, 10]).range([props.height + topMargin - bottomMargin, topMargin]); + } + + const xAxis = axisBottom().scale(xScale).ticks(5).tickFormat(timeFormat("%M:%S")); + const yAxis = axisLeft().scale(yScale).ticks(5).tickFormat(format(".3s")); + + this.state = { + data: null, + lines: null, + xAxis, + yAxis, + labelMargin, + identifier: uniqueIdentifier++ + }; + } + + componentDidMount() { + this.createInterval(); + } + + componentWillUnmount() { + this.removeInterval(); + } + + componentWillReceiveProps(nextProps) { + if (nextProps.time !== this.props.time) { + this.createInterval(); + } + + let labelMargin = 0; + if (nextProps.yLabel !== '') { + labelMargin = 30; + } + + // check if data is invalid + if (nextProps.data == null || nextProps.data.length === 0 || nextProps.data[0].length === 0) { + // create empty plot axes + const xScale = scaleTime().domain([Date.now() - nextProps.time * 1000, Date.now()]).range([0, nextProps.width - leftMargin - labelMargin - rightMargin]); + let yScale; + + if (nextProps.yUseMinMax) { + yScale = scaleLinear().domain([nextProps.yMin, nextProps.yMax]).range([nextProps.height + topMargin - bottomMargin, topMargin]); + } else { + yScale = scaleLinear().domain([0, 10]).range([nextProps.height + topMargin - bottomMargin, topMargin]); + } + + const xAxis = axisBottom().scale(xScale).ticks(5).tickFormat(timeFormat("%M:%S")); + const yAxis = axisLeft().scale(yScale).ticks(5).tickFormat(format(".3s")); + + this.setState({ data: null, xAxis, yAxis, labelMargin }); + return; + } + + // only show data in requested time + let data = nextProps.data; + + const firstTimestamp = data[0][data[0].length - 1].x - (nextProps.time + 1) * 1000; + if (data[0][0].x < firstTimestamp) { + // only show data in range (+100 ms) + const index = data[0].findIndex(value => value.x >= firstTimestamp - 100); + data = data.map(values => values.slice(index)); + } + + this.setState({ data, labelMargin }); + } + + createInterval() { + this.removeInterval(); + + if (this.props.time < 30) { + this.interval = setInterval(this.tick, 50); + } else if (this.props.time < 120) { + this.interval = setInterval(this.tick, 100); + } else if (this.props.time < 300) { + this.interval = setInterval(this.tick, 200); + } else { + this.interval = setInterval(this.tick, 1000); + } + } + + removeInterval() { + if (this.interval != null) { + clearInterval(this.interval); + + this.interval = null; + } + } + + tick = () => { + if (this.state.data == null) { + this.setState({ lines: null }); + return; + } + + if (this.props.paused === true) { + return; + } + + // calculate yRange + let yRange = [0, 0]; + + if (this.props.yUseMinMax) { + yRange = [this.props.yMin, this.props.yMax]; + } else if (this.props.data.length > 0) { + yRange = [this.props.data[0][0].y, this.props.data[0][0].y]; + + this.props.data.forEach(values => { + const range = extent(values, p => p.y); + + if (range[0] < yRange[0]) yRange[0] = range[0]; + if (range[1] > yRange[1]) yRange[1] = range[1]; + }); + } + + // create scale functions for both axes + const xScale = scaleTime().domain([Date.now() - this.props.time * 1000, Date.now()]).range([0, this.props.width - leftMargin - this.state.labelMargin - rightMargin]); + const yScale = scaleLinear().domain(yRange).range([this.props.height + topMargin - bottomMargin, topMargin]); + + const xAxis = axisBottom().scale(xScale).ticks(5).tickFormat(timeFormat("%M:%S")); + const yAxis = axisLeft().scale(yScale).ticks(5).tickFormat(format(".3s")); + + // generate paths from data + const sparkLine = line().x(p => xScale(p.x)).y(p => yScale(p.y)); + const lineColor = scaleOrdinal(schemeCategory10); + + const lines = this.state.data.map((values, index) => ); + + this.setState({ lines, xAxis, yAxis }); + } + + render() { + const yLabelPos = { + x: 12, + y: this.props.height / 2 + } + + return + select(node).call(this.state.xAxis)} style={{ transform: `translateX(${leftMargin + this.state.labelMargin}px) translateY(${this.props.height + topMargin - bottomMargin}px)` }} /> + select(node).call(this.state.yAxis)} style={{ transform: `translateX(${leftMargin + this.state.labelMargin}px)` }} /> + + {this.props.yLabel} + Time [s] + + + + + + + + + {this.state.lines} + + ; + } +} + +export default Plot; diff --git a/src/components/widgets/action.js b/src/components/widgets/action.js new file mode 100644 index 0000000..24e105c --- /dev/null +++ b/src/components/widgets/action.js @@ -0,0 +1,48 @@ +/** + * File: action.js + * Author: Steffen Vogel + * Date: 17.06.2018 + * Copyright: 2018, Institute for Automation of Complex Power Systems, EONERC + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React, { Component } from 'react'; +import { Button, ButtonGroup } from 'react-bootstrap'; +import Icon from '../icon'; + +class WidgetAction extends Component { + constructor(props) { + super(props); + + this.state = { + }; + } + + onClick(e) { + + } + + render() { + return + + + + ; + } +} + +export default WidgetAction; diff --git a/src/components/widgets/box.js b/src/components/widgets/box.js new file mode 100644 index 0000000..c32517f --- /dev/null +++ b/src/components/widgets/box.js @@ -0,0 +1,48 @@ +/** + * File: box.js + * Author: Ricardo Hernandez-Montoya + * Date: 25.04.2017 + * Copyright: 2018, Institute for Automation of Complex Power Systems, EONERC + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React, { Component } from 'react'; + +import EditWidgetColorControl from '../dialogs/edit-widget-color-control'; + +class WidgetBox extends Component { + render() { + + let colors = EditWidgetColorControl.ColorPalette; + + let colorStyle = { + borderColor: colors[this.props.widget.border_color], + backgroundColor: colors[this.props.widget.background_color], + opacity: this.props.widget.background_color_opacity + } + + return ( +
+
+ { } +
+
+ ); + } +} + +export default WidgetBox; diff --git a/src/components/widgets/button.js b/src/components/widgets/button.js new file mode 100644 index 0000000..e9c32c2 --- /dev/null +++ b/src/components/widgets/button.js @@ -0,0 +1,67 @@ +/** + * File: button.js + * Author: Ricardo Hernandez-Montoya + * Date: 29.03.2017 + * Copyright: 2018, Institute for Automation of Complex Power Systems, EONERC + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React, { Component } from 'react'; +import { Button } from 'react-bootstrap'; + +class WidgetButton extends Component { + + constructor(props) { + super(props); + + this.state = { + pressed: false + } + } + + onPress(e) { + if (!this.props.widget.toggle) { + this.setState({ pressed: true }); + this.valueChanged(this.props.widget.on_value); + } + } + + onRelease(e) { + let nextState = false; + if (this.props.widget.toggle) { + nextState = !this.state.pressed; + } + + this.setState({ pressed: nextState }); + this.valueChanged(nextState ? this.props.widget.on_value : this.props.widget.off_value); + } + + valueChanged(newValue) { + if (this.props.onInputChanged) + this.props.onInputChanged(newValue); + } + + render() { + return ( +
+ +
+ ); + } +} + +export default WidgetButton; diff --git a/src/components/widgets/custom-action.js b/src/components/widgets/custom-action.js new file mode 100644 index 0000000..4a1a7cb --- /dev/null +++ b/src/components/widgets/custom-action.js @@ -0,0 +1,71 @@ +/** + * File: action.js + * Author: Steffen Vogel + * Date: 21.11.2018 + * Copyright: 2018, Institute for Automation of Complex Power Systems, EONERC + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React, { Component } from 'react'; +import { Button } from 'react-bootstrap'; +import Icon from '../icon'; +import UserStore from '../../stores/user-store'; +import SimulatorStore from '../../stores/simulator-store'; +import AppDispatcher from '../../app-dispatcher'; + +class WidgetCustomAction extends Component { + constructor(props) { + super(props); + + this.state = { + simulator: null + }; + } + + static getStores() { + return [ SimulatorStore ]; + } + + componentWillReceiveProps(props) { + if (props.simulationModel === null) + return; + + this.setState({ + simulator: SimulatorStore.getState().find(s => s._id === props.simulationModel.simulator), + sessionToken: UserStore.getState().token + }); + } + + onClick() { + AppDispatcher.dispatch({ + type: 'simulators/start-action', + simulator: this.state.simulator, + data: this.props.widget.actions, + token: this.state.sessionToken + }); + } + + render() { + return
+ +
; + } +} + +export default WidgetCustomAction; diff --git a/src/components/widgets/gauge.js b/src/components/widgets/gauge.js new file mode 100644 index 0000000..d1baa50 --- /dev/null +++ b/src/components/widgets/gauge.js @@ -0,0 +1,214 @@ +/** + * File: gauge.js + * Author: Ricardo Hernandez-Montoya + * Date: 31.03.2017 + * Copyright: 2018, Institute for Automation of Complex Power Systems, EONERC + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React, { Component } from 'react'; +import { Gauge } from 'gaugeJS'; + +class WidgetGauge extends Component { + constructor(props) { + super(props); + + this.gaugeCanvas = null; + this.gauge = null; + + this.state = { + value: 0, + minValue: null, + maxValue: null + }; + } + + componentDidMount() { + this.gauge = new Gauge(this.gaugeCanvas).setOptions(this.computeGaugeOptions(this.props.widget)); + //this.gauge.maxValue = this.state.maxValue; + //this.gauge.setMinValue(this.state.minValue); + this.gauge.animationSpeed = 30; + //this.gauge.set(this.state.value); + + //this.updateLabels(this.state.minValue, this.state.maxValue); + } + + componentWillReceiveProps(nextProps) { + if (nextProps.simulationModel == null) { + this.setState({ value: 0 }); + return; + } + + const simulator = nextProps.simulationModel.simulator; + + // update value + if (nextProps.data == null || nextProps.data[simulator] == null + || nextProps.data[simulator].output == null + || nextProps.data[simulator].output.values == null + || nextProps.data[simulator].output.values.length === 0 + || nextProps.data[simulator].output.values[0].length === 0) { + this.setState({ value: 0 }); + return; + } + + // check if value has changed + const signal = nextProps.data[simulator].output.values[nextProps.widget.signal]; + // Take just 3 decimal positions + // Note: Favor this method over Number.toFixed(n) in order to avoid a type conversion, since it returns a String + if (signal != null) { + const value = Math.round(signal[signal.length - 1].y * 1e3) / 1e3; + if (this.state.value !== value && value != null) { + this.setState({ value }); + + // update min-max if needed + let updateLabels = false; + let minValue = this.state.minValue; + let maxValue = this.state.maxValue; + + if (minValue == null) { + minValue = value - 0.5; + updateLabels = true; + + this.setState({ minValue }); + this.gauge.setMinValue(minValue); + } + + if (maxValue == null) { + maxValue = value + 0.5; + updateLabels = true; + + this.setState({ maxValue }); + this.gauge.maxValue = maxValue; + } + + if (nextProps.widget.valueUseMinMax) { + if (this.state.minValue > nextProps.widget.valueMin) { + minValue = nextProps.widget.valueMin; + + this.setState({ minValue }); + this.gauge.setMinValue(minValue); + + updateLabels = true; + } + + if (this.state.maxValue < nextProps.widget.valueMax) { + maxValue = nextProps.widget.valueMax; + + this.setState({ maxValue }); + this.gauge.maxValue = maxValue; + + updateLabels = true; + } + } + + if (updateLabels === false) { + // check if min/max changed + if (minValue > this.gauge.minValue) { + minValue = this.gauge.minValue; + updateLabels = true; + + this.setState({ minValue }); + } + + if (maxValue < this.gauge.maxValue) { + maxValue = this.gauge.maxValue; + updateLabels = true; + + this.setState({ maxValue }); + } + } + + if (updateLabels) { + this.updateLabels(minValue, maxValue); + } + + // update gauge's value + this.gauge.set(value); + } + } + } + + updateLabels(minValue, maxValue, force) { + // calculate labels + const labels = []; + const labelCount = 5; + const labelStep = (maxValue - minValue) / (labelCount - 1); + + for (let i = 0; i < labelCount; i++) { + labels.push(minValue + labelStep * i); + } + + // calculate zones + let zones = this.props.widget.colorZones ? this.props.widget.zones : null; + if (zones != null) { + // adapt range 0-100 to actual min-max + const step = (maxValue - minValue) / 100; + + zones = zones.map(zone => { + return Object.assign({}, zone, { min: (zone.min * step) + +minValue, max: zone.max * step + +minValue, strokeStyle: '#' + zone.strokeStyle }); + }); + } + + this.gauge.setOptions({ + staticLabels: { + font: '10px "Helvetica Neue"', + labels, + color: "#000000", + fractionDigits: 1 + }, + staticZones: zones + }); + } + + computeGaugeOptions(widget) { + return { + angle: -0.25, + lineWidth: 0.2, + pointer: { + length: 0.6, + strokeWidth: 0.035 + }, + radiusScale: 0.8, + colorStart: '#6EA2B0', + colorStop: '#6EA2B0', + strokeColor: '#E0E0E0', + highDpiSupport: true, + limitMax: false, + limitMin: false + }; + } + + render() { + const componentClass = this.props.editing ? "gauge-widget editing" : "gauge-widget"; + let signalType = null; + + if (this.props.simulationModel != null) { + signalType = (this.props.simulationModel != null && this.props.simulationModel.outputLength > 0 && this.props.widget.signal < this.props.simulationModel.outputLength) ? this.props.simulationModel.outputMapping[this.props.widget.signal].type : ''; + } + + return ( +
+
{this.props.widget.name}
+ this.gaugeCanvas = node} /> +
{signalType}
+
{this.state.value}
+
+ ); + } +} + +export default WidgetGauge; diff --git a/src/components/widgets/html.js b/src/components/widgets/html.js new file mode 100644 index 0000000..78dd3c6 --- /dev/null +++ b/src/components/widgets/html.js @@ -0,0 +1,30 @@ +/** + * File: html.js + * Author: Markus Grigull + * Date: 29.08.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; + +class WidgetHTML extends React.Component { + render() { + return
+ } +} + +export default WidgetHTML; diff --git a/src/components/widgets/image.js b/src/components/widgets/image.js new file mode 100644 index 0000000..3438a51 --- /dev/null +++ b/src/components/widgets/image.js @@ -0,0 +1,55 @@ +/** + * File: image.js + * Author: Markus Grigull + * Date: 14.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; + +import AppDispatcher from '../../app-dispatcher'; +import config from '../../config'; + +class WidgetImage extends React.Component { + componentWillReceiveProps(nextProps) { + // Query the image referenced by the widget + let widgetFile = nextProps.widget.file; + if (widgetFile && !nextProps.files.find(file => file._id === widgetFile)) { + AppDispatcher.dispatch({ + type: 'files/start-load', + data: widgetFile, + token: nextProps.token + }); + } + } + + render() { + const file = this.props.files.find(file => file._id === this.props.widget.file); + + return ( +
+ {file ? ( + {file.name} e.preventDefault()} /> + ) : ( + questionmark e.preventDefault()} /> + )} +
+ ); + } +} + +export default WidgetImage; diff --git a/src/components/widgets/input.js b/src/components/widgets/input.js new file mode 100644 index 0000000..63bc655 --- /dev/null +++ b/src/components/widgets/input.js @@ -0,0 +1,94 @@ +/** + * File: input.js + * Author: Ricardo Hernandez-Montoya + * Date: 29.03.2017 + * Copyright: 2018, Institute for Automation of Complex Power Systems, EONERC + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React, { Component } from 'react'; +import { Form, FormGroup, Col, ControlLabel, FormControl, InputGroup } from 'react-bootstrap'; + +class WidgetInput extends Component { + + constructor(props) { + super(props); + + this.state = { + value: '', + unit: '' + }; + } + + componentWillReceiveProps(nextProps) { + if (nextProps.simulationModel == null) { + return; + } + + // Update value + if (nextProps.widget.default_value && this.state.value === undefined) { + this.setState({ + value: nextProps.widget.default_value + }); + } + + // Update unit + if (nextProps.widget.simulationModel && nextProps.simulationModel.inputMapping && this.state.unit !== nextProps.simulationModel.inputMapping[nextProps.widget.signal].type) { + this.setState({ + unit: nextProps.simulationModel.inputMapping[nextProps.widget.signal].type + }); + } + } + + valueIsChanging(newValue) { + this.setState({ value: newValue }); + } + + valueChanged(newValue) { + if (this.props.onInputChanged) { + this.props.onInputChanged(newValue); + } + } + + handleKeyPress(e) { + if(e.charCode === 13) { + this.valueChanged(this.state.value) + } + } + + render() { + return ( +
+
+ + + {this.props.widget.name} + + + + this.handleKeyPress(e) } onBlur={ (e) => this.valueChanged(this.state.value) } onChange={ (e) => this.valueIsChanging(e.target.value) } placeholder="Enter value" value={ this.state.value } /> + {this.state.unit} + + + +
+
+ ); + } +} + +export default WidgetInput; diff --git a/src/components/widgets/label.js b/src/components/widgets/label.js new file mode 100644 index 0000000..4ce680e --- /dev/null +++ b/src/components/widgets/label.js @@ -0,0 +1,41 @@ +/** + * File: label.js + * Author: Markus Grigull + * Date: 14.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React, { Component } from 'react'; + +import EditWidgetColorControl from '../dialogs/edit-widget-color-control'; + +class WidgetLabel extends Component { + render() { + const style = { + fontSize: this.props.widget.textSize + 'px', + color: EditWidgetColorControl.ColorPalette[this.props.widget.fontColor] + }; + + return ( +
+

{this.props.widget.name}

+
+ ); + } +} + +export default WidgetLabel; diff --git a/src/components/widgets/lamp.js b/src/components/widgets/lamp.js new file mode 100644 index 0000000..5b90f56 --- /dev/null +++ b/src/components/widgets/lamp.js @@ -0,0 +1,78 @@ +/** + * File: lamp.js + * Author: Steffen Vogel + * Date: 20.09.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React, { Component } from 'react'; + +import EditWidgetColorControl from '../dialogs/edit-widget-color-control'; + +class WidgetLamp extends Component { + constructor(props) { + super(props); + + this.state = { + value: '', + threshold: 0 + }; + } + + componentWillReceiveProps(nextProps) { + if (nextProps.simulationModel == null) { + this.setState({ value: '' }); + return; + } + + const simulator = nextProps.simulationModel.simulator; + + // update value + if (nextProps.data == null || nextProps.data[simulator] == null || nextProps.data[simulator].output == null || nextProps.data[simulator].output.values == null) { + this.setState({ value: '' }); + return; + } + + // check if value has changed + const signal = nextProps.data[simulator].output.values[nextProps.widget.signal]; + if (signal != null && this.state.value !== signal[signal.length - 1].y) { + this.setState({ value: signal[signal.length - 1].y }); + } + } + + render() { + let colors = EditWidgetColorControl.ColorPalette; + let color; + + if (Number(this.state.value) > Number(this.props.widget.threshold)) + color = colors[this.props.widget.on_color]; + else + color = colors[this.props.widget.off_color]; + + let style = { + backgroundColor: color, + width: this.props.widget.width, + height: this.props.widget.height + } + + return ( +
+ ); + } +} + +export default WidgetLamp; diff --git a/src/components/widgets/plot-table.js b/src/components/widgets/plot-table.js new file mode 100644 index 0000000..368f7c5 --- /dev/null +++ b/src/components/widgets/plot-table.js @@ -0,0 +1,171 @@ +/** + * File: plot-table.js + * Author: Markus Grigull + * Date: 15.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React, { Component } from 'react'; +import classNames from 'classnames'; +import { FormGroup, Checkbox } from 'react-bootstrap'; + +import Plot from '../widget-plot/plot'; +import PlotLegend from '../widget-plot/plot-legend'; + +class WidgetPlotTable extends Component { + constructor(props) { + super(props); + + this.state = { + preselectedSignals: [], + signals: [] + }; + } + + componentWillReceiveProps(nextProps) { + if (nextProps.simulationModel == null) { + return; + } + + // Update internal selected signals state with props (different array objects) + if (this.props.widget.signals !== nextProps.widget.signals) { + this.setState( {signals: nextProps.widget.signals}); + } + + // Identify if there was a change in the preselected signals + if (JSON.stringify(nextProps.widget.preselectedSignals) !== JSON.stringify(this.props.widget.preselectedSignals) || this.state.preselectedSignals.length === 0) { + // Update the currently selected signals by intersecting with the preselected signals + // Do the same with the plot values + var intersection = this.computeIntersection(nextProps.widget.preselectedSignals, nextProps.widget.signals); + this.setState({ signals: intersection }); + + this.updatePreselectedSignalsState(nextProps); + return; + } + } + + // Perform the intersection of the lists, alternatively could be done with Sets ensuring unique values + computeIntersection(preselectedSignals, selectedSignals) { + return preselectedSignals.filter( s => selectedSignals.includes(s)); + } + + updatePreselectedSignalsState(nextProps) { + // Create checkboxes using the signal indices from simulation model + const preselectedSignals = nextProps.simulationModel.outputMapping.reduce( + // Loop through simulation model signals + (accum, model_signal, signal_index) => { + // Append them if they belong to the current selected type + if (nextProps.widget.preselectedSignals.indexOf(signal_index) > -1) { + accum.push( + { + index: signal_index, + name: model_signal.name, + type: model_signal.type + } + ) + } + return accum; + }, []); + + this.setState({ preselectedSignals }); + } + + updateSignalSelection(signal_index, checked) { + // Update the selected signals and propagate to parent component + var new_widget = Object.assign({}, this.props.widget, { + signals: checked? this.state.signals.concat(signal_index) : this.state.signals.filter( (idx) => idx !== signal_index ) + }); + this.props.onWidgetChange(new_widget); + } + + render() { + let checkBoxes = []; + + // Data passed to plot + if (this.props.simulationModel == null) { + return
; + } + + const simulator = this.props.simulationModel.simulator; + let simulatorData = []; + + if (this.props.data[simulator] != null && this.props.data[simulator].output != null && this.props.data[simulator].output.values != null) { + simulatorData = this.props.data[simulator].output.values.filter((values, index) => ( + this.props.widget.signals.findIndex(value => value === index) !== -1 + )); + } + + if (this.state.preselectedSignals && this.state.preselectedSignals.length > 0) { + // Create checkboxes using the signal indices from simulation model + checkBoxes = this.state.preselectedSignals.map( (signal) => { + var checked = this.state.signals.indexOf(signal.index) > -1; + var chkBxClasses = classNames({ + 'btn': true, + 'btn-default': true, + 'active': checked + }); + return this.updateSignalSelection(signal.index, e.target.checked) } > { signal.name } + }); + } + + // Prepare an array with the signals to show in the legend + var legendSignals = this.state.preselectedSignals.reduce( (accum, signal, i) => { + if (this.state.signals.includes(signal.index)) { + accum.push({ + index: signal.index, + name: signal.name, + type: signal.type + }); + } + return accum; + }, []); + + return ( +
+
+
+
+ { checkBoxes.length > 0 ? ( + + { checkBoxes } + + ) : ( No signal has been pre-selected. ) + } +
+ +
+ +
+
+ +
+
+ ); + } +} + +export default WidgetPlotTable; diff --git a/src/components/widgets/plot.js b/src/components/widgets/plot.js new file mode 100644 index 0000000..e61ca10 --- /dev/null +++ b/src/components/widgets/plot.js @@ -0,0 +1,88 @@ +/** + * File: plot.js + * Author: Markus Grigull + * Date: 08.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; + +import Plot from '../widget-plot/plot'; +import PlotLegend from '../widget-plot/plot-legend'; + +class WidgetPlot extends React.Component { + constructor(props) { + super(props); + + this.state = { + data: [], + legend: [] + }; + } + + componentWillReceiveProps(nextProps) { + if (nextProps.simulationModel == null) { + this.setState({ data: [], legend: [] }); + return; + } + + const simulator = nextProps.simulationModel.simulator; + + // Proceed if a simulation with models and a simulator are available + if (simulator && nextProps.data[simulator] != null && nextProps.data[simulator] != null && nextProps.data[simulator].output != null && nextProps.data[simulator].output.values != null) { + const chosenSignals = nextProps.widget.signals; + + const data = nextProps.data[simulator].output.values.filter((values, index) => ( + nextProps.widget.signals.findIndex(value => value === index) !== -1 + )); + + // Query the signals that will be displayed in the legend + const legend = nextProps.simulationModel.outputMapping.reduce( (accum, model_signal, signal_index) => { + if (chosenSignals.includes(signal_index)) { + accum.push({ index: signal_index, name: model_signal.name, type: model_signal.type }); + } + + return accum; + }, []); + + this.setState({ data, legend }); + } else { + this.setState({ data: [], legend: [] }); + } + } + + render() { + return
+
+ +
+ +
; + } +} + +export default WidgetPlot; diff --git a/src/components/widgets/slider.js b/src/components/widgets/slider.js new file mode 100644 index 0000000..4212eef --- /dev/null +++ b/src/components/widgets/slider.js @@ -0,0 +1,132 @@ +/** + * File: slider.js + * Author: Ricardo Hernandez-Montoya + * Date: 30.03.2017 + * Copyright: 2018, Institute for Automation of Complex Power Systems, EONERC + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React, { Component } from 'react'; +import { format } from 'd3'; +import classNames from 'classnames'; +import Slider from 'rc-slider'; +import 'rc-slider/assets/index.css'; + +class WidgetSlider extends Component { + + static get OrientationTypes() { + return ({ + HORIZONTAL: {value: 0, name: 'Horizontal'}, + VERTICAL: {value: 1, name: 'Vertical'} + }) + } + + constructor(props) { + super(props); + + this.state = { + unit: '' + }; + } + + componentWillReceiveProps(nextProps) { + if (nextProps.simulationModel == null) { + return; + } + + // Update value + if (nextProps.widget.default_value && this.state.value === undefined) { + this.setState({ + value: nextProps.widget.default_value, + }); + } + + // Update unit + if (nextProps.widget.simulationModel && nextProps.simulationModel.inputMapping && this.state.unit !== nextProps.simulationModel.inputMapping[nextProps.widget.signal].type) { + this.setState({ + unit: nextProps.simulationModel.inputMapping[nextProps.widget.signal].type + }); + } + + // Check if the orientation changed, update the size if it did + if (this.props.widget.orientation !== nextProps.widget.orientation) { + let baseWidget = nextProps.widget; + + // Exchange dimensions and constraints + let newWidget = Object.assign({}, baseWidget, { + width: baseWidget.height, + height: baseWidget.width, + minWidth: baseWidget.minHeight, + minHeight: baseWidget.minWidth, + maxWidth: baseWidget.maxHeight, + maxHeight: baseWidget.maxWidth + }); + + nextProps.onWidgetChange(newWidget); + } + } + + valueIsChanging(newValue) { + if (this.props.widget.continous_update) + this.valueChanged(newValue); + + this.setState({ value: newValue }); + } + + valueChanged(newValue) { + if (this.props.onInputChanged) { + this.props.onInputChanged(newValue); + } + } + + render() { + let isVertical = this.props.widget.orientation === WidgetSlider.OrientationTypes.VERTICAL.value; + + let fields = { + name: this.props.widget.name, + control: this.valueIsChanging(v) } onAfterChange={ (v) => this.valueChanged(v) }/>, + value: { format('.3s')(Number.parseFloat(this.state.value)) }, + unit: { this.state.unit } + } + + var widgetClasses = classNames({ + 'slider-widget': true, + 'full': true, + 'vertical': isVertical, + 'horizontal': !isVertical + }); + + return ( + this.props.widget.orientation === WidgetSlider.OrientationTypes.HORIZONTAL.value? ( +
+ +
{ fields.control }
+ { fields.value } +
+ ) : ( +
+ + { fields.control } + { fields.value } + { this.props.widget.showUnit && fields.unit } +
+ ) + ); + } +} + +export default WidgetSlider; diff --git a/src/components/widgets/table.js b/src/components/widgets/table.js new file mode 100644 index 0000000..53af120 --- /dev/null +++ b/src/components/widgets/table.js @@ -0,0 +1,99 @@ +/** + * File: table.js + * Author: Markus Grigull + * Date: 14.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React, { Component } from 'react'; +import { format } from 'd3'; + +import Table from '../table'; +import TableColumn from '../table-column'; + +class WidgetTable extends Component { + constructor(props) { + super(props); + + this.state = { + rows: [], + sequence: null, + showUnit: false + }; + } + + componentWillReceiveProps(nextProps) { + if (nextProps.simulationModel == null) { + this.setState({ rows: [], sequence: null }); + return; + } + + const simulator = nextProps.simulationModel.simulator; + + // check data + if (nextProps.data == null + || nextProps.data[simulator] == null + || nextProps.data[simulator].output == null + || nextProps.data[simulator].output.values.length === 0 + || nextProps.data[simulator].output.values[0].length === 0) { + + // clear values + this.setState({ rows: [], sequence: null, showUnit: false }); + return; + } + + // check if new data, otherwise skip + /*if (this.state.sequence >= nextProps.data[simulator.node][simulator.simulator].sequence) { + return; + }*/ + + // get rows + const rows = []; + + nextProps.data[simulator].output.values.forEach((signal, index) => { + if (index < nextProps.simulationModel.outputMapping.length) { + rows.push({ + name: nextProps.simulationModel.outputMapping[index].name, + unit: nextProps.simulationModel.outputMapping[index].type, + value: signal[signal.length - 1].y + }); + } + }); + + this.setState({ showUnit: nextProps.showUnit, rows: rows, sequence: nextProps.data[simulator].output.sequence }); + } + + render() { + var columns = [ + , + + ]; + + if (this.props.widget.showUnit) + columns.push() + + return ( +
+ + { columns } +
+
+ ); + } +} + +export default WidgetTable; diff --git a/src/components/widgets/topology.js b/src/components/widgets/topology.js new file mode 100644 index 0000000..c47b155 --- /dev/null +++ b/src/components/widgets/topology.js @@ -0,0 +1,185 @@ +/** + * File: topology.js + * Author: Ricardo Hernandez-Montoya + * Date: 08.01.2018 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import {ReactSVGPanZoom} from 'react-svg-pan-zoom'; +import config from '../../config'; +import '../../styles/simple-spinner.css'; +import { cimsvg } from 'libcimsvg'; + +// Do not show Pintura's grid +const pinturaGridStyle = { + display: 'none' +} + +// Avoid another color in the frontend +const pinturaBackingStyle = { + fill: 'transparent' +} + +// Center spinner +const spinnerContainerStyle = { + width: '100%', + height: '100%', + display: 'flex', + justifyContent: 'center', + alignItems: 'center' +} + +// Topology failed message +const msgContainerStyle = Object.assign({ + backgroundColor: '#ececec' +},spinnerContainerStyle) + +const msgStyle = { + fontWeight: 'bold' +} + +// Initialize functions +function attachComponentEvents() { + window.onMouseOver = (e) => show(textSibling(e)); + window.onMouseLeave = (e) => hide(textSibling(e)); +} + +function textSibling(e) { + // Find sibling text element and toggle its visibility + let gParent = e.target.parentElement; + return gParent.getElementsByTagName('text')[0]; +} + +function show(element) { + element.style.visibility = 'inherit'; +} + +function hide(element) { + element.style.visibility = 'hidden'; +} + +// De-initialize functions +function detachComponentEvents() { + window.onMouseOver = null; + window.onMouseLeave = null; +} + +class WidgetTopology extends React.Component { + constructor(props) { + super(props); + this.svgElem = React.createRef(); + this.Viewer = null; + + this.state = { + visualizationState: 'initial' + }; + } + + componentDidMount() { + if (this.svgElem) { + window.onMouseLeave = function() {}; + window.onMouseOver = function() {}; + window.onMouseLeave = function() {}; + window.onMouseUp = function() {}; + window.onMouseDown = function() {}; + window.onMouseMove = function() {}; + } + } + + componentWillUnmount() { + detachComponentEvents(); + } + + componentWillReceiveProps(nextProps) { + const file = nextProps.files.find(file => file._id === nextProps.widget.file); + // Ensure model is requested only once or a different was selected + if (this.props.widget.file !== nextProps.widget.file || (this.state.visualizationState === 'initial' && file)) { + this.setState({'visualizationState': 'loading' }); + if (file) { + fetch(new Request('/' + config.publicPathBase + file.path)) + .then( response => { + if (response.status === 200) { + this.setState({'visualizationState': 'ready' }); + return response.text().then( contents => { + if (this.svgElem) { + let cimsvgInstance = new cimsvg(this.svgElem.current); + cimsvg.setCimsvg(cimsvgInstance); + cimsvgInstance.setFileCount(1); + cimsvgInstance.loadFile(contents); + //cimsvgInstance.fit(); + attachComponentEvents(); + } + else { + console.error("The svgElem variable is not initialized before the attempt to create the cimsvg instance."); + } + }); + } else { + throw new Error('Request failed'); + } + }) + .catch(error => { + console.error(error); + this.setState({ + 'visualizationState': 'show_message', + 'message': 'Topology could not be loaded.'}); + }); + } + } else { + // No file has been selected + if (!nextProps.widget.file) { + this.setState({ + 'visualizationState': 'show_message', + 'message': 'Select a topology model first.'}); + } + } + } + + render() { + var markup = null; + + switch(this.state.visualizationState) { + case 'loading': + markup =
; break; + case 'show_message': + markup =
{ this.state.message }
; break; + default: + markup = (
+ this.Viewer = Viewer} + style={{outline: "1px solid grey"}} + detectAutoPan={false} + miniaturePosition="none" + toolbarPosition="none" + background="white" + tool="pan" + width={this.props.widget.width-2} height={this.props.widget.height-2} > + + + + + + + + +
); + } + return markup; + } +} + +export default WidgetTopology; diff --git a/src/components/widgets/value.js b/src/components/widgets/value.js new file mode 100644 index 0000000..c58f57d --- /dev/null +++ b/src/components/widgets/value.js @@ -0,0 +1,72 @@ +/** + * File: value.js + * Author: Markus Grigull + * Date: 04.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React, { Component } from 'react'; +import { format } from 'd3'; + +class WidgetValue extends Component { + constructor(props) { + super(props); + + this.state = { + value: '', + unit: '' + }; + } + + componentWillReceiveProps(nextProps) { + if (nextProps.simulationModel == null) { + this.setState({ value: '' }); + return; + } + + const simulator = nextProps.simulationModel.simulator; + + // update value + if (nextProps.data == null || nextProps.data[simulator] == null || nextProps.data[simulator].output == null || nextProps.data[simulator].output.values == null) { + this.setState({ value: '' }); + return; + } + + const unit = nextProps.simulationModel.outputMapping[nextProps.widget.signal].type; + + // check if value has changed + const signal = nextProps.data[simulator].output.values[nextProps.widget.signal]; + if (signal != null && this.state.value !== signal[signal.length - 1].y) { + this.setState({ value: signal[signal.length - 1].y, unit }); + } + } + + render() { + var value_to_render = Number(this.state.value); + return ( +
+ {this.props.widget.name} + {Number.isNaN(value_to_render) ? NaN : format('.3s')(value_to_render)} + {this.props.widget.showUnit && + [{this.state.unit}] + } +
+ ); + } +} + +export default WidgetValue; diff --git a/src/config.js b/src/config.js new file mode 100644 index 0000000..4054518 --- /dev/null +++ b/src/config.js @@ -0,0 +1,11 @@ + +const config = { + publicPathBase: 'public/', + instance: 'frontend of the Global RT-SuperLab Demonstration', + admin: { + name: 'Steffen Vogel', + mail: 'stvogel@eonerc.rwth-aachen.de' + } +} + +export default config diff --git a/src/containers/app.js b/src/containers/app.js new file mode 100644 index 0000000..4199935 --- /dev/null +++ b/src/containers/app.js @@ -0,0 +1,151 @@ +/** + * File: app.js + * Author: Markus Grigull + * Date: 02.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { Container } from 'flux/utils'; +import { DragDropContext } from 'react-dnd'; +import HTML5Backend from 'react-dnd-html5-backend'; +import NotificationSystem from 'react-notification-system'; +import { Redirect, Route } from 'react-router-dom'; +import { Col } from 'react-bootstrap'; + +import AppDispatcher from '../app-dispatcher'; +import SimulationStore from '../stores/simulation-store'; +import SimulatorStore from '../stores/simulator-store'; +import UserStore from '../stores/user-store'; +import NotificationsDataManager from '../data-managers/notifications-data-manager'; + +import Home from '../components/home'; +import Header from '../components/header'; +import Footer from '../components/footer'; +import SidebarMenu from '../components/menu-sidebar'; +import HeaderMenu from '../components/header-menu'; + +import Projects from './projects'; +import Project from './project'; +import Simulators from './simulators'; +import Visualization from './visualization'; +import Simulations from './simulations'; +import Simulation from './simulation'; +import SimulationModel from './simulation-model'; +import Users from './users'; + +import '../styles/app.css'; + +class App extends React.Component { + static getStores() { + return [ SimulatorStore, UserStore, SimulationStore ]; + } + + static calculateState(prevState) { + let currentUser = UserStore.getState().currentUser; + + return { + simulators: SimulatorStore.getState(), + simulations: SimulationStore.getState(), + currentRole: currentUser ? currentUser.role : '', + token: UserStore.getState().token, + + showSidebarMenu: false, + }; + } + + componentWillMount() { + // if token stored locally, request user + const token = localStorage.getItem('token'); + + if (token != null && token !== '') { + // save token so we dont logout + this.setState({ token }); + + AppDispatcher.dispatch({ + type: 'users/logged-in', + token: token + }); + } + } + + componentDidMount() { + // load all simulators and simulations to fetch simulation data + AppDispatcher.dispatch({ + type: 'simulators/start-load', + token: this.state.token + }); + + AppDispatcher.dispatch({ + type: 'simulations/start-load', + token: this.state.token + }); + + NotificationsDataManager.setSystem(this.refs.notificationSystem); + } + + showSidebarMenu = () => { + this.setState({ showSidebarMenu: true }); + } + + hideSidebarMenu = () => { + this.setState({ showSidebarMenu: false }); + } + + render() { + if (this.state.token == null) { + return (); + } + + return ( +
+ + + + +
+ + +
+ +
+ + + + +
+ + + + + + + + + + +
+
+ +
+
+
+ ); + } +} + +export default DragDropContext(HTML5Backend)(Container.create(App)); diff --git a/src/containers/login.js b/src/containers/login.js new file mode 100644 index 0000000..2a812cf --- /dev/null +++ b/src/containers/login.js @@ -0,0 +1,96 @@ +/** + * File: login.js + * Author: Markus Grigull + * Date: 15.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React, { Component } from 'react'; +import { Container } from 'flux/utils'; +import { PageHeader } from 'react-bootstrap'; +import NotificationSystem from 'react-notification-system'; +import { Redirect } from 'react-router-dom'; + +import LoginForm from '../components/login-form'; +import Header from '../components/header'; +import Footer from '../components/footer'; +import NotificationsDataManager from '../data-managers/notifications-data-manager'; + +import AppDispatcher from '../app-dispatcher'; +import UserStore from '../stores/user-store'; + +class Login extends Component { + static getStores() { + return [ UserStore ]; + } + + static calculateState() { + return { + currentUser: UserStore.getState().currentUser, + token: UserStore.getState().token, + loginMessage: UserStore.getState().loginMessage + }; + } + + componentDidMount() { + NotificationsDataManager.setSystem(this.refs.notificationSystem); + } + + componentWillUpdate(nextProps, nextState) { + // if token stored locally, request user + if (nextState.token == null) { + const token = localStorage.getItem('token'); + + if (token != null && token !== '' && nextState.currentUser == null) { + AppDispatcher.dispatch({ + type: 'users/logged-in', + token: token + }); + } + } else { + // check if logged in + if (nextState.currentUser != null) { + // save login in local storage + localStorage.setItem('token', nextState.token); + } + } + } + + render() { + if (this.state.currentUser != null) { + return (); + } + + return ( +
+ + +
+ +
+ Login + + +
+ +
+
+ ); + } +} + +export default Container.create(Login); diff --git a/src/containers/logout.js b/src/containers/logout.js new file mode 100644 index 0000000..9fa39ae --- /dev/null +++ b/src/containers/logout.js @@ -0,0 +1,44 @@ +/** + * File: logout.js + * Author: Markus Grigull + * Date: 15.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { Redirect } from 'react-router-dom'; + +import AppDispatcher from '../app-dispatcher'; + +class Logout extends React.Component { + componentWillMount() { + AppDispatcher.dispatch({ + type: 'users/logout' + }); + + // discard login token + localStorage.setItem('token', ''); + } + + render() { + return ( + + ); + } +} + +export default Logout; diff --git a/src/containers/project.js b/src/containers/project.js new file mode 100644 index 0000000..ce5e3b4 --- /dev/null +++ b/src/containers/project.js @@ -0,0 +1,234 @@ +/** + * File: project.js + * Author: Markus Grigull + * Date: 03.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React, { Component } from 'react'; +import { Container } from 'flux/utils'; +import { Button } from 'react-bootstrap'; +import FileSaver from 'file-saver'; + +import AppDispatcher from '../app-dispatcher'; +import ProjectStore from '../stores/project-store'; +import UserStore from '../stores/user-store'; +import VisualizationStore from '../stores/visualization-store'; +import SimulationStore from '../stores/simulation-store'; + +import Icon from '../components/icon'; +import CustomTable from '../components/table'; +import TableColumn from '../components/table-column'; +import NewVisualzationDialog from '../components/dialogs/new-visualization'; +import EditVisualizationDialog from '../components/dialogs/edit-visualization'; +import ImportVisualizationDialog from '../components/dialogs/import-visualization'; + +import DeleteDialog from '../components/dialogs/delete-dialog'; + +class Visualizations extends Component { + static getStores() { + return [ ProjectStore, VisualizationStore, UserStore, SimulationStore ]; + } + + static calculateState(prevState, props) { + prevState = prevState || {}; + + // load project + const sessionToken = UserStore.getState().token; + + let project = ProjectStore.getState().find(project => project._id === props.match.params.project); + if (project == null) { + AppDispatcher.dispatch({ + type: 'projects/start-load', + data: props.match.params.project, + token: sessionToken + }); + + project = {}; + } + + // load simulation + let simulation = {}; + + if (project.simulation != null) { + simulation = SimulationStore.getState().find(simulation => simulation._id === project.simulation); + } + + // load visualizations + let visualizations = []; + + if (project.visualizations != null) { + visualizations = VisualizationStore.getState().filter(visualization => project.visualizations.includes(visualization._id)); + } + + return { + visualizations, + project, + simulation, + sessionToken, + + newModal: prevState.newModal || false, + deleteModal: prevState.deleteModal || false, + editModal: prevState.editModal || false, + importModal: prevState.importModal || false, + modalData: prevState.modalData || {} + }; + } + + componentDidMount() { + AppDispatcher.dispatch({ + type: 'visualizations/start-load', + token: this.state.sessionToken + }); + + AppDispatcher.dispatch({ + type: 'simulations/start-load', + token: this.state.sessionToken + }); + } + + closeNewModal(data) { + this.setState({ newModal: false }); + + if (data) { + // add project to visualization + data.project = this.state.project._id; + + AppDispatcher.dispatch({ + type: 'visualizations/start-add', + data: data, + token: this.state.sessionToken + }); + + this.setState({ project: {} }, () => { + AppDispatcher.dispatch({ + type: 'projects/start-load', + data: this.props.match.params.project, + token: this.state.sessionToken + }); + }); + } + } + + closeDeleteModal = confirmDelete => { + this.setState({ deleteModal: false }); + + if (confirmDelete === false) { + return; + } + + AppDispatcher.dispatch({ + type: 'visualizations/start-remove', + data: this.state.modalData, + token: this.state.sessionToken + }); + } + + closeEditModal(data) { + this.setState({ editModal : false }); + + if (data) { + AppDispatcher.dispatch({ + type: 'visualizations/start-edit', + data: data, + token: this.state.sessionToken + }); + } + } + + closeImportModal(data) { + this.setState({ importModal: false }); + + if (data) { + data.project = this.state.project._id; + + AppDispatcher.dispatch({ + type: 'visualizations/start-add', + data, + token: this.state.sessionToken + }); + + this.setState({ project: {} }, () => { + AppDispatcher.dispatch({ + type: 'projects/start-load', + data: this.props.match.params.project, + token: this.state.sessionToken + }); + }); + } + } + + exportVisualization(index) { + // filter properties + let visualization = Object.assign({}, this.state.visualizations[index]); + delete visualization._id; + delete visualization.project; + delete visualization.user; + + visualization.widgets.forEach(widget => { + delete widget.simulator; + }); + + // show save dialog + const blob = new Blob([JSON.stringify(visualization, null, 2)], { type: 'application/json' }); + FileSaver.saveAs(blob, 'visualization - ' + visualization.name + '.json'); + } + + onModalKeyPress = (event) => { + if (event.key === 'Enter') { + event.preventDefault(); + + this.confirmDeleteModal(); + } + } + + render() { + const buttonStyle = { + marginRight: '10px' + }; + + return ( +
+

{this.state.project.name}

+ + + + this.setState({ editModal: true, modalData: this.state.visualizations[index] })} + onDelete={(index) => this.setState({ deleteModal: true, modalData: this.state.visualizations[index] })} + onExport={index => this.exportVisualization(index)} + /> + + + + + + this.closeNewModal(data)} /> + this.closeEditModal(data)} visualization={this.state.modalData} /> + this.closeImportModal(data)} simulation={this.state.simulation} /> + + +
+ ); + } +} + +export default Container.create(Visualizations, {withProps: true}); diff --git a/src/containers/projects.js b/src/containers/projects.js new file mode 100644 index 0000000..b94c846 --- /dev/null +++ b/src/containers/projects.js @@ -0,0 +1,159 @@ +/** + * File: projects.js + * Author: Markus Grigull + * Date: 02.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { Container } from 'flux/utils'; +import { Button } from 'react-bootstrap'; + +import AppDispatcher from '../app-dispatcher'; +import ProjectStore from '../stores/project-store'; +import UserStore from '../stores/user-store'; +import SimulationStore from '../stores/simulation-store'; + +import Icon from '../components/icon'; +import Table from '../components/table'; +import TableColumn from '../components/table-column'; +import NewProjectDialog from '../components/dialogs/new-project'; +import EditProjectDialog from '../components/dialogs/edit-project'; + +import DeleteDialog from '../components/dialogs/delete-dialog'; + +class Projects extends React.Component { + static getStores() { + return [ ProjectStore, SimulationStore, UserStore ]; + } + + static calculateState() { + return { + projects: ProjectStore.getState(), + simulations: SimulationStore.getState(), + sessionToken: UserStore.getState().token, + + newModal: false, + editModal: false, + deleteModal: false, + modalData: {} + }; + } + + componentWillMount() { + AppDispatcher.dispatch({ + type: 'projects/start-load', + token: this.state.sessionToken + }); + + AppDispatcher.dispatch({ + type: 'simulations/start-load', + token: this.state.sessionToken + }); + } + + closeNewModal(data) { + this.setState({ newModal: false }); + + if (data) { + AppDispatcher.dispatch({ + type: 'projects/start-add', + data, + token: this.state.sessionToken + }); + } + } + + closeDeleteModal = confirmDelete => { + this.setState({ deleteModal: false }); + + if (confirmDelete === false) { + return; + } + + AppDispatcher.dispatch({ + type: 'projects/start-remove', + data: this.state.modalData, + token: this.state.sessionToken + }); + } + + closeEditModal(data) { + this.setState({ editModal: false }); + + if (data) { + AppDispatcher.dispatch({ + type: 'projects/start-edit', + data: data, + token: this.state.sessionToken + }); + } + } + + getSimulationName(id) { + for (var i = 0; i < this.state.simulations.length; i++) { + if (this.state.simulations[i]._id === id) { + return this.state.simulations[i].name; + } + } + + return id; + } + + hasValidSimulation() { + const simulations = this.state.simulations.filter(simulation => { + return simulation.models.length > 0; + }); + + return simulations.length > 0; + } + + onModalKeyPress = (event) => { + if (event.key === 'Enter') { + event.preventDefault(); + + this.confirmDeleteModal(); + } + } + + render() { + return ( +
+

Projects

+ + + + this.getSimulationName(id)} /> + this.setState({ editModal: true, modalData: this.state.projects[index] })} onDelete={index => this.setState({ deleteModal: true, modalData: this.state.projects[index] })} /> +
+ + + + {!this.hasValidSimulation() && + Simulation with at least one simulation-model required! + } + + this.closeNewModal(data)} simulations={this.state.simulations} /> + this.closeEditModal(data)} project={this.state.modalData} simulations={this.state.simulations} /> + + +
+ ); + } +} + +export default Container.create(Projects); diff --git a/src/containers/select-file.js b/src/containers/select-file.js new file mode 100644 index 0000000..755356d --- /dev/null +++ b/src/containers/select-file.js @@ -0,0 +1,151 @@ +/** + * File: selectFile.js + * Author: Markus Grigull + * Date: 10.05.2018 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { Container } from 'flux/utils'; +import { FormGroup, FormControl, ControlLabel, Button, ProgressBar, Col } from 'react-bootstrap'; + +import FileStore from '../stores/file-store'; +import UserStore from '../stores/user-store'; + +import AppDispatcher from '../app-dispatcher'; + +class SelectFile extends React.Component { + static getStores() { + return [ FileStore, UserStore ]; + } + + static calculateState() { + return { + files: FileStore.getState(), + sessionToken: UserStore.getState().token, + selectedFile: '', + uploadFile: null, + uploadProgress: 0 + }; + } + + componentDidMount() { + AppDispatcher.dispatch({ + type: 'files/start-load', + token: this.state.sessionToken + }); + } + + componentWillReceiveProps(nextProps) { + if (nextProps.value === this.state.selectedSimulator) { + return; + } + + let selectedSimulator = nextProps.value; + if (selectedSimulator == null) { + if (this.state.simulators.length > 0) { + selectedSimulator = this.state.simulators[0]._id; + } else { + selectedSimulator = ''; + } + } + + this.setState({ selectedSimulator }); + } + + handleChange = event => { + this.setState({ selectedFile: event.target.value }); + + // send file to callback + if (this.props.onChange != null) { + const file = this.state.files.find(f => f._id === event.target.value); + + this.props.onChange(file); + } + } + + selectUploadFile = event => { + this.setState({ uploadFile: event.target.files[0] }); + } + + startFileUpload = () => { + // upload file + const formData = new FormData(); + formData.append(0, this.state.uploadFile); + + AppDispatcher.dispatch({ + type: 'files/start-upload', + data: formData, + token: this.state.sessionToken, + progressCallback: this.updateUploadProgress, + finishedCallback: this.clearProgress + }); + } + + updateUploadProgress = event => { + this.setState({ uploadProgress: parseInt(event.percent.toFixed(), 10) }); + } + + clearProgress = () => { + // select uploaded file + const selectedFile = this.state.files[this.state.files.length - 1]._id; + this.setState({ selectedFile, uploadProgress: 0 }); + } + + render() { + const fileOptions = this.state.files.map(f => + + ); + + const progressBarStyle = { + marginLeft: '100px', + marginTop: '-25px' + }; + + return
+ + + {this.props.name} + + + + + {fileOptions} + + + + + + + + + + + + + + + + + +
; + } +} + +export default Container.create(SelectFile); diff --git a/src/containers/select-simulator.js b/src/containers/select-simulator.js new file mode 100644 index 0000000..bcf7719 --- /dev/null +++ b/src/containers/select-simulator.js @@ -0,0 +1,88 @@ +/** + * File: selectSimulator.js + * Author: Markus Grigull + * Date: 10.05.2018 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { Container } from 'flux/utils'; +import { FormGroup, FormControl, ControlLabel, Col } from 'react-bootstrap'; +import _ from 'lodash'; + +import SimulatorStore from '../stores/simulator-store'; + +class SelectSimulator extends React.Component { + static getStores() { + return [ SimulatorStore ]; + } + + static calculateState() { + return { + simulators: SimulatorStore.getState(), + selectedSimulator: '' + }; + } + + componentWillReceiveProps(nextProps) { + if (nextProps.value === this.state.selectedSimulator) { + return; + } + + let selectedSimulator = nextProps.value; + if (selectedSimulator == null) { + if (this.state.simulators.length > 0) { + selectedSimulator = this.state.simulators[0]._id; + } else { + selectedSimulator = ''; + } + } + + this.setState({ selectedSimulator }); + } + + handleChange = event => { + this.setState({ selectedSimulator: event.target.value }); + + // send complete simulator to callback + if (this.props.onChange != null) { + const simulator = this.state.simulators.find(s => s._id === event.target.value); + + this.props.onChange(simulator); + } + } + + render() { + const simulatorOptions = this.state.simulators.map(s => + + ); + + return + + Simulator + + + + + {simulatorOptions} + + + ; + } +} + +export default Container.create(SelectSimulator); diff --git a/src/containers/simulation-model.js b/src/containers/simulation-model.js new file mode 100644 index 0000000..975b9e6 --- /dev/null +++ b/src/containers/simulation-model.js @@ -0,0 +1,171 @@ +/** + * File: simulationModel.js + * Author: Markus Grigull + * Date: 10.05.2018 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { Container } from 'flux/utils'; +import { Button, Col, Form, ControlLabel } from 'react-bootstrap'; + +import SimulationModelStore from '../stores/simulation-model-store'; +import UserStore from '../stores/user-store'; +import AppDispatcher from '../app-dispatcher'; + +import SelectSimulator from './select-simulator'; +import SelectFile from './select-file'; +import SignalMapping from '../components/signal-mapping'; +import EditableHeader from '../components/editable-header'; +import ParametersEditor from '../components/parameters-editor'; + +class SimulationModel extends React.Component { + static getStores() { + return [ SimulationModelStore, UserStore ]; + } + + static calculateState(prevState, props) { + const simulationModel = SimulationModelStore.getState().find(m => m._id === props.match.params.simulationModel); + + return { + simulationModel: simulationModel || {}, + sessionToken: UserStore.getState().token + }; + } + + componentWillMount() { + AppDispatcher.dispatch({ + type: 'simulationModels/start-load', + data: this.props.match.params.simulationModel, + token: this.state.sessionToken + }); + } + + submitForm = event => { + event.preventDefault(); + } + + saveChanges = () => { + AppDispatcher.dispatch({ + type: 'simulationModels/start-edit', + data: this.state.simulationModel, + token: this.state.sessionToken + }); + + this.props.history.push('/simulations/' + this.state.simulationModel.simulation); + } + + discardChanges = () => { + this.props.history.push('/simulations/' + this.state.simulationModel.simulation); + } + + handleSimulatorChange = simulator => { + const simulationModel = this.state.simulationModel; + + simulationModel.simulator = simulator; + + this.setState({ simulationModel }); + } + + handleModelChange = file => { + console.log(file); + } + + handleConfigurationChange = file => { + console.log(file); + } + + handleOutputMappingChange = (length, signals) => { + const simulationModel = this.state.simulationModel; + + simulationModel.outputMapping = signals; + simulationModel.outputLength = length; + + this.setState({ simulationModel }); + } + + handleInputMappingChange = (length, signals) => { + const simulationModel = this.state.simulationModel; + + simulationModel.inputMapping = signals; + simulationModel.inputLength = length; + + this.setState({ simulationModel }); + } + + handleTitleChange = title => { + const simulationModel = this.state.simulationModel; + + simulationModel.name = title; + + this.setState({ simulationModel }); + } + + handleStartParametersChange = startParameters => { + const simulationModel = this.state.simulationModel; + + simulationModel.startParameters = startParameters; + + this.setState({ simulationModel }); + } + + render() { + const buttonStyle = { + marginRight: '10px' + }; + + return
+ + +
+ + + + + + + +
+ + Start Parameters + + + + + +
+ + + + + + + + + + + +
+ + + + +
; + } +} + +export default Container.create(SimulationModel, { withProps: true }); diff --git a/src/containers/simulation.js b/src/containers/simulation.js new file mode 100644 index 0000000..090a8de --- /dev/null +++ b/src/containers/simulation.js @@ -0,0 +1,288 @@ +/** + * File: simulation.js + * Author: Markus Grigull + * Date: 04.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { Container } from 'flux/utils'; +import { Button } from 'react-bootstrap'; +import FileSaver from 'file-saver'; +import _ from 'lodash'; + +import SimulationStore from '../stores/simulation-store'; +import SimulatorStore from '../stores/simulator-store'; +import SimulationModelStore from '../stores/simulation-model-store'; +import UserStore from '../stores/user-store'; +import AppDispatcher from '../app-dispatcher'; + +import Icon from '../components/icon'; +import Table from '../components/table'; +import TableColumn from '../components/table-column'; +import ImportSimulationModelDialog from '../components/dialogs/import-simulation-model'; + +import SimulatorAction from '../components/simulator-action'; +import DeleteDialog from '../components/dialogs/delete-dialog'; + +class Simulation extends React.Component { + static getStores() { + return [ SimulationStore, SimulatorStore, SimulationModelStore, UserStore ]; + } + + static calculateState(prevState, props) { + // get selected simulation + const sessionToken = UserStore.getState().token; + + let simulation = SimulationStore.getState().find(s => s._id === props.match.params.simulation); + if (simulation == null) { + AppDispatcher.dispatch({ + type: 'simulations/start-load', + data: props.match.params.simulation, + token: sessionToken + }); + + simulation = {}; + } + + // load models + let simulationModels = []; + if (simulation.models != null) { + simulationModels = SimulationModelStore.getState().filter(m => m != null && simulation.models.includes(m._id)); + } + + return { + simulationModels, + simulation, + + simulators: SimulatorStore.getState(), + sessionToken, + + deleteModal: false, + importModal: false, + modalData: {}, + + selectedSimulationModels: [] + } + } + + componentWillMount() { + AppDispatcher.dispatch({ + type: 'simulations/start-load', + token: this.state.sessionToken + }); + + AppDispatcher.dispatch({ + type: 'simulationModels/start-load', + token: this.state.sessionToken + }); + + AppDispatcher.dispatch({ + type: 'simulators/start-load', + token: this.state.sessionToken + }); + } + + addSimulationModel = () => { + const simulationModel = { + simulation: this.state.simulation._id, + name: 'New Simulation Model', + simulator: this.state.simulators.length > 0 ? this.state.simulators[0]._id : null, + outputLength: 1, + outputMapping: [{ name: 'Signal', type: 'Type' }], + inputLength: 1, + inputMapping: [{ name: 'Signal', type: 'Type' }] + }; + + AppDispatcher.dispatch({ + type: 'simulationModels/start-add', + data: simulationModel, + token: this.state.sessionToken + }); + + this.setState({ simulation: {} }, () => { + AppDispatcher.dispatch({ + type: 'simulations/start-load', + data: this.props.match.params.simulation, + token: this.state.sessionToken + }); + }); + } + + closeDeleteModal = confirmDelete => { + this.setState({ deleteModal: false }); + + if (confirmDelete === false) { + return; + } + + AppDispatcher.dispatch({ + type: 'simulationModels/start-remove', + data: this.state.modalData, + token: this.state.sessionToken + }); + } + + importSimulationModel = simulationModel => { + this.setState({ importModal: false }); + + if (simulationModel == null) { + return; + } + + simulationModel.simulation = this.state.simulation._id; + + console.log(simulationModel); + + AppDispatcher.dispatch({ + type: 'simulationModels/start-add', + data: simulationModel, + token: this.state.sessionToken + }); + + this.setState({ simulation: {} }, () => { + AppDispatcher.dispatch({ + type: 'simulations/start-load', + data: this.props.match.params.simulation, + token: this.state.sessionToken + }); + }); + } + + getSimulatorName(simulatorId) { + for (let simulator of this.state.simulators) { + if (simulator._id === simulatorId) { + return _.get(simulator, 'properties.name') || _.get(simulator, 'rawProperties.name') || simulator.uuid; + } + } + } + + exportModel(index) { + // filter properties + const model = Object.assign({}, this.state.simulationModels[index]); + + delete model.simulator; + delete model.simulation; + + // show save dialog + const blob = new Blob([JSON.stringify(model, null, 2)], { type: 'application/json' }); + FileSaver.saveAs(blob, 'simulation model - ' + model.name + '.json'); + } + + onSimulationModelChecked(index, event) { + const selectedSimulationModels = Object.assign([], this.state.selectedSimulationModels); + for (let key in selectedSimulationModels) { + if (selectedSimulationModels[key] === index) { + // update existing entry + if (event.target.checked) { + return; + } + + selectedSimulationModels.splice(key, 1); + + this.setState({ selectedSimulationModels }); + return; + } + } + + // add new entry + if (event.target.checked === false) { + return; + } + + selectedSimulationModels.push(index); + this.setState({ selectedSimulationModels }); + } + + runAction = action => { + for (let index of this.state.selectedSimulationModels) { + // get simulator for model + let simulator = null; + for (let sim of this.state.simulators) { + if (sim._id === this.state.simulationModels[index].simulator) { + simulator = sim; + } + } + + if (simulator == null) { + continue; + } + + if (action.data.action === 'start') { + action.data.parameters = this.state.simulationModels[index].startParameters; + } + + AppDispatcher.dispatch({ + type: 'simulators/start-action', + simulator, + data: action.data, + token: this.state.sessionToken + }); + } + } + + render() { + const buttonStyle = { + marginLeft: '10px' + }; + + return
+

{this.state.simulation.name}

+ + + this.onSimulationModelChecked(index, event)} width='30' /> + + this.getSimulatorName(simulator)} /> + + + this.setState({ deleteModal: true, modalData: this.state.simulationModels[index], modalIndex: index })} + onExport={index => this.exportModel(index)} + /> +
+ +
+ +
+ +
+ + +
+ +
+ + + + +
; + } +} + +export default Container.create(Simulation, { withProps: true }); diff --git a/src/containers/simulations.js b/src/containers/simulations.js new file mode 100644 index 0000000..2bd8a1d --- /dev/null +++ b/src/containers/simulations.js @@ -0,0 +1,328 @@ +/** + * File: simulations.js + * Author: Markus Grigull + * Date: 04.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React, { Component } from 'react'; +import { Container } from 'flux/utils'; +import { Button } from 'react-bootstrap'; +import FileSaver from 'file-saver'; + +import AppDispatcher from '../app-dispatcher'; +import SimulationStore from '../stores/simulation-store'; +import UserStore from '../stores/user-store'; +import SimulatorStore from '../stores/simulator-store'; +import SimulationModelStore from '../stores/simulation-model-store'; + +import Icon from '../components/icon'; +import Table from '../components/table'; +import TableColumn from '../components/table-column'; +import NewSimulationDialog from '../components/dialogs/new-simulation'; +import EditSimulationDialog from '../components/dialogs/edit-simulation'; +import ImportSimulationDialog from '../components/dialogs/import-simulation'; + +import SimulatorAction from '../components/simulator-action'; +import DeleteDialog from '../components/dialogs/delete-dialog'; + +class Simulations extends Component { + static getStores() { + return [ SimulationStore, UserStore, SimulatorStore, SimulationModelStore ]; + } + + static calculateState() { + const simulations = SimulationStore.getState(); + const simulationModels = SimulationModelStore.getState(); + const simulators = SimulatorStore.getState(); + + const sessionToken = UserStore.getState().token; + + return { + simulations, + simulationModels, + simulators, + sessionToken, + + newModal: false, + deleteModal: false, + editModal: false, + importModal: false, + modalSimulation: {}, + + selectedSimulations: [] + }; + } + + componentDidMount() { + AppDispatcher.dispatch({ + type: 'simulations/start-load', + token: this.state.sessionToken + }); + } + + componentDidUpdate() { + const simulationModelIds = []; + const simulatorIds = []; + + for (let simulation of this.state.simulations) { + for (let modelId of simulation.models) { + const model = this.state.simulationModels.find(m => m != null && m._id === modelId); + + if (model == null) { + simulationModelIds.push(modelId); + + continue; + } + + if (this.state.simulators.includes(s => s._id === model.simulator) === false) { + simulatorIds.push(model.simulator); + } + } + } + + if (simulationModelIds.length > 0) { + AppDispatcher.dispatch({ + type: 'simulationModels/start-load', + data: simulationModelIds, + token: this.state.sessionToken + }); + } + + if (simulatorIds.length > 0) { + AppDispatcher.dispatch({ + type: 'simulators/start-load', + data: simulatorIds, + token: this.state.sessionToken + }); + } + } + + closeNewModal(data) { + this.setState({ newModal : false }); + + if (data) { + AppDispatcher.dispatch({ + type: 'simulations/start-add', + data, + token: this.state.sessionToken + }); + } + } + + showDeleteModal(id) { + // get simulation by id + var deleteSimulation; + + this.state.simulations.forEach((simulation) => { + if (simulation._id === id) { + deleteSimulation = simulation; + } + }); + + this.setState({ deleteModal: true, modalSimulation: deleteSimulation }); + } + + closeDeleteModal = confirmDelete => { + this.setState({ deleteModal: false }); + + if (confirmDelete === false) { + return; + } + + AppDispatcher.dispatch({ + type: 'simulations/start-remove', + data: this.state.modalSimulation, + token: this.state.sessionToken + }); + } + + showEditModal(id) { + // get simulation by id + var editSimulation; + + this.state.simulations.forEach((simulation) => { + if (simulation._id === id) { + editSimulation = simulation; + } + }); + + this.setState({ editModal: true, modalSimulation: editSimulation }); + } + + closeEditModal(data) { + this.setState({ editModal : false }); + + if (data != null) { + AppDispatcher.dispatch({ + type: 'simulations/start-edit', + data, + token: this.state.sessionToken + }); + } + } + + closeImportModal(data) { + this.setState({ importModal: false }); + + if (data) { + AppDispatcher.dispatch({ + type: 'simulations/start-add', + data, + token: this.state.sessionToken + }); + } + } + + onModalKeyPress = (event) => { + if (event.key === 'Enter') { + event.preventDefault(); + + this.confirmDeleteModal(); + } + } + + exportSimulation(index) { + // filter properties + let simulation = Object.assign({}, this.state.simulations[index]); + delete simulation._id; + delete simulation.projects; + delete simulation.running; + delete simulation.user; + + simulation.models.forEach(model => { + delete model.simulator; + }); + + // show save dialog + const blob = new Blob([JSON.stringify(simulation, null, 2)], { type: 'application/json' }); + FileSaver.saveAs(blob, 'simulation - ' + simulation.name + '.json'); + } + + onSimulationChecked(index, event) { + const selectedSimulations = Object.assign([], this.state.selectedSimulations); + for (let key in selectedSimulations) { + if (selectedSimulations[key] === index) { + // update existing entry + if (event.target.checked) { + return; + } + + selectedSimulations.splice(key, 1); + + this.setState({ selectedSimulations }); + return; + } + } + + // add new entry + if (event.target.checked === false) { + return; + } + + selectedSimulations.push(index); + this.setState({ selectedSimulations }); + } + + runAction = action => { + for (let index of this.state.selectedSimulations) { + for (let model of this.state.simulations[index].models) { + // get simulation model + const simulationModel = this.state.simulationModels.find(m => m != null && m._id === model); + if (simulationModel == null) { + continue; + } + + // get simulator for model + let simulator = null; + for (let sim of this.state.simulators) { + if (sim._id === simulationModel.simulator) { + simulator = sim; + } + } + + if (simulator == null) { + continue; + } + + if (action.data.action === 'start') { + action.data.parameters = Object.assign({}, this.state.simulations[index].startParameters, simulationModel.startParameters); + } + + AppDispatcher.dispatch({ + type: 'simulators/start-action', + simulator, + data: action.data, + token: this.state.sessionToken + }); + } + } + } + + render() { + const buttonStyle = { + marginLeft: '10px' + }; + + return ( +
+

Simulations

+ + + this.onSimulationChecked(index, event)} width='30' /> + + this.setState({ editModal: true, modalSimulation: this.state.simulations[index] })} + onDelete={index => this.setState({ deleteModal: true, modalSimulation: this.state.simulations[index] })} + onExport={index => this.exportSimulation(index)} + /> +
+ +
+ +
+ +
+ + +
+ +
+ + this.closeNewModal(data)} /> + this.closeEditModal(data)} simulation={this.state.modalSimulation} /> + this.closeImportModal(data)} nodes={this.state.nodes} /> + + +
+ ); + } +} + +export default Container.create(Simulations); diff --git a/src/containers/simulators.js b/src/containers/simulators.js new file mode 100644 index 0000000..9e07bab --- /dev/null +++ b/src/containers/simulators.js @@ -0,0 +1,313 @@ +/** + * File: simulators.js + * Author: Markus Grigull + * Date: 02.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React, { Component } from 'react'; +import { Container } from 'flux/utils'; +import { Button } from 'react-bootstrap'; +import FileSaver from 'file-saver'; +import _ from 'lodash'; + +import AppDispatcher from '../app-dispatcher'; +import SimulatorStore from '../stores/simulator-store'; +import UserStore from '../stores/user-store'; + +import Icon from '../components/icon'; +import Table from '../components/table'; +import TableColumn from '../components/table-column'; +import NewSimulatorDialog from '../components/dialogs/new-simulator'; +import EditSimulatorDialog from '../components/dialogs/edit-simulator'; +import ImportSimulatorDialog from '../components/dialogs/import-simulator'; + +import SimulatorAction from '../components/simulator-action'; +import DeleteDialog from '../components/dialogs/delete-dialog'; + +class Simulators extends Component { + static getStores() { + return [ UserStore, SimulatorStore ]; + } + + static statePrio(state) { + switch (state) { + case 'running': + case 'starting': + return 1; + case 'paused': + case 'pausing': + case 'resuming': + return 2; + case 'idle': + return 3; + case 'shutdown': + return 4; + case 'error': + return 10; + default: + return 99; + } + } + + static calculateState() { + const simulators = SimulatorStore.getState().sort((a, b) => { + if (a.state !== b.state) + return this.statePrio(a.state) > this.statePrio(b.state); + else if (a.name !== b.name) + return a.name < b.name; + else + return a.stateUpdatedAt < b.stateUpdatedAt; + }); + + return { + sessionToken: UserStore.getState().token, + simulators, + modalSimulator: {}, + deleteModal: false, + + selectedSimulators: [] + }; + } + + componentWillMount() { + AppDispatcher.dispatch({ + type: 'simulators/start-load', + token: this.state.sessionToken + }); + + // Start timer for periodic refresh + this.timer = window.setInterval(() => this.refresh(), 1000); + } + + componentWillUnmount() { + window.clearInterval(this.timer); + } + + refresh() { + AppDispatcher.dispatch({ + type: 'simulators/start-load', + token: this.state.sessionToken + }); + } + + + closeNewModal(data) { + this.setState({ newModal : false }); + + if (data) { + AppDispatcher.dispatch({ + type: 'simulators/start-add', + data, + token: this.state.sessionToken + }); + } + } + + closeEditModal(data) { + this.setState({ editModal : false }); + + if (data) { + let simulator = this.state.simulators[this.state.modalIndex]; + simulator.properties = data; + this.setState({ simulator }); + + AppDispatcher.dispatch({ + type: 'simulators/start-edit', + data: simulator, + token: this.state.sessionToken + }); + } + } + + closeDeleteModal = confirmDelete => { + this.setState({ deleteModal: false }); + + if (confirmDelete === false) { + return; + } + + AppDispatcher.dispatch({ + type: 'simulators/start-remove', + data: this.state.modalSimulator, + token: this.state.sessionToken + }); + } + + exportSimulator(index) { + // filter properties + let simulator = Object.assign({}, this.state.simulators[index]); + delete simulator._id; + + // show save dialog + const blob = new Blob([JSON.stringify(simulator, null, 2)], { type: 'application/json' }); + FileSaver.saveAs(blob, 'simulator - ' + (_.get(simulator, 'properties.name') || _.get(simulator, 'rawProperties.name') || 'undefined') + '.json'); + } + + closeImportModal(data) { + this.setState({ importModal: false }); + + if (data) { + AppDispatcher.dispatch({ + type: 'simulators/start-add', + data, + token: this.state.sessionToken + }); + } + } + + onSimulatorChecked(index, event) { + const selectedSimulators = Object.assign([], this.state.selectedSimulators); + for (let key in selectedSimulators) { + if (selectedSimulators[key] === index) { + // update existing entry + if (event.target.checked) { + return; + } + + selectedSimulators.splice(key, 1); + + this.setState({ selectedSimulators }); + return; + } + } + + // add new entry + if (event.target.checked === false) { + return; + } + + selectedSimulators.push(index); + this.setState({ selectedSimulators }); + } + + runAction = action => { + for (let index of this.state.selectedSimulators) { + AppDispatcher.dispatch({ + type: 'simulators/start-action', + simulator: this.state.simulators[index], + data: action.data, + token: this.state.sessionToken + }); + } + } + + isSimulatorOutdated(simulator) { + if (!simulator.stateUpdatedAt) + return true; + + const fiveMinutes = 5 * 60 * 1000; + + return Date.now() - new Date(simulator.stateUpdatedAt) > fiveMinutes; + } + + stateLabelStyle = (state, simulator) => { + var style = [ 'label' ]; + + if (this.isSimulatorOutdated(simulator) && state !== 'shutdown') { + style.push('label-outdated'); + } + + switch (state) { + case 'running': + style.push('label-success'); + break; + + case 'paused': + style.push('label-info'); + break; + + case 'idle': + style.push('label-primary'); + break; + + case 'error': + style.push('label-danger'); + break; + + case 'shutdown': + style.push('label-warning'); + break; + + default: + style.push('label-default'); + } + + return style.join(' '); + } + + stateUpdateModifier = updatedAt => { + const date = new Date(updatedAt); + + return date.toLocaleString('de-DE'); + } + + render() { + const buttonStyle = { + marginLeft: '10px' + }; + + return ( +
+

Simulators

+ + + this.onSimulatorChecked(index, event)} width='30' /> + + + + + + {/* */} + + + this.setState({ editModal: true, modalSimulator: this.state.simulators[index], modalIndex: index })} + onExport={index => this.exportSimulator(index)} + onDelete={index => this.setState({ deleteModal: true, modalSimulator: this.state.simulators[index], modalIndex: index })} + /> +
+ +
+ +
+ +
+ + +
+ +
+ + this.closeNewModal(data)} /> + this.closeEditModal(data)} simulator={this.state.modalSimulator} /> + this.closeImportModal(data)} /> + + +
+ ); + } +} + +export default Container.create(Simulators); diff --git a/src/containers/users.js b/src/containers/users.js new file mode 100644 index 0000000..1e1779e --- /dev/null +++ b/src/containers/users.js @@ -0,0 +1,142 @@ +/** + * File: users.js + * Author: Ricardo Hernandez-Montoya + * Date: 02.05.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React, { Component } from 'react'; +import { Container } from 'flux/utils'; +import { Button } from 'react-bootstrap'; + +import AppDispatcher from '../app-dispatcher'; +import UserStore from '../stores/user-store'; +import UsersStore from '../stores/users-store'; + +import Icon from '../components/icon'; +import Table from '../components/table'; +import TableColumn from '../components/table-column'; +import NewUserDialog from '../components/dialogs/new-user'; +import EditUserDialog from '../components/dialogs/edit-user'; + +import DeleteDialog from '../components/dialogs/delete-dialog'; + +class Users extends Component { + static getStores() { + return [ UserStore, UsersStore ]; + } + + static calculateState(prevState, props) { + + let tokenState = UserStore.getState().token; + + // If there is a token available and this method was called as a result of loading users + if (!prevState && tokenState) { + AppDispatcher.dispatch({ + type: 'users/start-load', + token: tokenState + }); + } + + return { + token: tokenState, + users: UsersStore.getState(), + + newModal: false, + editModal: false, + deleteModal: false, + modalData: {} + }; + } + + closeNewModal(data) { + this.setState({ newModal: false }); + + if (data) { + AppDispatcher.dispatch({ + type: 'users/start-add', + data: data, + token: this.state.token + }); + } + } + + closeDeleteModal = confirmDelete => { + this.setState({ deleteModal: false }); + + if (confirmDelete === false) { + return; + } + + AppDispatcher.dispatch({ + type: 'users/start-remove', + data: this.state.modalData, + token: this.state.token + }); + } + + closeEditModal(data) { + this.setState({ editModal: false }); + + if (data) { + AppDispatcher.dispatch({ + type: 'users/start-edit', + data: data, + token: this.state.token + }); + } + } + + getHumanRoleName(role_key) { + const HUMAN_ROLE_NAMES = {admin: 'Administrator', user: 'User', guest: 'Guest'}; + + return HUMAN_ROLE_NAMES.hasOwnProperty(role_key)? HUMAN_ROLE_NAMES[role_key] : ''; + } + + onModalKeyPress = (event) => { + if (event.key === 'Enter') { + event.preventDefault(); + + this.confirmDeleteModal(); + } + } + + render() { + + return ( +
+

Users

+ + + + + this.getHumanRoleName(role)} /> + this.setState({ editModal: true, modalData: this.state.users[index] })} onDelete={index => this.setState({ deleteModal: true, modalData: this.state.users[index] })} /> +
+ + + + this.closeNewModal(data)} /> + this.closeEditModal(data)} user={this.state.modalData} /> + + +
+ ); + } +} + +export default Container.create(Users); diff --git a/src/containers/visualization.js b/src/containers/visualization.js new file mode 100644 index 0000000..a9e53ff --- /dev/null +++ b/src/containers/visualization.js @@ -0,0 +1,550 @@ +/** + * File: visualization.js + * Author: Markus Grigull + * Date: 02.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { Container } from 'flux/utils'; +import { Button, ButtonToolbar } from 'react-bootstrap'; +import { ContextMenu, Item, Separator } from 'react-contexify'; +import Fullscreenable from 'react-fullscreenable'; +import Slider from 'rc-slider'; +import classNames from 'classnames'; + +import Icon from '../components/icon'; +import WidgetFactory from '../components/widget-factory'; +import ToolboxItem from '../components/toolbox-item'; +import Dropzone from '../components/dropzone'; +import Widget from './widget'; +import EditWidget from '../components/dialogs/edit-widget'; +import Grid from '../components/grid'; + +import UserStore from '../stores/user-store'; +import VisualizationStore from '../stores/visualization-store'; +import ProjectStore from '../stores/project-store'; +import SimulationStore from '../stores/simulation-store'; +import SimulationModelStore from '../stores/simulation-model-store'; +import FileStore from '../stores/file-store'; +import AppDispatcher from '../app-dispatcher'; +import NotificationsDataManager from '../data-managers/notifications-data-manager'; +import NotificationsFactory from '../data-managers/notifications-factory'; + +import 'react-contexify/dist/ReactContexify.min.css'; + +class Visualization extends React.Component { + static getStores() { + return [ VisualizationStore, ProjectStore, SimulationStore, SimulationModelStore, FileStore, UserStore ]; + } + + static calculateState(prevState, props) { + if (prevState == null) { + prevState = {}; + } + + let simulationModels = []; + if (prevState.simulation != null) { + simulationModels = SimulationModelStore.getState().filter(m => prevState.simulation.models.includes(m._id)); + } + + return { + sessionToken: UserStore.getState().token, + visualizations: VisualizationStore.getState(), + projects: ProjectStore.getState(), + simulations: SimulationStore.getState(), + files: FileStore.getState(), + + visualization: prevState.visualization || {}, + project: prevState.project || null, + simulation: prevState.simulation || null, + simulationModels, + editing: prevState.editing || false, + paused: prevState.paused || false, + + editModal: prevState.editModal || false, + modalData: prevState.modalData || null, + modalIndex: prevState.modalIndex || null, + + maxWidgetHeight: prevState.maxWidgetHeight || 0, + dropZoneHeight: prevState.dropZoneHeight || 0 + }; + } + + componentWillMount() { + // TODO: Don't fetch token from local, use user-store! + const token = localStorage.getItem('token'); + + //document.addEventListener('keydown', this.handleKeydown.bind(this)); + + AppDispatcher.dispatch({ + type: 'visualizations/start-load', + token + }); + } + + componentWillUnmount() { + //document.removeEventListener('keydown', this.handleKeydown.bind(this)); + } + + componentDidUpdate() { + if (this.state.visualization._id !== this.props.match.params.visualization) { + this.reloadVisualization(); + } + + // load depending project + if (this.state.project == null && this.state.projects) { + this.state.projects.forEach((project) => { + if (project._id === this.state.visualization.project) { + this.setState({ project: project, simulation: null }); + + const token = localStorage.getItem('token'); + + AppDispatcher.dispatch({ + type: 'simulations/start-load', + data: project.simulation, + token + }); + } + }); + } + + // load depending simulation + if (this.state.simulation == null && this.state.simulations && this.state.project) { + this.state.simulations.forEach((simulation) => { + if (simulation._id === this.state.project.simulation) { + this.setState({ simulation: simulation }); + } + }); + } + } + + /*handleKeydown(e) { + switch (e.key) { + case ' ': + case 'p': + this.setState({ paused: !this.state.paused }); + break; + case 'e': + this.setState({ editing: !this.state.editing }); + break; + case 'f': + this.props.toggleFullscreen(); + break; + default: + } + }*/ + + transformToWidgetsDict(widgets) { + var widgetsDict = {}; + // Create a new key and make a copy of the widget object + var key = 0; + widgets.forEach( (widget) => widgetsDict[key++] = Object.assign({}, widget) ); + return widgetsDict; + } + + transformToWidgetsList(widgets) { + return Object.keys(widgets).map( (key) => widgets[key]); + } + + reloadVisualization() { + // select visualization by param id + this.state.visualizations.forEach((tempVisualization) => { + if (tempVisualization._id === this.props.match.params.visualization) { + + // convert widgets list to a dictionary + var visualization = Object.assign({}, tempVisualization, { + widgets: tempVisualization.widgets ? this.transformToWidgetsDict(tempVisualization.widgets) : {} + }); + + this.computeHeightWithWidgets(visualization.widgets); + + this.setState({ visualization: visualization, project: null }); + + const token = localStorage.getItem('token'); + + AppDispatcher.dispatch({ + type: 'projects/start-load', + data: visualization.project, + token + }); + } + }); + } + + snapToGrid(value) { + if (this.state.visualization.grid === 1) return value; + + return Math.round(value / this.state.visualization.grid) * this.state.visualization.grid; + } + + handleDrop(item, position) { + + let widget = null; + let defaultSimulationModel = null; + + if (this.state.simulation.models && this.state.simulation.models.length === 0) { + NotificationsDataManager.addNotification(NotificationsFactory.NO_SIM_MODEL_AVAILABLE); + } else { + defaultSimulationModel = this.state.simulation.models[0]; + } + + // snap position to grid + position.x = this.snapToGrid(position.x); + position.y = this.snapToGrid(position.y); + + // create new widget + widget = WidgetFactory.createWidgetOfType(item.name, position, defaultSimulationModel); + + var new_widgets = this.state.visualization.widgets; + var new_key = Object.keys(new_widgets).length; + + new_widgets[new_key] = widget; + + var visualization = Object.assign({}, this.state.visualization, { + widgets: new_widgets + }); + + this.increaseHeightWithWidget(widget); + this.setState({ visualization: visualization }); + } + + widgetStatusChange(updated_widget, key) { + // Widget changed internally, make changes effective then save them + this.widgetChange(updated_widget, key, this.saveChanges); + } + + widgetChange(updated_widget, key, callback = null) { + var widgets_update = {}; + widgets_update[key] = updated_widget; + var new_widgets = Object.assign({}, this.state.visualization.widgets, widgets_update); + + var visualization = Object.assign({}, this.state.visualization, { + widgets: new_widgets + }); + + // Check if the height needs to be increased, the section may have shrunk if not + if (!this.increaseHeightWithWidget(updated_widget)) { + this.computeHeightWithWidgets(visualization.widgets); + } + this.setState({ visualization: visualization }, callback); + } + + /* + * Set the initial height state based on the existing widgets + */ + computeHeightWithWidgets(widgets) { + // Compute max height from widgets + let maxHeight = Object.keys(widgets).reduce( (maxHeightSoFar, widgetKey) => { + let thisWidget = widgets[widgetKey]; + let thisWidgetHeight = thisWidget.y + thisWidget.height; + + return thisWidgetHeight > maxHeightSoFar? thisWidgetHeight : maxHeightSoFar; + }, 0); + + this.setState({ + maxWidgetHeight: maxHeight, + dropZoneHeight: maxHeight + 80 + }); + } + /* + * Adapt the area's height with the position of the new widget. + * Return true if the height increased, otherwise false. + */ + increaseHeightWithWidget(widget) { + let increased = false; + let thisWidgetHeight = widget.y + widget.height; + if (thisWidgetHeight > this.state.maxWidgetHeight) { + increased = true; + this.setState({ + maxWidgetHeight: thisWidgetHeight, + dropZoneHeight: thisWidgetHeight + 40 + }); + } + return increased; + } + + editWidget(e, data) { + this.setState({ editModal: true, modalData: this.state.visualization.widgets[data.key], modalIndex: data.key }); + } + + closeEdit(data) { + if (data) { + // save changes temporarily + var widgets_update = {}; + widgets_update[this.state.modalIndex] = data; + + var new_widgets = Object.assign({}, this.state.visualization.widgets, widgets_update); + + var visualization = Object.assign({}, this.state.visualization, { + widgets: new_widgets + }); + + this.setState({ editModal: false, visualization: visualization }); + } else { + this.setState({ editModal: false }); + } + } + + deleteWidget(e, data) { + delete this.state.visualization.widgets[data.key]; + var visualization = Object.assign({}, this.state.visualization, { + widgets: this.state.visualization.widgets + }); + this.setState({ visualization: visualization }); + } + + stopEditing() { + // Provide the callback so it can be called when state change is applied + this.setState({ editing: false }, this.saveChanges ); + } + + saveChanges() { + // Transform to a list + var visualization = Object.assign({}, this.state.visualization, { + widgets: this.transformToWidgetsList(this.state.visualization.widgets) + }); + + const token = localStorage.getItem('token'); + + AppDispatcher.dispatch({ + type: 'visualizations/start-edit', + data: visualization, + token + }); + } + + discardChanges() { + this.setState({ editing: false, visualization: {} }); + + this.reloadVisualization(); + } + + moveWidget(e, data, applyDirection) { + var widget = this.state.visualization.widgets[data.key]; + var updated_widgets = {}; + updated_widgets[data.key] = applyDirection(widget); + var new_widgets = Object.assign({}, this.state.visualization.widgets, updated_widgets); + + var visualization = Object.assign({}, this.state.visualization, { + widgets: new_widgets + }); + + this.setState({ visualization: visualization }); + } + + moveAbove(widget) { + // increase z-Order + widget.z++; + return widget; + } + + moveToFront(widget) { + // increase z-Order + widget.z = 100; + return widget; + } + + moveUnderneath(widget) { + // decrease z-Order + widget.z--; + if (widget.z < 0) { + widget.z = 0; + } + return widget; + } + + moveToBack(widget) { + // increase z-Order + widget.z = 0; + return widget; + } + + setGrid(value) { + // value 0 would block all widgets, set 1 as 'grid disabled' + if (value === 0) { + value = 1; + } + + let visualization = Object.assign({}, this.state.visualization, { + grid: value + }); + + this.setState({ visualization }); + } + + lockWidget(data) { + // lock the widget + let widget = this.state.visualization.widgets[data.key]; + widget.locked = true; + + // update visualization + let widgets = {}; + widgets[data.key] = widget; + widgets = Object.assign({}, this.state.visualization.widgets, widgets); + + const visualization = Object.assign({}, this.state.visualization, { widgets }); + this.setState({ visualization }); + } + + unlockWidget(data) { + // lock the widget + let widget = this.state.visualization.widgets[data.key]; + widget.locked = false; + + // update visualization + let widgets = {}; + widgets[data.key] = widget; + widgets = Object.assign({}, this.state.visualization.widgets, widgets); + + const visualization = Object.assign({}, this.state.visualization, { widgets }); + this.setState({ visualization }); + } + + pauseData = () => { + this.setState({ paused: true }); + } + + unpauseData = () => { + this.setState({ paused: false }); + } + + render() { + const current_widgets = this.state.visualization.widgets; + + let boxClasses = classNames('section', 'box', { 'fullscreen-container': this.props.isFullscreen }); + + let buttons = [] + let editingControls = []; + let gridControl = {}; + + if (this.state.editing) { + buttons.push({ click: () => this.stopEditing(), icon: 'save', text: 'Save' }); + buttons.push({ click: () => this.discardChanges(), icon: 'ban', text: 'Cancel' }); + + gridControl =
+ Grid: {this.state.visualization.grid > 1 ? this.state.visualization.grid : 'Disabled'} + this.setGrid(value)} /> +
+ } + + if (!this.props.isFullscreen) { + buttons.push({ click: this.props.toggleFullscreen, icon: 'expand', text: 'Fullscreen' }); + buttons.push({ click: this.state.paused ? this.unpauseData : this.pauseData, icon: this.state.paused ? 'play' : 'pause', text: this.state.paused ? 'Live' : 'Pause' }); + + if (!this.state.editing) + buttons.push({ click: () => this.setState({ editing: true }), icon: 'edit', text: 'Edit' }); + } + + const buttonList = buttons.map((btn, idx) => + + ); + + // Only one topology widget at the time is supported + let thereIsTopologyWidget = current_widgets && Object.values(current_widgets).filter( widget => widget.type === 'Topology').length > 0; + let topologyItemMsg = !thereIsTopologyWidget? '' : 'Currently only one is supported'; + + return ( +
+
+
+ {this.state.visualization.name} +
+ +
+ { this.state.editing && gridControl } + { buttonList } +
+
+ +
e.preventDefault() }> + {this.state.editing && +
+ + { editingControls } + + + + + + + + + + + + + + + + + + + +
+ } + + this.handleDrop(item, position)} editing={this.state.editing}> + {current_widgets != null && + Object.keys(current_widgets).map(widget_key => ( + this.widgetChange(w, k)} + onWidgetStatusChange={(w, k) => this.widgetStatusChange(w, k)} + editing={this.state.editing} + index={widget_key} + grid={this.state.visualization.grid} + paused={this.state.paused} + /> + ))} + + + + + {current_widgets != null && + Object.keys(current_widgets).map(widget_key => { + const data = { key: widget_key }; + + const locked = this.state.visualization.widgets[widget_key].locked; + const disabledMove = locked || this.state.visualization.widgets[widget_key].type === 'Box'; + + return + this.editWidget(e, data)}>Edit + this.deleteWidget(e, data)}>Delete + + this.moveWidget(e, data, this.moveAbove)}>Move above + this.moveWidget(e, data, this.moveToFront)}>Move to front + this.moveWidget(e, data, this.moveUnderneath)}>Move underneath + this.moveWidget(e, data, this.moveToBack)}>Move to back + + this.lockWidget(data)}>Lock + this.unlockWidget(data)}>Unlock + + })} + + this.closeEdit(data)} widget={this.state.modalData} simulationModels={this.state.simulationModels} files={this.state.files} /> +
+
+ ); + } +} + +export default Fullscreenable()(Container.create(Visualization, { withProps: true })); diff --git a/src/containers/widget.js b/src/containers/widget.js new file mode 100644 index 0000000..b4df992 --- /dev/null +++ b/src/containers/widget.js @@ -0,0 +1,297 @@ +/** + * File: widget.js + * Author: Markus Grigull + * Date: 04.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { Container } from 'flux/utils'; +import { ContextMenuProvider } from 'react-contexify'; +import Rnd from 'react-rnd'; +import classNames from 'classnames'; + +import AppDispatcher from '../app-dispatcher'; +import UserStore from '../stores/user-store'; +import SimulatorDataStore from '../stores/simulator-data-store'; +import SimulationModelStore from '../stores/simulation-model-store'; +import FileStore from '../stores/file-store'; + +import WidgetCustomAction from '../components/widgets/custom-action'; +import WidgetAction from '../components/widgets/action'; +import WidgetLamp from '../components/widgets/lamp'; +import WidgetValue from '../components/widgets/value'; +import WidgetPlot from '../components/widgets/plot'; +import WidgetTable from '../components/widgets/table'; +import WidgetLabel from '../components/widgets/label'; +import WidgetPlotTable from '../components/widgets/plot-table'; +import WidgetImage from '../components/widgets/image'; +import WidgetButton from '../components/widgets/button'; +import WidgetInput from '../components/widgets/input'; +import WidgetSlider from '../components/widgets/slider'; +import WidgetGauge from '../components/widgets/gauge'; +import WidgetBox from '../components/widgets/box'; +import WidgetHTML from '../components/widgets/html'; +import WidgetTopology from '../components/widgets/topology'; + +import '../styles/widgets.css'; + +class Widget extends React.Component { + static getStores() { + return [ SimulatorDataStore, SimulationModelStore, FileStore, UserStore ]; + } + + static calculateState(prevState, props) { + const sessionToken = UserStore.getState().token; + + let simulatorData = {}; + + if (props.paused) { + if (prevState && prevState.simulatorData) { + simulatorData = JSON.parse(JSON.stringify(prevState.simulatorData)); + } + } else { + simulatorData = SimulatorDataStore.getState(); + } + + if (prevState) { + return { + sessionToken, + simulatorData, + files: FileStore.getState(), + sequence: prevState.sequence + 1, + + simulationModels: SimulationModelStore.getState() + }; + } else { + return { + sessionToken, + simulatorData, + files: FileStore.getState(), + sequence: 0, + + simulationModels: SimulationModelStore.getState() + }; + } + } + + constructor(props) { + super(props); + + // Reference to the context menu element + this.contextMenuTriggerViaDraggable = null; + } + + componentWillMount() { + // If loading for the first time + if (this.state.sessionToken) { + AppDispatcher.dispatch({ + type: 'files/start-load', + token: this.state.sessionToken + }); + + AppDispatcher.dispatch({ + type: 'simulationModels/start-load', + token: this.state.sessionToken + }); + } + } + + snapToGrid(value) { + if (this.props.grid === 1) + return value; + + return Math.round(value / this.props.grid) * this.props.grid; + } + + drag(event, data) { + const x = this.snapToGrid(data.x); + const y = this.snapToGrid(data.y); + + if (x !== data.x || y !== data.y) { + this.rnd.updatePosition({ x, y }); + } + } + + dragStop(event, data) { + // update widget + let widget = this.props.data; + widget.x = this.snapToGrid(data.x); + widget.y = this.snapToGrid(data.y); + + this.props.onWidgetChange(widget, this.props.index); + } + + resizeStop(direction, delta, event) { + // update widget + let widget = Object.assign({}, this.props.data); + + // resize depends on direction + if (direction === 'left' || direction === 'topLeft' || direction === 'bottomLeft') { + widget.x -= delta.width; + } + + if (direction === 'top' || direction === 'topLeft' || direction === 'topRight') { + widget.y -= delta.height; + } + + widget.width += delta.width; + widget.height += delta.height; + + this.props.onWidgetChange(widget, this.props.index); + } + + borderWasClicked(e) { + // check if it was triggered by the right button + if (e.button === 2) { + // launch the context menu using the reference + if(this.contextMenuTriggerViaDraggable) { + this.contextMenuTriggerViaDraggable.handleContextClick(e); + } + } + } + + inputDataChanged(widget, data) { + let simulationModel = null; + + for (let model of this.state.simulationModels) { + if (model._id !== widget.simulationModel) { + continue; + } + + simulationModel = model; + } + + AppDispatcher.dispatch({ + type: 'simulatorData/inputChanged', + simulator: simulationModel.simulator, + signal: widget.signal, + data + }); + } + + render() { + // configure grid + const grid = [this.props.grid, this.props.grid]; + + // get widget element + const widget = this.props.data; + let borderedWidget = false; + let element = null; + let zIndex = Number(widget.z); + + let simulationModel = null; + + for (let model of this.state.simulationModels) { + if (model._id !== widget.simulationModel) { + continue; + } + + simulationModel = model; + } + + // dummy is passed to widgets to keep updating them while in edit mode + if (widget.type === 'CustomAction') { + element = + } else if (widget.type === 'Action') { + element = + } else if (widget.type === 'Lamp') { + element = + } else if (widget.type === 'Value') { + element = + } else if (widget.type === 'Plot') { + element = + } else if (widget.type === 'Table') { + element = + } else if (widget.type === 'Label') { + element = + } else if (widget.type === 'PlotTable') { + element = this.props.onWidgetStatusChange(w, this.props.index)} paused={this.props.paused} /> + } else if (widget.type === 'Image') { + element = + } else if (widget.type === 'Button') { + element = this.inputDataChanged(widget, value)} /> + } else if (widget.type === 'Input') { + element = this.inputDataChanged(widget, value)} /> + } else if (widget.type === 'Slider') { + element = this.inputDataChanged(widget, value)} onWidgetChange={(w) => this.props.onWidgetStatusChange(w, this.props.index) } /> + } else if (widget.type === 'Gauge') { + element = + } else if (widget.type === 'Box') { + element = + } else if (widget.type === 'HTML') { + element = + } else if (widget.type === 'Topology') { + element = + } + + if (widget.type === 'Box') + zIndex = 0; + + const widgetClasses = classNames({ + 'widget': !this.props.editing, + 'editing-widget': this.props.editing, + 'border': borderedWidget, + 'unselectable': false, + 'locked': widget.locked && this.props.editing + }); + + if (this.props.editing) { + const resizing = { bottom: !widget.locked, bottomLeft: !widget.locked, bottomRight: !widget.locked, left: !widget.locked, right: !widget.locked, top: !widget.locked, topLeft: !widget.locked, topRight: !widget.locked}; + + return ( + { this.rnd = c; }} + default={{ x: Number(widget.x), y: Number(widget.y), width: widget.width, height: widget.height }} + minWidth={widget.minWidth} + minHeight={widget.minHeight} + lockAspectRatio={Boolean(widget.lockAspect)} + bounds={'parent'} + className={ widgetClasses } + onResizeStart={(event, direction, ref) => this.borderWasClicked(event)} + onResizeStop={(event, direction, ref, delta) => this.resizeStop(direction, delta, event)} + onDrag={(event, data) => this.drag(event, data)} + onDragStop={(event, data) => this.dragStop(event, data)} + dragGrid={grid} + resizeGrid={grid} + z={zIndex} + enableResizing={resizing} + disableDragging={widget.locked} + > + + {element} + + + ); + } else { + return ( +
+ {element} +
+ ); + } + } +} + +export default Container.create(Widget, { withProps: true }); diff --git a/src/data-managers/files-data-manager.js b/src/data-managers/files-data-manager.js new file mode 100644 index 0000000..b9fbd91 --- /dev/null +++ b/src/data-managers/files-data-manager.js @@ -0,0 +1,56 @@ +/** + * File: files-data-manager.js + * Author: Markus Grigull + * Date: 16.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import RestDataManager from './rest-data-manager'; +import RestAPI from '../api/rest-api'; +import AppDispatcher from '../app-dispatcher'; + +class FilesDataManager extends RestDataManager { + constructor() { + super('file', '/files'); + } + + upload(file, token = null, progressCallback = null, finishedCallback = null) { + RestAPI.upload(this.makeURL('/upload'), file, token, progressCallback).then(response => { + + AppDispatcher.dispatch({ + type: 'files/uploaded', + }); + + // Trigger a files reload + AppDispatcher.dispatch({ + type: 'files/start-load', + token + }); + + if (finishedCallback) { + finishedCallback(); + } + }).catch(error => { + AppDispatcher.dispatch({ + type: 'files/upload-error', + error + }); + }); + } +} + +export default new FilesDataManager(); diff --git a/src/data-managers/notifications-data-manager.js b/src/data-managers/notifications-data-manager.js new file mode 100644 index 0000000..f463fcd --- /dev/null +++ b/src/data-managers/notifications-data-manager.js @@ -0,0 +1,34 @@ +/** + * File: notifications-data-manager.js + * Author: Markus Grigull + * Date: 21.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +class NotificationsDataManager { + _notificationSystem = null; + + setSystem(notificationSystem) { + this._notificationSystem = notificationSystem; + } + + addNotification(notification) { + this._notificationSystem.addNotification(notification); + } +} + +export default new NotificationsDataManager(); diff --git a/src/data-managers/notifications-factory.js b/src/data-managers/notifications-factory.js new file mode 100644 index 0000000..4f2a079 --- /dev/null +++ b/src/data-managers/notifications-factory.js @@ -0,0 +1,37 @@ +/** + * File: notifications-factory.js + * Description: An unique source of pre-defined notifications that are displayed + * throughout the application. + * Author: Ricardo Hernandez-Montoya + * Date: 13.04.2017 + * Copyright: 2018, Institute for Automation of Complex Power Systems, EONERC + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +class NotificationsFactory { + + static get NO_SIM_MODEL_AVAILABLE() { + return { + title: 'No simulation model available', + message: 'Consider defining a simulation model in the simulators section.', + level: 'warning' + }; + } + +} + +export default NotificationsFactory; diff --git a/src/data-managers/projects-data-manager.js b/src/data-managers/projects-data-manager.js new file mode 100644 index 0000000..e1b8167 --- /dev/null +++ b/src/data-managers/projects-data-manager.js @@ -0,0 +1,24 @@ +/** + * File: projects-data-manager.js + * Author: Markus Grigull + * Date: 07.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import RestDataManager from './rest-data-manager'; + +export default new RestDataManager('project', '/projects'); diff --git a/src/data-managers/rest-data-manager.js b/src/data-managers/rest-data-manager.js new file mode 100644 index 0000000..dbd278e --- /dev/null +++ b/src/data-managers/rest-data-manager.js @@ -0,0 +1,149 @@ +/** + * File: rest-data-manager.js + * Author: Markus Grigull + * Date: 03.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import RestAPI from '../api/rest-api'; +import AppDispatcher from '../app-dispatcher'; + +const API_URL = '/api/v1'; + +class RestDataManager { + constructor(type, url, keyFilter) { + this.url = url; + this.type = type; + this.keyFilter = keyFilter; + this.onLoad = null; + } + + makeURL(part) { + return API_URL + part; + } + + filterKeys(object) { + // don't change anything if no filter is set + if (this.keyFilter == null || Array.isArray(this.keyFilter) === false) { + return object; + } + + // remove all keys not in the filter + Object.keys(object).filter(key => { + return this.keyFilter.indexOf(key) === -1; + }).forEach(key => { + delete object[key]; + }); + + return object; + } + + load(id, token = null) { + if (id != null) { + // load single object + RestAPI.get(this.makeURL(this.url + '/' + id), token).then(response => { + const data = this.filterKeys(response[this.type]); + + AppDispatcher.dispatch({ + type: this.type + 's/loaded', + data: data + }); + + if (this.onLoad != null) { + this.onLoad(data); + } + }).catch(error => { + AppDispatcher.dispatch({ + type: this.type + 's/load-error', + error: error + }); + }); + } else { + // load all objects + RestAPI.get(this.makeURL(this.url), token).then(response => { + const data = response[this.type + 's'].map(element => { + return this.filterKeys(element); + }); + + AppDispatcher.dispatch({ + type: this.type + 's/loaded', + data: data + }); + + if (this.onLoad != null) { + this.onLoad(data); + } + }).catch(error => { + AppDispatcher.dispatch({ + type: this.type + 's/load-error', + error: error + }); + }); + } + } + + add(object, token = null) { + var obj = {}; + obj[this.type] = this.filterKeys(object); + + RestAPI.post(this.makeURL(this.url), obj, token).then(response => { + AppDispatcher.dispatch({ + type: this.type + 's/added', + data: response[this.type] + }); + }).catch(error => { + AppDispatcher.dispatch({ + type: this.type + 's/add-error', + error: error + }); + }); + } + + remove(object, token = null) { + RestAPI.delete(this.makeURL(this.url + '/' + object._id), token).then(response => { + AppDispatcher.dispatch({ + type: this.type + 's/removed', + data: response[this.type], + original: object + }); + }).catch(error => { + AppDispatcher.dispatch({ + type: this.type + 's/remove-error', + error: error + }); + }); + } + + update(object, token = null) { + var obj = {}; + obj[this.type] = this.filterKeys(object); + + RestAPI.put(this.makeURL(this.url + '/' + object._id), obj, token).then(response => { + AppDispatcher.dispatch({ + type: this.type + 's/edited', + data: response[this.type] + }); + }).catch(error => { + AppDispatcher.dispatch({ + type: this.type + 's/edit-error', + error: error + }); + }); + } +}; + +export default RestDataManager; diff --git a/src/data-managers/simulation-models-data-manager.js b/src/data-managers/simulation-models-data-manager.js new file mode 100644 index 0000000..5496268 --- /dev/null +++ b/src/data-managers/simulation-models-data-manager.js @@ -0,0 +1,50 @@ +/** + * File: simulation-models-data-manager.js + * Author: Markus Grigull + * Date: 20.04.2018 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import RestDataManager from './rest-data-manager'; +import AppDispatcher from '../app-dispatcher'; + +class SimulationModelDataManager extends RestDataManager { + constructor() { + super('simulationModel', '/models'); + + this.onLoad = this.onModelsLoad; + } + + onModelsLoad(data) { + if (!Array.isArray(data)) + data = [ data ]; + + for (let model of data) + this.loadModelData(model); + } + + loadModelData(model) { + AppDispatcher.dispatch({ + type: 'simulatorData/prepare', + inputLength: parseInt(model.inputLength, 10), + outputLength: parseInt(model.outputLength, 10), + id: model.simulator + }); + } +} + +export default new SimulationModelDataManager(); diff --git a/src/data-managers/simulations-data-manager.js b/src/data-managers/simulations-data-manager.js new file mode 100644 index 0000000..30885aa --- /dev/null +++ b/src/data-managers/simulations-data-manager.js @@ -0,0 +1,24 @@ +/** + * File: simulation-data-manager.js + * Author: Markus Grigull + * Date: 04.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import RestDataManager from './rest-data-manager'; + +export default new RestDataManager('simulation', '/simulations', [ '_id', 'name', 'projects', 'models', 'startParameters' ]); diff --git a/src/data-managers/simulator-data-data-manager.js b/src/data-managers/simulator-data-data-manager.js new file mode 100644 index 0000000..3154115 --- /dev/null +++ b/src/data-managers/simulator-data-data-manager.js @@ -0,0 +1,168 @@ +/** + * File: simulator-data-data-manager.js + * Author: Markus Grigull + * Date: 03.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import WebsocketAPI from '../api/websocket-api'; +import AppDispatcher from '../app-dispatcher'; + +const OFFSET_TYPE = 2; +const OFFSET_VERSION = 4; + +class SimulatorDataDataManager { + constructor() { + this._sockets = {}; + } + + open(endpoint, identifier) { + // pass signals to onOpen callback + if (this._sockets[identifier] != null) + return; // already open? + + this._sockets[identifier] = new WebsocketAPI(endpoint, { onOpen: (event) => this.onOpen(event, identifier, true), onClose: (event) => this.onClose(event, identifier), onMessage: (event) => this.onMessage(event, identifier) }); + } + + update(endpoint, identifier) { + if (this._sockets[identifier] != null) { + if (this._sockets[identifier].endpoint !== endpoint) { + this._sockets[identifier].close(); + this._sockets[identifier] = new WebsocketAPI(endpoint, { onOpen: (event) => this.onOpen(event, identifier, false), onClose: (event) => this.onClose(event, identifier), onMessage: (event) => this.onMessage(event, identifier), onError: (error) => this.onError(error, identifier) }); + } + } + } + + closeAll() { + // close every open socket + for (var identifier in this._sockets) { + if (this._sockets.hasOwnProperty(identifier)) { + this._sockets[identifier].close(4000); + delete this._sockets[identifier]; + } + } + } + + send(message, identifier) { + const socket = this._sockets[identifier]; + if (socket == null) { + return false; + } + + const data = this.messageToBuffer(message); + socket.send(data); + + return true; + } + + onOpen(event, identifier, firstOpen) { + AppDispatcher.dispatch({ + type: 'simulatorData/opened', + id: identifier, + firstOpen: firstOpen + }); + } + + onClose(event, identifier) { + AppDispatcher.dispatch({ + type: 'simulatorData/closed', + id: identifier, + notification: (event.code !== 4000) + }); + + // remove from list, keep null reference for flag detection + delete this._sockets[identifier]; + } + + onMessage(event, identifier) { + var msgs = this.bufferToMessageArray(event.data); + + if (msgs.length > 0) { + AppDispatcher.dispatch({ + type: 'simulatorData/data-changed', + data: msgs, + id: identifier + }); + } + } + + bufferToMessage(data) { + // parse incoming message into usable data + if (data.byteLength === 0) { + return null; + } + + const id = data.getUint8(1); + const bits = data.getUint8(0); + const length = data.getUint16(0x02, 1); + const bytes = length * 4 + 16; + + return { + version: (bits >> OFFSET_VERSION) & 0xF, + type: (bits >> OFFSET_TYPE) & 0x3, + length: length, + sequence: data.getUint32(0x04, 1), + timestamp: data.getUint32(0x08, 1) * 1e3 + data.getUint32(0x0C, 1) * 1e-6, + values: new Float32Array(data.buffer, data.byteOffset + 0x10, length), + blob: new DataView(data.buffer, data.byteOffset + 0x00, bytes), + id: id + }; + } + + bufferToMessageArray(blob) { + /* some local variables for parsing */ + let offset = 0; + const msgs = []; + + /* for every msg in vector */ + while (offset < blob.byteLength) { + const msg = this.bufferToMessage(new DataView(blob, offset)); + + if (msg !== undefined) { + msgs.push(msg); + offset += msg.blob.byteLength; + } + } + + return msgs; + } + + messageToBuffer(message) { + const buffer = new ArrayBuffer(16 + 4 * message.length); + const view = new DataView(buffer); + + let bits = 0; + bits |= (message.version & 0xF) << OFFSET_VERSION; + bits |= (message.type & 0x3) << OFFSET_TYPE; + + const sec = Math.floor(message.timestamp / 1e3); + const nsec = (message.timestamp - sec * 1e3) * 1e6; + + view.setUint8(0x00, bits, true); + view.setUint16(0x02, message.length, true); + view.setUint32(0x04, message.sequence, true); + view.setUint32(0x08, sec, true); + view.setUint32(0x0C, nsec, true); + + const data = new Float32Array(buffer, 0x10, message.length); + data.set(message.values); + + return buffer; + } +} + +export default new SimulatorDataDataManager(); diff --git a/src/data-managers/simulators-data-manager.js b/src/data-managers/simulators-data-manager.js new file mode 100644 index 0000000..df45f34 --- /dev/null +++ b/src/data-managers/simulators-data-manager.js @@ -0,0 +1,47 @@ +/** + * File: simulator-data-manager.js + * Author: Markus Grigull + * Date: 03.03.2018 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import RestDataManager from './rest-data-manager'; +import RestAPI from '../api/rest-api'; +import AppDispatcher from '../app-dispatcher'; + +class SimulatorsDataManager extends RestDataManager { + constructor() { + super('simulator', '/simulators'); + } + + doActions(simulator, action, token = null) { + // TODO: Make only simulator id dependent + RestAPI.post(this.makeURL(this.url + '/' + simulator._id), action, token).then(response => { + AppDispatcher.dispatch({ + type: 'simulators/action-started', + data: response + }); + }).catch(error => { + AppDispatcher.dispatch({ + type: 'simulators/action-error', + error + }); + }); + } +} + +export default new SimulatorsDataManager(); diff --git a/src/data-managers/users-data-manager.js b/src/data-managers/users-data-manager.js new file mode 100644 index 0000000..f5db8f8 --- /dev/null +++ b/src/data-managers/users-data-manager.js @@ -0,0 +1,61 @@ +/** + * File: users-data-manager.js + * Author: Markus Grigull + * Date: 15.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import RestDataManager from './rest-data-manager'; +import RestAPI from '../api/rest-api'; +import AppDispatcher from '../app-dispatcher'; + +class UsersDataManager extends RestDataManager { + constructor() { + super('user', '/users'); + } + + login(username, password) { + RestAPI.post(this.makeURL('/authenticate'), { username: username, password: password }).then(response => { + AppDispatcher.dispatch({ + type: 'users/logged-in', + token: response.token + }); + }).catch(error => { + AppDispatcher.dispatch({ + type: 'users/login-error', + error: error + }); + }); + } + + getCurrentUser(token) { + RestAPI.get(this.makeURL('/users/me'), token).then(response => { + AppDispatcher.dispatch({ + type: 'users/current-user', + user: response.user + }); + }).catch(error => { + AppDispatcher.dispatch({ + type: 'users/current-user-error', + error: error + }); + }); + } + +} + +export default new UsersDataManager(); diff --git a/src/data-managers/visualizations-data-manager.js b/src/data-managers/visualizations-data-manager.js new file mode 100644 index 0000000..b141880 --- /dev/null +++ b/src/data-managers/visualizations-data-manager.js @@ -0,0 +1,24 @@ +/** + * File: visualizations-data-manager.js + * Author: Markus Grigull + * Date: 03.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import RestDataManager from './rest-data-manager'; + +export default new RestDataManager('visualization', '/visualizations'); diff --git a/src/img/eonerc_rwth.svg b/src/img/eonerc_rwth.svg new file mode 100644 index 0000000..42c4c3f --- /dev/null +++ b/src/img/eonerc_rwth.svg @@ -0,0 +1,152 @@ + + + +image/svg+xml \ No newline at end of file diff --git a/src/img/european_commission.svg b/src/img/european_commission.svg new file mode 100644 index 0000000..5bf4867 --- /dev/null +++ b/src/img/european_commission.svg @@ -0,0 +1,272 @@ + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/img/jara.svg b/src/img/jara.svg new file mode 100644 index 0000000..2f3f0d6 --- /dev/null +++ b/src/img/jara.svg @@ -0,0 +1,157 @@ + + + +image/svg+xml \ No newline at end of file diff --git a/src/img/reserve.svg b/src/img/reserve.svg new file mode 100644 index 0000000..23f3092 --- /dev/null +++ b/src/img/reserve.svg @@ -0,0 +1,81 @@ + + + +image/svg+xml \ No newline at end of file diff --git a/src/img/villas_web.svg b/src/img/villas_web.svg new file mode 100644 index 0000000..ccbc714 --- /dev/null +++ b/src/img/villas_web.svg @@ -0,0 +1,158 @@ + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + diff --git a/src/index.js b/src/index.js new file mode 100644 index 0000000..a853c12 --- /dev/null +++ b/src/index.js @@ -0,0 +1,33 @@ +/** + * File: index.js + * Author: Markus Grigull + * Date: 02.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import ReactDOM from 'react-dom'; + +import Router from './router'; + +import 'bootstrap/dist/css/bootstrap.css'; +import './styles/index.css'; + +ReactDOM.render( + , + document.getElementById('root') +); diff --git a/src/router.js b/src/router.js new file mode 100644 index 0000000..d9f3e45 --- /dev/null +++ b/src/router.js @@ -0,0 +1,43 @@ +/** + * File: router.js + * Author: Markus Grigull + * Date: 02.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import React from 'react'; +import { BrowserRouter, Route, Switch } from 'react-router-dom'; + +import App from './containers/app'; +import Login from './containers/login'; +import Logout from './containers/logout'; + +class Root extends React.Component { + render() { + return ( + + + + + + + + ); + } +} + +export default Root; diff --git a/src/stores/array-store.js b/src/stores/array-store.js new file mode 100644 index 0000000..ccd9689 --- /dev/null +++ b/src/stores/array-store.js @@ -0,0 +1,131 @@ +/** + * File: array-store.js + * Author: Markus Grigull + * Date: 03.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import { ReduceStore } from 'flux/utils'; + +import AppDispatcher from '../app-dispatcher'; + +class ArrayStore extends ReduceStore { + constructor(type, dataManager) { + super(AppDispatcher); + + this.type = type; + this.dataManager = dataManager; + } + + getInitialState() { + return []; + } + + updateElements(state, newElements) { + // search for existing element to update + state.forEach((element, index, array) => { + newElements = newElements.filter((updateElement, newIndex) => { + if (element._id === updateElement._id) { + // update each property + for (var key in updateElement) { + if (updateElement.hasOwnProperty(key)) { + array[index][key] = updateElement[key]; + } + } + + // remove updated element from update list + return false; + } + + return true; + }); + }); + + // all elements still in the list will just be added + state = state.concat(newElements); + + // announce change to listeners + this.__emitChange(); + + return state; + } + + reduce(state, action) { + switch (action.type) { + case this.type + '/start-load': + if (Array.isArray(action.data)) { + action.data.forEach((id) => { + this.dataManager.load(id, action.token); + }); + } else { + this.dataManager.load(action.data, action.token); + } + return state; + + case this.type + '/loaded': + if (Array.isArray(action.data)) { + return this.updateElements(state, action.data); + } else { + return this.updateElements(state, [action.data]); + } + + case this.type + '/load-error': + // TODO: Add error message + return state; + + case this.type + '/start-add': + this.dataManager.add(action.data, action.token); + return state; + + case this.type + '/added': + return this.updateElements(state, [action.data]); + + case this.type + '/add-error': + // TODO: Add error message + return state; + + case this.type + '/start-remove': + this.dataManager.remove(action.data, action.token); + return state; + + case this.type + '/removed': + return state.filter((item) => { + return (item !== action.original); + }); + + case this.type + '/remove-error': + // TODO: Add error message + return state; + + case this.type + '/start-edit': + this.dataManager.update(action.data, action.token); + return state; + + case this.type + '/edited': + return this.updateElements(state, [action.data]); + + case this.type + '/edit-error': + // TODO: Add error message + return state; + + default: + return state; + } + } +} + +export default ArrayStore; diff --git a/src/stores/file-store.js b/src/stores/file-store.js new file mode 100644 index 0000000..1437652 --- /dev/null +++ b/src/stores/file-store.js @@ -0,0 +1,50 @@ +/** + * File: file-store.js + * Author: Markus Grigull + * Date: 16.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import ArrayStore from './array-store'; +import FilesDataManager from '../data-managers/files-data-manager'; + +class FileStore extends ArrayStore { + constructor() { + super('files', FilesDataManager); + } + + reduce(state, action) { + switch (action.type) { + case 'files/start-upload': + FilesDataManager.upload(action.data, action.token, action.progressCallback, action.finishedCallback); + return state; + + case 'files/uploaded': + //console.log('ready uploaded'); + return state; + + case 'files/upload-error': + console.log(action.error); + return state; + + default: + return super.reduce(state, action); + } + } +} + +export default new FileStore(); diff --git a/src/stores/project-store.js b/src/stores/project-store.js new file mode 100644 index 0000000..0df9380 --- /dev/null +++ b/src/stores/project-store.js @@ -0,0 +1,25 @@ +/** + * File: project-store.js + * Author: Markus Grigull + * Date: 07.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import ArrayStore from './array-store'; +import ProjectsDataManager from '../data-managers/projects-data-manager'; + +export default new ArrayStore('projects', ProjectsDataManager); diff --git a/src/stores/simulation-model-store.js b/src/stores/simulation-model-store.js new file mode 100644 index 0000000..73d3dd2 --- /dev/null +++ b/src/stores/simulation-model-store.js @@ -0,0 +1,25 @@ +/** + * File: simulation-model-store.js + * Author: Markus Grigull + * Date: 20.04.2018 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import ArrayStore from './array-store'; +import SimulationModelsDataManager from '../data-managers/simulation-models-data-manager'; + +export default new ArrayStore('simulationModels', SimulationModelsDataManager); diff --git a/src/stores/simulation-store.js b/src/stores/simulation-store.js new file mode 100644 index 0000000..87f4676 --- /dev/null +++ b/src/stores/simulation-store.js @@ -0,0 +1,25 @@ +/** + * File: simulation-store.js + * Author: Markus Grigull + * Date: 04.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import ArrayStore from './array-store'; +import SimulationsDataManager from '../data-managers/simulations-data-manager'; + +export default new ArrayStore('simulations', SimulationsDataManager); diff --git a/src/stores/simulator-data-store.js b/src/stores/simulator-data-store.js new file mode 100644 index 0000000..1c4c8bf --- /dev/null +++ b/src/stores/simulator-data-store.js @@ -0,0 +1,128 @@ +/** + * File: simulator-data-store.js + * Author: Markus Grigull + * Date: 03.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import { ReduceStore } from 'flux/utils'; + +import AppDispatcher from '../app-dispatcher'; +import SimulatorDataDataManager from '../data-managers/simulator-data-data-manager'; + +const MAX_VALUES = 10000; + +class SimulationDataStore extends ReduceStore { + constructor() { + super(AppDispatcher); + } + + getInitialState() { + return {}; + } + + reduce(state, action) { + switch (action.type) { + case 'simulatorData/opened': + // create entry for simulator + if (state[action.id] === undefined) + state[action.id] = {}; + + return state; + + case 'simulatorData/prepare': + state[action.id] = { + output: { + sequence: -1, + length: action.outputLength, + values: [] + }, + input: { + sequence: -1, + length: action.inputLength, + version: 2, + type: 0, + timestamp: Date.now(), + values: new Array(action.inputLength).fill(0) + } + }; + + this.__emitChange(); + return state; + + case 'simulatorData/data-changed': + // get index for simulator id + if (state[action.id] == null) { + return state; + } + + if (state[action.id].output == null) { + state[action.id].output = { + values: [] + }; + } + + // loop over all samples in a vector + for (let j = 0; j < action.data.length; j++) { + let smp = action.data[j]; + + // add data to simulator + for (let i = 0; i < smp.length; i++) { + while (state[action.id].output.values.length < i + 1) { + state[action.id].output.values.push([]); + } + + state[action.id].output.values[i].push({ x: smp.timestamp, y: smp.values[i] }); + + // erase old values + if (state[action.id].output.values[i].length > MAX_VALUES) { + const pos = state[action.id].output.values[i].length - MAX_VALUES; + state[action.id].output.values[i].splice(0, pos); + } + } + + // update metadata + state[action.id].output.timestamp = smp.timestamp; + state[action.id].output.sequence = smp.sequence; + } + + // explicit call to prevent array copy + this.__emitChange(); + + return state; + + case 'simulatorData/inputChanged': + if (state[action.simulator] == null || state[action.simulator].input == null) { + return state; + } + + // update message properties + state[action.simulator].input.timestamp = Date.now(); + state[action.simulator].input.sequence++; + state[action.simulator].input.values[action.signal] = action.data; + + SimulatorDataDataManager.send(state[action.simulator].input, action.simulator); + + return state; + + default: + return state; + } + } +} + +export default new SimulationDataStore(); diff --git a/src/stores/simulator-store.js b/src/stores/simulator-store.js new file mode 100644 index 0000000..00b8635 --- /dev/null +++ b/src/stores/simulator-store.js @@ -0,0 +1,84 @@ +/** + * File: simulator-store.js + * Author: Markus Grigull + * Date: 03.03.2018 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import _ from 'lodash'; + +import ArrayStore from './array-store'; +import SimulatorsDataManager from '../data-managers/simulators-data-manager'; +import SimulatorDataDataManager from '../data-managers/simulator-data-data-manager'; + +class SimulatorStore extends ArrayStore { + constructor() { + super('simulators', SimulatorsDataManager); + } + + reduce(state, action) { + switch(action.type) { + case 'simulators/loaded': + // connect to each simulator + for (let simulator of action.data) { + const endpoint = _.get(simulator, 'properties.endpoint') || _.get(simulator, 'rawProperties.endpoint'); + + if (endpoint != null && endpoint !== '') { + SimulatorDataDataManager.open(endpoint, simulator._id); + } else { + // console.warn('Endpoint not found for simulator at ' + endpoint); + // console.log(simulator); + } + } + + return super.reduce(state, action); + + case 'simulators/edited': + // connect to each simulator + const simulator = action.data; + const endpoint = _.get(simulator, 'properties.endpoint') || _.get(simulator, 'rawProperties.endpoint'); + + if (endpoint != null && endpoint !== '') { + SimulatorDataDataManager.update(endpoint, simulator._id); + } + + return super.reduce(state, action); + + case 'simulators/fetched': + return this.updateElements(state, [action.data]); + + case 'simulators/fetch-error': + return state; + + case 'simulators/start-action': + if (!Array.isArray(action.data)) + action.data = [ action.data ] + + SimulatorsDataManager.doActions(action.simulator, action.data, action.token); + return state; + + case 'simulators/action-error': + console.log(action.error); + return state; + + default: + return super.reduce(state, action); + } + } +} + +export default new SimulatorStore(); diff --git a/src/stores/user-store.js b/src/stores/user-store.js new file mode 100644 index 0000000..e8722c8 --- /dev/null +++ b/src/stores/user-store.js @@ -0,0 +1,83 @@ +/** + * File: user-store.js + * Author: Markus Grigull + * Date: 15.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import { ReduceStore } from 'flux/utils'; + +import AppDispatcher from '../app-dispatcher'; +import UsersDataManager from '../data-managers/users-data-manager'; +import SimulatorDataDataManager from '../data-managers/simulator-data-data-manager'; + +class UserStore extends ReduceStore { + constructor() { + super(AppDispatcher); + } + + getInitialState() { + return { + users: [], + currentUser: null, + token: null, + loginMessage: null + }; + } + + reduce(state, action) { + switch (action.type) { + case 'users/login': + UsersDataManager.login(action.username, action.password); + return Object.assign({}, state, { loginMessage: null }); + + case 'users/logout': + // disconnect from all simulators + SimulatorDataDataManager.closeAll(); + + // delete user and token + return Object.assign({}, state, { token: null, currentUser: null }); + + case 'users/logged-in': + // request logged-in user data + UsersDataManager.getCurrentUser(action.token); + + return Object.assign({}, state, { token: action.token }); + + case 'users/current-user': + // save logged-in user + return Object.assign({}, state, { currentUser: action.user }); + + case 'users/current-user-error': + // discard user token + return Object.assign({}, state, { currentUser: null, token: null }); + + case 'users/login-error': + if (action.error && !action.error.handled) { + // If it was an error and hasn't been handled, the credentials must have been wrong. + state = Object.assign({}, state, { loginMessage: 'Wrong credentials! Please try again.' }); + } + + return state; + + default: + return state; + } + } +} + +export default new UserStore(); diff --git a/src/stores/users-store.js b/src/stores/users-store.js new file mode 100644 index 0000000..e42b1ed --- /dev/null +++ b/src/stores/users-store.js @@ -0,0 +1,67 @@ +/** + * File: users-store.js + * Author: Markus Grigull + * Date: 15.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import ArrayStore from './array-store'; +import UsersDataManager from '../data-managers/users-data-manager'; +import NotificationsDataManager from '../data-managers/notifications-data-manager'; + +class UsersStore extends ArrayStore { + constructor() { + super('users', UsersDataManager); + } + + reduce(state, action) { + switch (action.type) { + + case this.type + '/add-error': + if (action.error && !action.error.handled && action.error.response) { + // If it was an error and hasn't been handled, user could not be added + const USER_ADD_ERROR_NOTIFICATION = { + title: 'Failed to add new user', + message: action.error.response.body.message, + level: 'error' + } + NotificationsDataManager.addNotification(USER_ADD_ERROR_NOTIFICATION); + + } + return super.reduce(state, action); + + case this.type + '/edit-error': + if (action.error && !action.error.handled && action.error.response) { + // If it was an error and hasn't been handled, user couldn't not be updated + const USER_EDIT_ERROR_NOTIFICATION = { + title: 'Failed to edit user', + message: action.error.response.body.message, + level: 'error' + } + NotificationsDataManager.addNotification(USER_EDIT_ERROR_NOTIFICATION); + + } + return super.reduce(state, action); + + default: + return super.reduce(state, action); + } + } + +} + +export default new UsersStore(); diff --git a/src/stores/visualization-store.js b/src/stores/visualization-store.js new file mode 100644 index 0000000..ba69682 --- /dev/null +++ b/src/stores/visualization-store.js @@ -0,0 +1,25 @@ +/** + * File: visualization-store.js + * Author: Markus Grigull + * Date: 02.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +import ArrayStore from './array-store'; +import VisualizationsDataManager from '../data-managers/visualizations-data-manager'; + +export default new ArrayStore('visualizations', VisualizationsDataManager); diff --git a/src/styles/app.css b/src/styles/app.css new file mode 100644 index 0000000..552f7ed --- /dev/null +++ b/src/styles/app.css @@ -0,0 +1,388 @@ +/** + * File: app.css + * Author: Markus Grigull + * Date: 02.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +/** + * Application container + */ +body { + background-color: #6EA2B0 !important; +} + +.app { + height: 100vh; + color: #4d4d4d; + + font: 16px 'Helvetica Neue', Helvetica, Arial, sans-serif; + hyphens: auto; +} + +.app-body { + /*height: 100%;*/ +} + +.app-header { + width: 100%; + height: 60px; + padding: 10px 0 0 0; + + color: #527984; + background-color: #fff; +} + +.app-header h1 { + width: 100%; + margin: 0; + + text-align: left; +} + +@media (min-width: 768px) { + .app-header h1 { + text-align: center !important; + } +} + +.app-header .menu-icon { + color: #818181; + right: 5px; + + padding: 6px 0 0 0; +} + +.btn-link { + padding: 0 !important; +} + +.app-footer { + width: 100%; + + margin-top: 20px; + padding-bottom: 10px; + + text-align: center; +} + +.app-footer a { + color: #4d4d4d; + + text-decoration: underline; +} + +.app-body-spacing { + padding: 15px 5px 0px 5px; +} + +.app-body-spacing > div { + margin-left: 7px; + margin-right: 7px; +} + +.app-content-fullscreen { + height: 100%; +} + +.app-content { + padding: 15px 20px; + + width: auto; + min-height: 300px; + + background-color: #fff; + box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2), + 0 9px 18px 0 rgba(0, 0, 0, 0.1); +} + +@media (min-width: 768px) { + .app-content-margin-left { + margin-left: 200px !important; + } +} + +/** + * Menus + */ +.menu-sidebar { + /*display: inline-table;*/ + padding: 20px 25px 20px 25px; + width: 180px; + float: left; + + background-color: #fff; + box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2), + 0 9px 18px 0 rgba(0, 0, 0, 0.1); +} + +.menu-sidebar a { + color: #4d4d4d; + text-decoration:none; +} + +.menu-sidebar a:hover, .menu-sidebar a:focus { + text-decoration:none; +} + +.active { + font-weight: bold; +} + +.menu-sidebar ul { + padding-top: 10px; + list-style: none; + white-space: nowrap; +} + +.menu-sidebar a::after { + /* Trick to make menu items to be as wide as in bold */ + display: block; + content: attr(title); + font-weight: bold; + height: 1px; + color: transparent; + overflow: hidden; + visibility: hidden; + margin-bottom: -1px; +} + +.sidenav { + height: 100%; + position: fixed; + top: 0; + right: 0; + z-index: 100; + background-color: #111; + overflow-x: hidden; + padding-top: 60px; + transition: 0.5s; +} + +.sidenav a { + padding: 8px 8px 8px 32px; + text-decoration: none; + font-size: 25px; + color: #818181; + display: block; + transition: 0.3s; +} + +.sidenav a:hover { + color: #f1f1f1; + text-decoration: none; +} + +.sidenav .closeButton { + position: absolute; + top: -15px; + right: 15px; + font-size: 56px; + margin-left: 50px; + text-decoration: none; + display: block; + color: #818181; + transition: 0.3s; +} + +.sidenav .closeButton:hover { + text-decoration: none; + color: #f1f1f1; +} + +/** + * Home page + */ +.home-container > ul { + margin-left: 2em; +} + +.home-container > img { + margin: 20px; +} + +/** + * Visualizations + */ +.fullscreen-container { + padding: 10px; + background-color: white; +} + + +/** + * Login form + */ +.login-container { + max-width: 500px; + + margin: 30px auto; + padding: 15px 20px; + + background-color: #fff; + box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2), + 0 9px 18px 0 rgba(0, 0, 0, 0.1); +} + +/** + * Tables + */ +.table th { + background-color: #527984; + color: #fff; +} + +/** + * Buttons + */ +.table-control-button { + border: none; + + background: none; + + padding: 0 5px; +} + +.table-control-button:hover { + color: #888; +} + +.table-control-checkbox input { + position: relative !important; + margin-top: 0 !important; +} + +.unselectable { + -webkit-touch-callout: none !important; /* iOS Safari */ + -webkit-user-select: none !important; /* Safari */ + -khtml-user-select: none !important; /* Konqueror HTML */ + -moz-user-select: none !important; /* Firefox */ + -ms-user-select: none !important; /* Internet Explorer/Edge */ + user-select: none !important; /* Non-prefixed version, currently + supported by Chrome and Opera */ +} + +/** + * Toolbox + */ +.toolbox-dropzone { + width: 100%; + min-height: 400px; + + display: flex; + position: relative; +} + +.toolbox-dropzone-editing { + border: 3px dashed #e1e1e1; +} + +.toolbox-dropzone-active { + border-color: #aaa; +} + +.toolbox { + margin-top: 10px; + margin-bottom: 10px; +} + +.toolbox-item { + display: inline-block; + + margin-right: 5px; + cursor: move; +} + +.toolbox-item-dragging { + opacity: 0.4; +} + +.toolbox-item-disabled { + border-color: lightgray; + + color: lightgray; + + cursor: default !important; +} + +/** + * Sections + */ + +.box { + display: -webkit-flex; + display: flex; + flex-direction: column; +} + +.box-header { + -webkit-flex: 0 0 auto; + flex: 0 0 auto; +} + +.box-content { + -webkit-flex: 1 0 auto; + flex: 1 0 auto; +} + +.section { + min-height: 100%; + width: 100%; +} + +.section-header div { + display: inline-block; + vertical-align: middle; + /* height: 100%; */ +} + +.section-title { + font-size: 1.5em; +} + +.section-header .section-buttons-group { + margin-right: 10px; + margin-left: 10px; +} + +.section-header button { + padding-left: 3px; + padding-right: 3px; +} + +.section-header .btn-link:hover, .section-header .btn-link:focus { + text-decoration: none; +} + +.section-buttons-group-right { + height: auto !important; + + float: right; +} + +.section-buttons-group-right .rc-slider { + margin-left: 12px; +} + +.form-horizontal .form-group { + margin-left: 0 !important; + margin-right: 0 !important; +} + +.label-outdated { + opacity: 0.4; +} diff --git a/src/styles/context-menu.css b/src/styles/context-menu.css new file mode 100644 index 0000000..1dff534 --- /dev/null +++ b/src/styles/context-menu.css @@ -0,0 +1,85 @@ +/* Copied from react-contextmenu/examples */ + +.react-contextmenu { + min-width: 160px; + padding: 5px 0; + margin: 2px 0 0; + font-size: 16px; + color: #373a3c; + text-align: left; + background-color: #fff; + background-clip: padding-box; + border: 1px solid rgba(0,0,0,.15); + border-radius: .25rem; + outline: none; + opacity: 0; + pointer-events: none; + transition: opacity 250ms ease !important; +} + +.react-contextmenu.react-contextmenu--visible { + opacity: 1; + pointer-events: auto; +} + +.react-contextmenu-item { + padding: 3px 20px; + font-weight: 400; + line-height: 1.5; + color: #373a3c; + text-align: inherit; + white-space: nowrap; + background: 0 0; + border: 0; +cursor: pointer; +} + +.react-contextmenu-item.react-contextmenu-item--active, +.react-contextmenu-item.react-contextmenu-item--selected { + color: #fff; + background-color: #20a0ff; + border-color: #20a0ff; + text-decoration: none; +} + +.react-contextmenu-item.react-contextmenu-item--disabled, +.react-contextmenu-item.react-contextmenu-item--disabled:hover { + color: #878a8c; + background-color: transparent; + border-color: rgba(0,0,0,.15); +} + +.react-contextmenu-item--divider { + margin-bottom: 3px; + padding: 2px 0; + border-bottom: 1px solid rgba(0,0,0,.15); + cursor: inherit; +} +.react-contextmenu-item--divider:hover { + background-color: transparent; + border-color: rgba(0,0,0,.15); +} + +.react-contextmenu-item.react-contextmenu-submenu { +padding: 0; +} + +.react-contextmenu-item.react-contextmenu-submenu > .react-contextmenu-item { +} + +.react-contextmenu-item.react-contextmenu-submenu > .react-contextmenu-item:after { + content: "\25B6"; + display: inline-block; + position: absolute; + right: 7px; +} + +.react-contextmenu-wrapper { + width: 100%; + height: 100%; + position: absolute; + top: 0px; + left: 0px; + overflow: auto; +} + diff --git a/src/styles/index.css b/src/styles/index.css new file mode 100644 index 0000000..dde0352 --- /dev/null +++ b/src/styles/index.css @@ -0,0 +1,25 @@ +/** + * File: index.css + * Author: Markus Grigull + * Date: 17.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +* { + margin: 0; + padding: 0; +} diff --git a/src/styles/simple-spinner.css b/src/styles/simple-spinner.css new file mode 100644 index 0000000..c86368a --- /dev/null +++ b/src/styles/simple-spinner.css @@ -0,0 +1,19 @@ + +/* + Basic spinner animation + taken from: https://www.w3schools.com/howto/howto_css_loader.asp +*/ + +.loader { + border: 16px solid #f3f3f3; + border-top: 16px solid #6ea2b0; + border-radius: 50%; + width: 120px; + height: 120px; + animation: spin 1s linear infinite; +} + +@keyframes spin { + 0% { transform: rotate(0deg); } + 100% { transform: rotate(360deg); } +} diff --git a/src/styles/widgets.css b/src/styles/widgets.css new file mode 100644 index 0000000..2e79f89 --- /dev/null +++ b/src/styles/widgets.css @@ -0,0 +1,433 @@ +/** + * File: widgets.css + * Author: Markus Grigull + * Date: 02.03.2017 + * + * This file is part of VILLASweb. + * + * VILLASweb is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * VILLASweb is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with VILLASweb. If not, see . + ******************************************************************************/ + +.widget { + +} + +.border { + border: 1px solid lightgray; +} + +.editing-widget { + +} + +.editing-widget:hover { + background-color: #fff; +} + +.locked { + cursor: not-allowed !important; +} + +/* Firefox-specific rules */ +@-moz-document url-prefix() { + .editing-widget:not(.border):hover { + outline-offset: -10px; + } +} + +.editing-widget:not(.border):hover { + outline: 1px solid lightgray; +} + +/* Reset Bootstrap styles to "disable" while editing */ +div[class*="-widget"] .btn[disabled], .btn.disabled, div[class*="-widget"] input[disabled], .form-control[disabled], .checkbox.disabled label { + cursor: inherit; + pointer-events: none; +} + +.editing-widget .btn-default.active { + background-color: #abcfd8; + border-color: #ccc; +} + +.btn-default[disabled]:hover { + background-color: #fff; + border-color: #ccc; +} + +.btn-default.active[disabled]:hover { + background-color: #e6e6e6; + border-color: #adadad; +} + /* End reset */ + + /* Match Bootstrap's them to VILLAS */ +.widget .btn-default.active { + background-color: #abcfd8; +} + +.widget .btn-default.active:hover, .widget .btn-default.active:hover { + background-color: #89b3bd; +} + +.widget .btn-default:hover { + background-color: #abcfd8; +} +/* End match */ + +/* Begin edit menu: Colors */ +.color-control input[type="radio"] { + display: none; +} + +.color-control .radio-inline.checked { + border-color: #000 !important; +} + +.color-control .radio-inline { + height: 24px; + flex: 1 1 auto; + border: 2px solid; + /* Reset bootstrap padding */ + padding-left: 0px; +} + +.color-control .radio-inline + .radio-inline { + /* Reset bootstrap margin */ + margin-left: 0px; +} + +.color-control .radio-inline:hover { + border-color: #444 !important; +} + +.color-control div[class*="colors-column-"] { + display: flex; + padding: 2px 20px; +} + +/* End edit menu: Colors */ + +/* PlotTable widget */ +.plot-table-widget, .plot-widget, .value-widget, .image-widget, .label-widget { + width: 100%; + height: 100%; + padding: 3px 6px; +} + +.plot-table-widget { + display: -webkit-flex; + display: flex; + flex-direction: column; +} + +.plot-table-widget .content { + -webkit-flex: 1 0 auto; + flex: 1 0 auto; + display: -webkit-flex; + display: flex; + flex-direction: column; +} + +.table-plot-row { + -webkit-flex: 1 0 auto; + flex: 1 0 auto; + display: -webkit-flex; + display: flex; +} + +.plot-table-widget .widget-table { + -webkit-flex: 1 0 auto; + flex: 1 0 auto; + flex-basis: 90px; + max-width: 50%; + display: flex; + flex-direction: column; + justify-content: center; + margin-right: 10px; +} + +.plot-table-widget small { + text-align: center; +} + +.plot-table-widget .checkbox label { + height: 100%; + width: 100%; + padding: 6px 12px; + overflow-x: hidden; +} + +.plot-table-widget .btn { + padding: 0px; +} + +.plot-table-widget input[type="checkbox"] { + display: none; +} +/* End PlotTable Widget */ + +/* Plot Widget */ +.plot-widget { + display: -webkit-flex; + display: flex; + flex-direction: column; +} +/* End Plot Widget */ + +/* Plots */ +/* The plot container, in order to avoid 100% height/width */ +.widget-plot { + display: flex; + -webkit-flex: 1 1 auto; + flex: 1 1 auto; + margin-bottom: 5px; +} + +.plot-legend { + display: -webkit-flex; + display: flex; + flex-basis: 20px; /* Enough to allocate one row */ + max-height: 40px; /* Allocate up to two rows */ + flex-shrink: 0; + flex-wrap: wrap; + justify-content: space-around; +} + +.signal-legend { + float: left; + list-style-type: none; + font-size: 1.2em; + padding-left: 10px; + padding-right: 5px; + vertical-align: middle; +} + +li.signal-legend::before { + content: '■'; +} + +.signal-legend span { + font-size: 0.8em; +} + +.signal-legend-name { + margin-left: 5px; + font-weight: 700; + color: black; +} + +span.signal-unit { + color: grey; + font-style: italic; + font-weight: 50%; +} + +span.signal-unit::before { + content: '['; + font-style: normal; +} + +span.signal-unit::after { + content: ']'; + font-style: normal; +} + +/* End Plots */ + +.single-value-widget { + padding: 0; + margin: 0; + + width: 100%; + height: 100%; + display: flex; + + word-wrap: break-word; +} + +.single-value-widget > * { + width: 50%; + float: left; + margin: 5px; + font-size: 1vw; +} + +/* Button widget styling */ + +/* End button widget styling */ + +.full { + width: 100%; + height: 100%; +} + +/* Number input widget */ +div[class*="-widget"] label { + cursor: inherit; +} + +.number-input-widget { + display: flex; + flex-direction: column; + justify-content: center; +} + +.number-input-widget .form-horizontal .form-group { + margin: 0px; +} +/* End number input widget */ + +/* Begin Slider widget */ +.slider-widget { + display: flex; + align-items: center; + justify-content: space-around; +} + +.slider-widget label { + flex: 0 0 auto; + text-align: center; +} + +.slider-widget span { + text-align: center; + font-size: 1.5em; + font-weight: 600; +} + +.slider-widget.horizontal .slider { + flex: 1 1 auto; +} + +.slider-widget.horizontal span { + flex: 0 0 50pt; +} + +.slider-widget.horizontal label { + padding-right: 10px; +} + +.slider-widget.vertical { + flex-direction: column; +} + +.slider-widget.vertical span { + padding-top: 10px; +} + +.slider-widget.vertical label { + padding-bottom: 10px; +} + +/* Begin Slider customization */ +.rc-slider-track { + background-color: #6EA2B0; +} + +.rc-slider-handle, .rc-slider-handle:hover { + border-color: #6EA2B0; +} + +.rc-slider-disabled { + background-color: inherit; +} + +.rc-slider-disabled .rc-slider-handle { + cursor: inherit; +} + +.rc-slider-disabled .rc-slider-handle:hover { + border-color:#ccc; +} +/* End Slider customization */ + +/* End slider widget */ + +/* Gauge widget */ +.gauge-widget { + width: 100%; + height: 100%; +} + +.gauge-widget canvas { + width: 100%; + height: 87%; +} + +.gauge-name { + height: 10%; + width: 100%; + text-align: center; + font-weight: bold; +} + +.gauge-unit { + position: absolute; + width: 100%; + font-size: 1.0em; + bottom: 25%; + text-align: center; +} + +.gauge-value { + position: absolute; + width: 100%; + font-weight: bold; + font-size: 18px; + bottom: 10%; + text-align: center; +} +/* End gauge widget */ + +/* Begin label widget */ +.label-widget { + padding: 0; +} + +.label-widget h4 { + padding: 0; + margin: 0; + + word-wrap: break-word; +} +/* End label widget */ + +/* Begin table widget */ +.table-widget table { + background-color: #fff; +} + +.table-widget td, .table-widget th { + text-align: left; +} + +.table-widget td { + padding: 2px 8px !important; +} + +/* End table widget*/ + +/* Begin box widget */ +.box-widget .border { + width: 100%; + height: 100%; + border: 2px solid; +} +/* End box widget */ + +.plot-table-widget .widget-plot { + -webkit-flex: 1 0 auto; + flex: 1 0 auto; +}