Marek Czernek
2020-03-06 a0dac2546dca4548028ebc084eb6747ce08e68f9
Provide Frontend skeleton
26 files added
12431 ■■■■■ changed files
mczernek-exchange-application/frontend/.gitignore 23 ●●●●● patch | view | raw | blame | history
mczernek-exchange-application/frontend/README.md 89 ●●●●● patch | view | raw | blame | history
mczernek-exchange-application/frontend/package.json 37 ●●●●● patch | view | raw | blame | history
mczernek-exchange-application/frontend/public/favicon.ico patch | view | raw | blame | history
mczernek-exchange-application/frontend/public/index.html 43 ●●●●● patch | view | raw | blame | history
mczernek-exchange-application/frontend/public/logo.svg 17 ●●●●● patch | view | raw | blame | history
mczernek-exchange-application/frontend/public/logo192.png patch | view | raw | blame | history
mczernek-exchange-application/frontend/public/logo512.png patch | view | raw | blame | history
mczernek-exchange-application/frontend/public/manifest.json 25 ●●●●● patch | view | raw | blame | history
mczernek-exchange-application/frontend/public/robots.txt 3 ●●●●● patch | view | raw | blame | history
mczernek-exchange-application/frontend/src/App.css 21 ●●●●● patch | view | raw | blame | history
mczernek-exchange-application/frontend/src/App.js 46 ●●●●● patch | view | raw | blame | history
mczernek-exchange-application/frontend/src/Graph.js 111 ●●●●● patch | view | raw | blame | history
mczernek-exchange-application/frontend/src/HistoricalDataForm.js 155 ●●●●● patch | view | raw | blame | history
mczernek-exchange-application/frontend/src/Loading.js 27 ●●●●● patch | view | raw | blame | history
mczernek-exchange-application/frontend/src/MainStructure.js 49 ●●●●● patch | view | raw | blame | history
mczernek-exchange-application/frontend/src/NavList.js 48 ●●●●● patch | view | raw | blame | history
mczernek-exchange-application/frontend/src/SingleCurrencyExchange.js 186 ●●●●● patch | view | raw | blame | history
mczernek-exchange-application/frontend/src/Status.js 66 ●●●●● patch | view | raw | blame | history
mczernek-exchange-application/frontend/src/Welcome.js 33 ●●●●● patch | view | raw | blame | history
mczernek-exchange-application/frontend/src/index.js 13 ●●●●● patch | view | raw | blame | history
mczernek-exchange-application/frontend/src/serviceWorker.js 141 ●●●●● patch | view | raw | blame | history
mczernek-exchange-application/frontend/src/setupTests.js 5 ●●●●● patch | view | raw | blame | history
mczernek-exchange-application/frontend/src/training_black.png patch | view | raw | blame | history
mczernek-exchange-application/frontend/src/training_white.png patch | view | raw | blame | history
mczernek-exchange-application/frontend/yarn.lock 11293 ●●●●● patch | view | raw | blame | history
mczernek-exchange-application/frontend/.gitignore
New file
@@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
mczernek-exchange-application/frontend/README.md
New file
@@ -0,0 +1,89 @@
# Frontend Microservice
This is the frontend microservice that displays data from our exchange application.
The entry point is at `src/index.js` -> `src/app.js`.
The frontend currently works with the `history` shim microservice.
For testing, start run `history` accessible on `localhost:8080` and then start `frontend` (on any port).
## TODO
* Remove hardcoded localhost calls
* Containerize this application
## TODO Stretch Goals
* Finish Status dashboard
* Refactor into nicer directory structure
# Documentation
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `yarn 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.
### `yarn test`
Launches the test runner in the interactive watch mode.<br />
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `yarn 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](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `yarn 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.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting
### Analyzing the Bundle Size
This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size
### Making a Progressive Web App
This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app
### Advanced Configuration
This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration
### Deployment
This section has moved here: https://facebook.github.io/create-react-app/docs/deployment
### `yarn build` fails to minify
This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify
mczernek-exchange-application/frontend/package.json
New file
@@ -0,0 +1,37 @@
{
  "name": "frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@patternfly/react-charts": "^5.3.5",
    "@patternfly/react-core": "^3.140.11",
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.3.2",
    "@testing-library/user-event": "^7.1.2",
    "react": "^16.13.0",
    "react-dom": "^16.13.0",
    "react-router-dom": "^5.1.2",
    "react-scripts": "3.4.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}
mczernek-exchange-application/frontend/public/favicon.ico
mczernek-exchange-application/frontend/public/index.html
New file
@@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="DO328 application"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <!--
      manifest.json provides metadata used when your web app is installed on a
      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <!--
      Notice the use of %PUBLIC_URL% in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.
      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>Exchange Application</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.
      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.
      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  </body>
</html>
mczernek-exchange-application/frontend/public/logo.svg
New file
@@ -0,0 +1,17 @@
<svg class="rh-logo"
    xmlns="http://www.w3.org/2000/svg" viewBox="0 0 613 145">
    <defs>
        <style>
                                .rh-logo-hat {
                                  fill: #e00;
                                }
                                .rh-logo-type {
                                  fill: #fff;
                                }
        </style>
    </defs>
    <title>Red Hat</title>
    <path class="rh-logo-hat" d="M127.47,83.49c12.51,0,30.61-2.58,30.61-17.46a14,14,0,0,0-.31-3.42l-7.45-32.36c-1.72-7.12-3.23-10.35-15.73-16.6C124.89,8.69,103.76.5,97.51.5,91.69.5,90,8,83.06,8c-6.68,0-11.64-5.6-17.89-5.6-6,0-9.91,4.09-12.93,12.5,0,0-8.41,23.72-9.49,27.16A6.43,6.43,0,0,0,42.53,44c0,9.22,36.3,39.45,84.94,39.45M160,72.07c1.73,8.19,1.73,9.05,1.73,10.13,0,14-15.74,21.77-36.43,21.77C78.54,104,37.58,76.6,37.58,58.49a18.45,18.45,0,0,1,1.51-7.33C22.27,52,.5,55,.5,74.22c0,31.48,74.59,70.28,133.65,70.28,45.28,0,56.7-20.48,56.7-36.65,0-12.72-11-27.16-30.83-35.78"></path>
    <path class="rh-logo-band" d="M160,72.07c1.73,8.19,1.73,9.05,1.73,10.13,0,14-15.74,21.77-36.43,21.77C78.54,104,37.58,76.6,37.58,58.49a18.45,18.45,0,0,1,1.51-7.33l3.66-9.06A6.43,6.43,0,0,0,42.53,44c0,9.22,36.3,39.45,84.94,39.45,12.51,0,30.61-2.58,30.61-17.46a14,14,0,0,0-.31-3.42Z"></path>
    <path class="rh-logo-type" d="M579.74,92.8c0,11.89,7.15,17.67,20.19,17.67a52.11,52.11,0,0,0,11.89-1.68V95a24.84,24.84,0,0,1-7.68,1.16c-5.37,0-7.36-1.68-7.36-6.73V68.3h15.56V54.1H596.78v-18l-17,3.68V54.1H568.49V68.3h11.25Zm-53,.32c0-3.68,3.69-5.47,9.26-5.47a43.12,43.12,0,0,1,10.1,1.26v7.15a21.51,21.51,0,0,1-10.63,2.63c-5.46,0-8.73-2.1-8.73-5.57m5.2,17.56c6,0,10.84-1.26,15.36-4.31v3.37h16.82V74.08c0-13.56-9.14-21-24.39-21-8.52,0-16.94,2-26,6.1l6.1,12.52c6.52-2.74,12-4.42,16.83-4.42,7,0,10.62,2.73,10.62,8.31v2.73a49.53,49.53,0,0,0-12.62-1.58c-14.31,0-22.93,6-22.93,16.73,0,9.78,7.78,17.24,20.19,17.24m-92.44-.94h18.09V80.92h30.29v28.82H506V36.12H487.93V64.41H457.64V36.12H439.55ZM370.62,81.87c0-8,6.31-14.1,14.62-14.1A17.22,17.22,0,0,1,397,72.09V91.54A16.36,16.36,0,0,1,385.24,96c-8.2,0-14.62-6.1-14.62-14.09m26.61,27.87h16.83V32.44l-17,3.68V57.05a28.3,28.3,0,0,0-14.2-3.68c-16.19,0-28.92,12.51-28.92,28.5a28.25,28.25,0,0,0,28.4,28.6,25.12,25.12,0,0,0,14.93-4.83ZM320,67c5.36,0,9.88,3.47,11.67,8.83H308.47C310.15,70.3,314.36,67,320,67M291.33,82c0,16.2,13.25,28.82,30.28,28.82,9.36,0,16.2-2.53,23.25-8.42l-11.26-10c-2.63,2.74-6.52,4.21-11.14,4.21a14.39,14.39,0,0,1-13.68-8.83h39.65V83.55c0-17.67-11.88-30.39-28.08-30.39a28.57,28.57,0,0,0-29,28.81M262,51.58c6,0,9.36,3.78,9.36,8.31S268,68.2,262,68.2H244.11V51.58Zm-36,58.16h18.09V82.92h13.77l13.89,26.82H292l-16.2-29.45a22.27,22.27,0,0,0,13.88-20.72c0-13.25-10.41-23.45-26-23.45H226Z"></path>
</svg>
mczernek-exchange-application/frontend/public/logo192.png
mczernek-exchange-application/frontend/public/logo512.png
mczernek-exchange-application/frontend/public/manifest.json
New file
@@ -0,0 +1,25 @@
{
  "short_name": "React App",
  "name": "Create React App Sample",
  "icons": [
    {
      "src": "favicon.ico",
      "sizes": "64x64 32x32 24x24 16x16",
      "type": "image/x-icon"
    },
    {
      "src": "logo192.png",
      "type": "image/png",
      "sizes": "192x192"
    },
    {
      "src": "logo512.png",
      "type": "image/png",
      "sizes": "512x512"
    }
  ],
  "start_url": ".",
  "display": "standalone",
  "theme_color": "#000000",
  "background_color": "#ffffff"
}
mczernek-exchange-application/frontend/public/robots.txt
New file
@@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:
mczernek-exchange-application/frontend/src/App.css
New file
@@ -0,0 +1,21 @@
.centered {
    text-align: center;
}
.margin-separator {
    margin-top: 20px;
}
.text-container {
    text-align: center;
    font-size: 3em;
    max-width: 300px;
    border-bottom-style: solid;
    border-color: #2b9af3;
    word-wrap: break-word;
}
.currency-text {
    font-size: 0.6em;
    vertical-align: top;
}
mczernek-exchange-application/frontend/src/App.js
New file
@@ -0,0 +1,46 @@
import React, { Component } from 'react';
import Structure from './MainStructure'
import HistoricalDataForm from './HistoricalDataForm'
import WelcomePage from './Welcome'
import SingleCurrencyExchange from './SingleCurrencyExchange'
import Status from './Status'
import {
  BrowserRouter as Router,
  Switch,
  Route,
} from "react-router-dom";
class App extends Component {
  render() {
    return (
      <Router>
        <Switch>
          <Route path="/" exact >
            <Structure>
              <WelcomePage />
            </Structure>
          </Route>
          <Route path="/exchange" exact>
            <Structure>
              <SingleCurrencyExchange />
            </Structure>
          </Route>
          <Route path="/history" exact>
            <Structure>
              <HistoricalDataForm />
            </Structure>
          </Route>
          {/* <Route path="/status" exact>
            <Structure>
              <Status />
            </Structure>
          </Route> */}
        </Switch>
      </Router>
    )
  }
}
export default App;
mczernek-exchange-application/frontend/src/Graph.js
New file
@@ -0,0 +1,111 @@
import React from 'react';
import { Chart, ChartAxis, ChartGroup, ChartLine, ChartScatter, ChartThemeColor, ChartVoronoiContainer } from '@patternfly/react-charts';
export default class ScatterLineChart extends React.Component {
    constructor(props) {
        super(props);
        this.containerRef = React.createRef();
        this.state = {
            width: 0,
            series: "",
        };
        this.handleResize = () => {
            if (this.containerRef.current && this.containerRef.current.clientWidth) {
                this.setState({ width: this.containerRef.current.clientWidth });
            }
        };
    }
    componentDidMount() {
        this.handleResize();
        window.addEventListener('resize', this.handleResize);
    }
    componentWillUnmount() {
        window.removeEventListener('resize', this.handleResize);
    }
    render() {
        const { width } = this.state;
        var conv = []
        var maxYAxis = 0
        this.props.data.forEach(e => {
            if(e.value > maxYAxis) {
                maxYAxis = e.value
            }
            const date = new Date(e.date)
            const dateString = `${date.getDate()}/${date.getMonth() + 1}`
            conv.unshift({
                name: this.props.target,
                x: dateString,
                y: e.value
            })
        });
        const series = [
            {
                datapoints: conv,
                legendItem: { name: 'Conversion' }
            }
        ];
        return (
            <div ref={this.containerRef}>
                <div style={{ height: '275px' }}>
                    <Chart
                        ariaDesc="Average number of pets"
                        ariaTitle="Line chart example"
                        containerComponent={
                            <ChartVoronoiContainer
                                labels={({ datum }) => datum.childName.includes('line-') ? `${datum.name}: ${datum.y}` : null}
                                constrainToVisibleArea
                            />
                        }
                        legendData={series.map(s => s.legendItem)}
                        legendPosition="bottom-left"
                        height={275}
                        maxDomain={{ y: maxYAxis + 1 }}
                        minDomain={{ y: 0 }}
                        padding={{
                            bottom: 75, // Adjusted to accommodate legend
                            left: 50,
                            right: 50,
                            top: 50
                        }}
                        themeColor={ChartThemeColor.orange}
                        width={width}
                    >
                        <ChartAxis tickValues={[2, 3, 4]} />
                        <ChartAxis dependentAxis showGrid tickValues={[2, 5, 8]} />
                        <ChartGroup>
                            {series.map((s, idx) => {
                                return (
                                    <ChartScatter
                                        data={s.datapoints}
                                        key={'scatter-' + idx}
                                        name={'scatter-' + idx}
                                    />
                                );
                            })}
                        </ChartGroup>
                        <ChartGroup>
                            {series.map((s, idx) => {
                                return (
                                    <ChartLine
                                        key={'line-' + idx}
                                        name={'line-' + idx}
                                        data={s.datapoints}
                                    />
                                );
                            })}
                        </ChartGroup>
                    </Chart>
                </div>
            </div>
        );
    }
}
mczernek-exchange-application/frontend/src/HistoricalDataForm.js
New file
@@ -0,0 +1,155 @@
import React, { Component } from 'react';
import {
    Form,
    FormGroup,
    FormSelect,
    FormSelectOption,
    Button,
    TextContent,
    Text,
    Flex,
    FlexItem,
} from '@patternfly/react-core';
import Spinner from './Loading';
import RenderedChart from './Graph'
class CurrencyPicker extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            currencies: [],
            src: 'Loading currencies',
            target: 'Loading currencies',
            exchangeData: '',
            requestExchangeData: false,
            inputValue: 1,
            inputValid: true,
        };
    }
    componentDidMount() {
        this.setState({
            loading: true
        })
        fetch('http://localhost:8080')
            .then(currencies => currencies.json())
            .then(currencies => this.setState({
                currencies, src: currencies[0], target: currencies[1], loading: false
            }))
            .catch(err => console.log(err));
    }
    onChangeSrc = (src) => {
        this.setState({ src });
    };
    onChangeTarget = (target) => {
        this.setState({ target });
    };
    onChangeInput = (inputValue) => {
        const inputValid = this.inputValidation(inputValue);
        this.setState({ inputValue, inputValid });
    }
    inputValidation = (input) => {
        return input > 0
    }
    submit = (e) => {
        e.preventDefault();
        this.setState({ requestExchangeData: true })
        const payload = {
            source: this.state.src,
            target: this.state.target
        }
        fetch('http://localhost:8080', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(payload)
        })
            .then(exchangeData => exchangeData.json())
            .then(exchangeData => this.setState({ exchangeData }))
            .catch(err => console.log(err))
    };
    render() {
        const { exchangeData, requestExchangeData } = this.state;
        return (
            <React.Fragment>
                <TextContent>
                    <Text component="h1" className="centered">
                        <b>Historical Currency Data</b>
                    </Text>
                </TextContent>
                <Form onSubmit={this.submit} >
                    <Flex>
                        <FlexItem>
                            <FormGroup
                                isInline={true}
                                label="Source currency"
                                fieldId="source_group"
                            >
                                <FormSelect
                                    value={this.state.src}
                                    onChange={this.onChangeSrc}
                                    id="src"
                                    aria-label="FormSelect Input"
                                >
                                    {this.state.loading
                                        ? <FormSelectOption isDisabled={true} label="Loading currencies" />
                                        : this.state.currencies.map((curr, index) => (
                                            <FormSelectOption key={index} value={curr} label={curr} />
                                        ))
                                    }
                                </FormSelect>
                            </FormGroup>
                        </FlexItem>
                        <FlexItem>
                            <FormGroup
                                label="Target currency"
                                isInline={true}
                                fieldId="target_group"
                            >
                                <FormSelect
                                    value={this.state.target}
                                    onChange={this.onChangeTarget}
                                    id="target"
                                    aria-label="FormSelect Input"
                                >
                                    {this.state.loading
                                        ? <FormSelectOption isDisabled={true} label="Loading currencies" />
                                        : this.state.currencies.map((curr, index) => (
                                            <FormSelectOption key={index} value={curr} label={curr} />
                                        ))
                                    }
                                </FormSelect>
                            </FormGroup>
                        </FlexItem>
                        <FlexItem>
                        </FlexItem>
                    </Flex>
                    <span>
                        <Button isDisabled={this.state.loading || this.state.src === this.state.target} type="submit" variant="primary">Submit</Button>
                    </span>
                </Form>
                {requestExchangeData && exchangeData && <RenderedChart data={exchangeData} target={this.state.target} amount={this.state.amount} />}
                {requestExchangeData && !exchangeData && <Spinner />}
            </React.Fragment>
        )
    }
};
export default CurrencyPicker;
mczernek-exchange-application/frontend/src/Loading.js
New file
@@ -0,0 +1,27 @@
import React from 'react';
import {
  Title,
  EmptyState,
  EmptyStateIcon,
} from '@patternfly/react-core';
const EmptyStateSpinner = () => {
  const Spinner = () => (
    <span className="pf-c-spinner" role="progressbar" aria-valuetext="Loading...">
      <span className="pf-c-spinner__clipper" />
      <span className="pf-c-spinner__lead-ball" />
      <span className="pf-c-spinner__tail-ball" />
    </span>
  )
  return (
    <EmptyState>
      <EmptyStateIcon variant="container" component={Spinner} />
      <Title size="lg">
        Loading
      </Title>
    </EmptyState>
  );
}
export default EmptyStateSpinner;
mczernek-exchange-application/frontend/src/MainStructure.js
New file
@@ -0,0 +1,49 @@
import React from 'react';
import { Brand, Page, PageHeader, PageSidebar, PageSection } from '@patternfly/react-core';
import imgBrand from './training_white.png'
import NavList from './NavList'
class VerticalPage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isNavOpen: true,
    };
    this.onNavToggle = () => {
      this.setState({
        isNavOpen: !this.state.isNavOpen
      });
    };
  }
  render() {
    const { isNavOpen } = this.state;
    const logoProps = {
      href: '/'
    };
    const Header = (
      <PageHeader
        logo={<Brand src={imgBrand} alt="Patternfly Logo" />}
        logoProps={logoProps}
        showNavToggle
        isNavOpen={isNavOpen}
        onNavToggle={this.onNavToggle}
        style={{ borderTop: "2px solid #c00" }}
      />
    );
    const Sidebar = <PageSidebar nav={<NavList/>} isNavOpen={isNavOpen} theme="dark" />;
    return (
      <Page header={Header} sidebar={Sidebar} style={{minHeight: 800}}>
        <PageSection >
          {this.props.children}
        </PageSection>
      </Page>
    );
  }
}
export default VerticalPage;
mczernek-exchange-application/frontend/src/NavList.js
New file
@@ -0,0 +1,48 @@
import React from 'react';
import {
    Nav,
    NavItem,
    NavList,
} from '@patternfly/react-core';
import { Link} from "react-router-dom";
class NavDefaultList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            activeItem: 0
        };
        this.onSelect = result => {
            this.setState({
                activeItem: result.itemId
            });
        };
    }
    render() {
        const { activeItem } = this.state;
        return (
            <Nav onSelect={this.onSelect} theme="dark">
                <NavList>
                    <NavItem id="home" itemId={0} isActive={activeItem === 0}>
                        <Link to="/">Home</Link>
                    </NavItem>
                    <NavItem id="historical_Data" itemId={1} isActive={activeItem === 1}>
                        <Link to="/history" >Historical Data</Link>
                    </NavItem>
                    <NavItem id="exchange" itemId={2} isActive={activeItem === 2}>
                        <Link to="/exchange" >Exchange</Link>
                    </NavItem>
                    {/* <NavItem id="status" itemId={3} isActive={activeItem === 3}>
                        <Link to="/status" >Application Status</Link>
                    </NavItem> */}
                </NavList>
            </Nav>
        );
    }
}
export default NavDefaultList;
mczernek-exchange-application/frontend/src/SingleCurrencyExchange.js
New file
@@ -0,0 +1,186 @@
import React, { Component } from 'react';
import {
    Form,
    FormGroup,
    FormSelect,
    FormSelectOption,
    Button,
    TextContent,
    Text,
    TextInput,
    TextVariants,
    Flex,
    FlexItem,
} from '@patternfly/react-core';
import Spinner from './Loading';
class CurrencyPicker extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            currencies: [],
            src: 'Loading currencies',
            target: 'Loading currencies',
            exchangeData: '',
            requestExchangeData: false,
            inputValue: 1,
            inputValid: true,
        };
    }
    componentDidMount() {
        this.setState({
            loading: true
        })
        fetch('http://localhost:8080')
            .then(currencies => currencies.json())
            .then(currencies => this.setState({
                currencies, src: currencies[0], target: currencies[1], loading: false
            }))
            .catch(err => console.log(err));
    }
    onChangeSrc = (src) => {
        this.setState({ src, requestExchangeData: false });
    };
    onChangeTarget = (target) => {
        this.setState({ target, requestExchangeData: false });
    };
    onChangeInput = (inputValue) => {
        const inputValid = this.inputValidation(inputValue);
        this.setState({ inputValue, inputValid });
    }
    inputValidation = (input) => {
        return input > 0
    }
    submit = (e) => {
        e.preventDefault();
        this.setState({ requestExchangeData: true })
        fetch(`http://localhost:8080/${this.state.src}`, {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
        })
            .then(exchangeData => exchangeData.json())
            .then(exchangeData => this.setState({ exchangeData }))
            .catch(err => console.log(err))
    };
    render() {
        const { exchangeData, requestExchangeData } = this.state;
        return (
            <React.Fragment>
                <TextContent>
                    <Text component="h1" className="centered">
                        <b>Single Currency Exchange</b>
                    </Text>
                </TextContent>
                <Form onSubmit={this.submit} >
                    <Flex>
                        <FlexItem>
                            <FormGroup
                                isInline={true}
                                label="Amount"
                                fieldId="amount_group"
                            >
                                <TextInput
                                    value={this.state.inputValue}
                                    name="amount"
                                    type="number"
                                    onChange={this.onChangeInput}
                                    isValid={this.state.inputValid}
                                    aria-label="amount from input" />
                            </FormGroup>
                        </FlexItem>
                        <FlexItem>
                            <FormGroup
                                isInline={true}
                                label="Source currency"
                                fieldId="source_group"
                            >
                                <FormSelect
                                    value={this.state.src}
                                    onChange={this.onChangeSrc}
                                    id="src"
                                    aria-label="FormSelect Input"
                                >
                                    {this.state.loading
                                        ? <FormSelectOption isDisabled={true} label="Loading currencies" />
                                        : this.state.currencies.map((curr, index) => (
                                            <FormSelectOption key={index} value={curr} label={curr} />
                                        ))
                                    }
                                </FormSelect>
                            </FormGroup>
                        </FlexItem>
                        <FlexItem>
                            <FormGroup
                                label="Target currency"
                                isInline={true}
                                fieldId="target_group"
                            >
                                <FormSelect
                                    value={this.state.target}
                                    onChange={this.onChangeTarget}
                                    id="target"
                                    aria-label="FormSelect Input"
                                >
                                    {this.state.loading
                                        ? <FormSelectOption isDisabled={true} label="Loading currencies" />
                                        : this.state.currencies.map((curr, index) => (
                                            <FormSelectOption key={index} value={curr} label={curr} />
                                        ))
                                    }
                                </FormSelect>
                            </FormGroup>
                        </FlexItem>
                    </Flex>
                    <span>
                        <Button isDisabled={this.isLoadingOrCurrenciesEqual()} type="submit" variant="primary">Submit</Button>
                    </span>
                </Form>
                {this.displayConversion() &&
                    <div>
                        <TextContent className="margin-separator">
                            <Text component={TextVariants.p} className="text-container">
                                <span className="currency-text">
                                    {exchangeData.targetSign}
                                </span>
                                {exchangeData.value * this.state.inputValue}
                            </Text>
                        </TextContent>
                    </div>
                }
                {requestExchangeData && !exchangeData && <Spinner />}
            </React.Fragment>
        )
    }
    displayConversion() {
        const {requestExchangeData, exchangeData, src, target, inputValue} = this.state;
        return requestExchangeData && exchangeData &&
            (src !== target) &&
            this.inputValidation(inputValue);
    }
    isLoadingOrCurrenciesEqual() {
        const {loading, src, target, inputValue} = this.state;
        return loading || (src === target) || (!this.inputValidation(inputValue));
    }
};
export default CurrencyPicker;
mczernek-exchange-application/frontend/src/Status.js
New file
@@ -0,0 +1,66 @@
import React, { Component } from 'react';
import { List, ListItem } from '@patternfly/react-core';
export default class Status extends Component {
    constructor(props) {
        super(props);
        this.state = {
            service1: false,
            service2: false,
            service3: false
        };
    }
    testService1() {
        const timeout = (time, promise) => {
            return new Promise(function (resolve, reject) {
                setTimeout(() => {
                    reject(new Error('Request timed out.'))
                }, time);
                promise.then(resolve, reject);
            });
        }
        const controller = new AbortController();
        const signal = controller.signal;
        timeout(3000, fetch('http://localhost:8080', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ src: "EUR", target: "USD" }),
            signal: signal
        }))
            .then(data => data = data.json())
            .then(this.setState({ service1: true }))
            .catch(err => {
                console.log(err);
                controller.abort();
            })
    }
    testService2() {
    }
    componentDidMount() {
        this.testService1()
    }
    render() {
        const { service1, service2, service3 } = this.state;
        console.log(service1)
        return (
            <List>
                <ListItem>Service 1 - {service1 ? "OK" : "NOK"} </ListItem>
                <ListItem>Service 2 - {service2 ? "OK" : "NOK"}</ListItem>
                <ListItem>Service 3 - {service3 ? "OK" : "NOK"}</ListItem>
            </List>
        )
    }
}
mczernek-exchange-application/frontend/src/Welcome.js
New file
@@ -0,0 +1,33 @@
import React, { Component } from 'react';
import rhtLogo from './training_black.png'
import { TextContent, Text } from '@patternfly/react-core'
export default class WelcomePage extends Component {
    render() {
        return (
            <TextContent>
                <Text component="h1" className="centered">
                    <b>Welcome to the currency exchange application of DO328!</b>
                </Text>
                <div className="centered">
                    <img src={rhtLogo} alt="Red Hat Training Logo" />
                </div>
                <Text component="p">
                    Please choose one of the two links on the left:
                </Text>
                <ul>
                    <li>Historical data for seeing currency's exchange rate in time</li>
                    <li>Exchange for seeing how much money is your amount worth in a different currency</li>
                </ul>
                <Text component="p">
                    For detailed info about the structure of this application, see #github link here.
                </Text>
                <Text component="p">
                    To file issues or ask questions, see #github link here.
                </Text>
            </TextContent>
        )
    }
}
mczernek-exchange-application/frontend/src/index.js
New file
@@ -0,0 +1,13 @@
import React from 'react';
import ReactDOM from 'react-dom';
import '@patternfly/react-core/dist/styles/base.css';
import './App.css'
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
mczernek-exchange-application/frontend/src/serviceWorker.js
New file
@@ -0,0 +1,141 @@
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://bit.ly/CRA-PWA
const isLocalhost = Boolean(
  window.location.hostname === 'localhost' ||
    // [::1] is the IPv6 localhost address.
    window.location.hostname === '[::1]' ||
    // 127.0.0.0/8 are considered localhost for IPv4.
    window.location.hostname.match(
      /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
    )
);
export function register(config) {
  if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
    // The URL constructor is available in all browsers that support SW.
    const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
    if (publicUrl.origin !== window.location.origin) {
      // Our service worker won't work if PUBLIC_URL is on a different origin
      // from what our page is served on. This might happen if a CDN is used to
      // serve assets; see https://github.com/facebook/create-react-app/issues/2374
      return;
    }
    window.addEventListener('load', () => {
      const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
      if (isLocalhost) {
        // This is running on localhost. Let's check if a service worker still exists or not.
        checkValidServiceWorker(swUrl, config);
        // Add some additional logging to localhost, pointing developers to the
        // service worker/PWA documentation.
        navigator.serviceWorker.ready.then(() => {
          console.log(
            'This web app is being served cache-first by a service ' +
              'worker. To learn more, visit https://bit.ly/CRA-PWA'
          );
        });
      } else {
        // Is not localhost. Just register service worker
        registerValidSW(swUrl, config);
      }
    });
  }
}
function registerValidSW(swUrl, config) {
  navigator.serviceWorker
    .register(swUrl)
    .then(registration => {
      registration.onupdatefound = () => {
        const installingWorker = registration.installing;
        if (installingWorker == null) {
          return;
        }
        installingWorker.onstatechange = () => {
          if (installingWorker.state === 'installed') {
            if (navigator.serviceWorker.controller) {
              // At this point, the updated precached content has been fetched,
              // but the previous service worker will still serve the older
              // content until all client tabs are closed.
              console.log(
                'New content is available and will be used when all ' +
                  'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
              );
              // Execute callback
              if (config && config.onUpdate) {
                config.onUpdate(registration);
              }
            } else {
              // At this point, everything has been precached.
              // It's the perfect time to display a
              // "Content is cached for offline use." message.
              console.log('Content is cached for offline use.');
              // Execute callback
              if (config && config.onSuccess) {
                config.onSuccess(registration);
              }
            }
          }
        };
      };
    })
    .catch(error => {
      console.error('Error during service worker registration:', error);
    });
}
function checkValidServiceWorker(swUrl, config) {
  // Check if the service worker can be found. If it can't reload the page.
  fetch(swUrl, {
    headers: { 'Service-Worker': 'script' }
  })
    .then(response => {
      // Ensure service worker exists, and that we really are getting a JS file.
      const contentType = response.headers.get('content-type');
      if (
        response.status === 404 ||
        (contentType != null && contentType.indexOf('javascript') === -1)
      ) {
        // No service worker found. Probably a different app. Reload the page.
        navigator.serviceWorker.ready.then(registration => {
          registration.unregister().then(() => {
            window.location.reload();
          });
        });
      } else {
        // Service worker found. Proceed as normal.
        registerValidSW(swUrl, config);
      }
    })
    .catch(() => {
      console.log(
        'No internet connection found. App is running in offline mode.'
      );
    });
}
export function unregister() {
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.ready
      .then(registration => {
        registration.unregister();
      })
      .catch(error => {
        console.error(error.message);
      });
  }
}
mczernek-exchange-application/frontend/src/setupTests.js
New file
@@ -0,0 +1,5 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom/extend-expect';
mczernek-exchange-application/frontend/src/training_black.png
mczernek-exchange-application/frontend/src/training_white.png
mczernek-exchange-application/frontend/yarn.lock
New file
Diff too large