Skip to content
Snippets Groups Projects
Commit 9849dcba authored by Ulrik Ofstad's avatar Ulrik Ofstad
Browse files

commit

parent e5a3e749
No related branches found
No related tags found
No related merge requests found
Showing
with 726 additions and 74 deletions
.DS_Store 0 → 100644
File added
node_modules
config.ts
bundle.js
bundle.js.map
coverage
LICENSE 0 → 100644
MIT License
Copyright (c) 2020-2022 ntnu-dcst2002
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# React
# Client tests example
## Setup database connections
You need to create two configuration files that will contain the database connection details. These
files should not be uploaded to your git repository, and they have therefore been added to
`.gitignore`. The connection details may vary, but example content of the two configuration files
are as follows:
## Getting started
`server/config.ts`:
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://gitlab.stud.idi.ntnu.no/ulrikof/react.git
git branch -M main
git push -uf origin main
```ts
process.env.MYSQL_HOST = 'mysql.stud.ntnu.no';
process.env.MYSQL_USER = 'username_todo';
process.env.MYSQL_PASSWORD = 'username_todo';
process.env.MYSQL_DATABASE = 'username_todo_dev';
```
## Integrate with your tools
- [ ] [Set up project integrations](https://gitlab.stud.idi.ntnu.no/ulrikof/react/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
`server/test/config.ts`:
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
```ts
process.env.MYSQL_HOST = 'mysql.stud.ntnu.no';
process.env.MYSQL_USER = 'username_todo';
process.env.MYSQL_PASSWORD = 'username_todo';
process.env.MYSQL_DATABASE = 'username_todo_test';
```
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
These environment variables will be used in the `server/src/mysql-pool.ts` file.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Start server
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
Install dependencies and start server:
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
```sh
cd server
npm install
npm start
```
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
### Run server tests:
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
```sh
npm test
```
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
## Bundle client files to be served through server
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
Install dependencies and bundle client files:
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
```sh
cd client
npm install
npm start
```
## License
For open source projects, say how it is licensed.
### Run client tests:
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
```sh
npm test
```
{
"presets": ["@babel/preset-env", "@babel/preset-typescript", "@babel/preset-react"],
"highlightCode": false
}
package-lock=false
{
"name": "todo-client",
"version": "1.0.0",
"description": "A simple Todo web client",
"license": "MIT",
"scripts": {
"start": "webpack --mode development --watch",
"test": "jest --setupFiles ./test/setup.tsx"
},
"jest": {
"testEnvironment": "jsdom",
"snapshotSerializers": [
"enzyme-to-json/serializer"
],
"collectCoverage": true
},
"browserslist": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
],
"dependencies": {
"axios": "^1.5.0",
"react-router-dom-v5-compat": "^6.16.0",
"react-simplified": "^4.0.1"
},
"devDependencies": {
"@babel/core": "^7.22.17",
"@babel/preset-env": "^7.22.15",
"@babel/preset-react": "^7.22.15",
"@babel/preset-typescript": "^7.22.15",
"@cfaester/enzyme-adapter-react-18": "^0.7.1",
"@types/enzyme": "^3.10.13",
"@types/jest": "^29.5.4",
"@types/react-dom": "^18.2.7",
"@types/react-router-dom": "^5.3.3",
"babel-jest": "^29.7.0",
"babel-loader": "^9.1.3",
"enzyme": "^3.11.0",
"enzyme-to-json": "^3.6.2",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"prettier": "^3.0.3",
"typescript": "^5.2.2",
"webpack": "^5.88.2",
"webpack-cli": "^5.1.4"
}
}
Source diff could not be displayed: it is too large. Options to address this: view the blob.
This diff is collapsed.
This diff is collapsed.
Source diff could not be displayed: it is too large. Options to address this: view the blob.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Todo web application example</title>
<link rel="stylesheet" href="bootstrap.min.css" />
</head>
<body>
<div id="root"></div>
<script src="bootstrap.min.js"></script>
<!-- Embed React application bundled by webpack and babel -->
<script src="bundle.js"></script>
</body>
</html>
import * as React from 'react';
import { createRoot } from 'react-dom/client';
import { Component } from 'react-simplified';
import { HashRouter, Route } from 'react-router-dom';
import { NavBar, Card, Alert, Row, Column, Form, Button } from './widgets';
import taskService from './task-service';
class App extends Component {
input: string = '';
stdout: string = '';
stderr: string = '';
language = 'js';
render() {
return (
<>
<Card title="Skriv inne kode!">
<Row>
<Column>
<select
value={this.language}
onChange={(event) => (this.language = event.target.value)}
>
<option value="js">js</option>
<option value="python">python</option>
</select>
<Form.Textarea
type="string"
value={this.input}
onChange={(event) => (this.input = event.currentTarget.value)}
></Form.Textarea>
<Button.Success
onClick={() => {
this.runButton();
}}
>
Run Code
</Button.Success>
</Column>
</Row>
</Card>
<Card title="Output">
<Card title="Stdout">
<pre>{this.stdout}</pre>
</Card>
<Card title="Stderr">
<pre>{this.stderr}</pre>
</Card>
</Card>
</>
);
}
async runButton() {
try {
let response = await taskService.create(this.input, this.language);
this.stdout = response.stdoutData;
this.stderr = response.stderrData;
} catch (error) {
console.error(error);
}
}
}
let root = document.getElementById('root');
if (root)
createRoot(root).render(
<>
<App></App>
</>,
);
import axios from 'axios';
axios.defaults.baseURL = 'http://localhost:3000/api/v2';
export type Task = {
id: number;
title: string;
done: boolean;
};
type Response_data = {
stdoutData: '';
stderrData: '';
};
class TaskService {
create(input: string, language: string) {
return axios
.post<Response_data>('/tasks', { input: input, language: language })
.then((response) => response.data);
}
}
const taskService = new TaskService();
export default taskService;
import * as React from 'react';
import { ReactNode, ChangeEvent } from 'react';
import { Component } from 'react-simplified';
import { NavLink } from 'react-router-dom';
/**
* Renders an information card using Bootstrap classes.
*
* Properties: title
*/
export class Card extends Component<{ title: ReactNode }> {
render() {
return (
<div className="card">
<div className="card-body">
<h5 className="card-title">{this.props.title}</h5>
<div className="card-text">{this.props.children}</div>
</div>
</div>
);
}
}
/**
* Renders a row using Bootstrap classes.
*/
export class Row extends Component {
render() {
return <div className="row">{this.props.children}</div>;
}
}
/**
* Renders a column with specified width using Bootstrap classes.
*
* Properties: width, right
*/
export class Column extends Component<{ width?: number; right?: boolean }> {
render() {
return (
<div className={'col' + (this.props.width ? '-' + this.props.width : '')}>
<div className={'float-' + (this.props.right ? 'end' : 'start')}>{this.props.children}</div>
</div>
);
}
}
/**
* Renders a success button using Bootstrap styles.
*
* Properties: small, onClick
*/
class ButtonSuccess extends Component<{
small?: boolean;
onClick: () => void;
}> {
render() {
return (
<button
type="button"
className="btn btn-success"
style={
this.props.small
? {
padding: '5px 5px',
fontSize: '16px',
lineHeight: '0.7',
}
: {}
}
onClick={this.props.onClick}
>
{this.props.children}
</button>
);
}
}
/**
* Renders a danger button using Bootstrap styles.
*
* Properties: small, onClick
*/
class ButtonDanger extends Component<{
small?: boolean;
onClick: () => void;
}> {
render() {
return (
<button
type="button"
className="btn btn-danger"
style={
this.props.small
? {
padding: '5px 5px',
fontSize: '16px',
lineHeight: '0.7',
}
: {}
}
onClick={this.props.onClick}
>
{this.props.children}
</button>
);
}
}
/**
* Renders a light button using Bootstrap styles.
*
* Properties: small, onClick
*/
class ButtonLight extends Component<{
small?: boolean;
onClick: () => void;
}> {
render() {
return (
<button
type="button"
className="btn btn-light"
style={
this.props.small
? {
padding: '5px 5px',
fontSize: '16px',
lineHeight: '0.7',
}
: {}
}
onClick={this.props.onClick}
>
{this.props.children}
</button>
);
}
}
/**
* Renders a button using Bootstrap styles.
*
* Properties: onClick
*/
export class Button {
static Success = ButtonSuccess;
static Danger = ButtonDanger;
static Light = ButtonLight;
}
/**
* Renders a NavBar link using Bootstrap styles.
*
* Properties: to
*/
class NavBarLink extends Component<{ to: string }> {
render() {
return (
<NavLink className="nav-link" activeClassName="active" to={this.props.to}>
{this.props.children}
</NavLink>
);
}
}
/**
* Renders a NavBar using Bootstrap classes.
*
* Properties: brand
*/
export class NavBar extends Component<{ brand: ReactNode }> {
static Link = NavBarLink;
render() {
return (
<nav className="navbar navbar-expand-sm navbar-light bg-light">
<div className="container-fluid justify-content-start">
<NavLink className="navbar-brand" activeClassName="active" exact to="/">
{this.props.brand}
</NavLink>
<div className="navbar-nav">{this.props.children}</div>
</div>
</nav>
);
}
}
/**
* Renders a form label using Bootstrap styles.
*/
class FormLabel extends Component {
render() {
return <label className="col-form-label">{this.props.children}</label>;
}
}
/**
* Renders a form input using Bootstrap styles.
*/
class FormInput extends Component<{
type: string;
value: string | number;
onChange: (event: ChangeEvent<HTMLInputElement>) => void;
[prop: string]: any;
}> {
render() {
// ...rest will contain extra passed attributes such as disabled, required, width, height, pattern
// For further information, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
const { type, value, onChange, ...rest } = this.props;
return (
<input
{...rest}
className="form-control"
type={this.props.type}
value={this.props.value}
onChange={this.props.onChange}
/>
);
}
}
/**
* Renders a form textarea using Bootstrap styles.
*/
class FormTextarea extends React.Component<{
value: string | number;
onChange: (event: ChangeEvent<HTMLTextAreaElement>) => void;
[prop: string]: any;
}> {
render() {
// ...rest will contain extra passed attributes such as disabled, required, rows, cols
// For further information, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
const { value, onChange, ...rest } = this.props;
return <textarea {...rest} className="form-control" value={value} onChange={onChange} />;
}
}
/**
* Renders a form checkbox using Bootstrap styles.
*/
class FormCheckbox extends Component<{
checked: boolean;
onChange: (event: ChangeEvent<HTMLInputElement>) => void;
[prop: string]: any;
}> {
render() {
// ...rest will contain extra passed attributes such as disabled, required, width, height, pattern
// For further information, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
const { checked, onChange, ...rest } = this.props;
return (
<input
{...rest}
className="form-check-input"
type="checkbox"
checked={checked}
onChange={onChange}
/>
);
}
}
/**
* Renders a form select using Bootstrap styles.
*/
class FormSelect extends Component<{
value: string | number;
onChange: (event: ChangeEvent<HTMLSelectElement>) => void;
[prop: string]: any;
}> {
render() {
// ...rest will contain extra passed attributes such as disabled, required, size.
// For further information, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
const { value, onChange, children, ...rest } = this.props;
return (
<select {...rest} className="custom-select" value={value} onChange={onChange}>
{children}
</select>
);
}
}
/**
* Renders form components using Bootstrap styles.
*/
export class Form {
static Label = FormLabel;
static Input = FormInput;
static Textarea = FormTextarea;
static Checkbox = FormCheckbox;
static Select = FormSelect;
}
/**
* Renders alert messages using Bootstrap classes.
*
* Students: this slightly more complex component is not part of curriculum.
*/
export class Alert extends Component {
alerts: { id: number; text: ReactNode; type: string }[] = [];
nextId: number = 0;
render() {
return (
<div>
{this.alerts.map((alert, i) => (
<div
key={alert.id}
className={'alert alert-dismissible alert-' + alert.type}
role="alert"
>
{alert.text}
<button
type="button"
className="btn-close btn-sm"
onClick={() => this.alerts.splice(i, 1)}
/>
</div>
))}
</div>
);
}
/**
* Show success alert.
*/
static success(text: ReactNode) {
// To avoid 'Cannot update during an existing state transition' errors, run after current event through setTimeout
setTimeout(() => {
let instance = Alert.instance(); // Get rendered Alert component instance
if (instance) instance.alerts.push({ id: instance.nextId++, text: text, type: 'success' });
});
}
/**
* Show info alert.
*/
static info(text: ReactNode) {
// To avoid 'Cannot update during an existing state transition' errors, run after current event through setTimeout
setTimeout(() => {
let instance = Alert.instance(); // Get rendered Alert component instance
if (instance) instance.alerts.push({ id: instance.nextId++, text: text, type: 'info' });
});
}
/**
* Show warning alert.
*/
static warning(text: ReactNode) {
// To avoid 'Cannot update during an existing state transition' errors, run after current event through setTimeout
setTimeout(() => {
let instance = Alert.instance(); // Get rendered Alert component instance
if (instance) instance.alerts.push({ id: instance.nextId++, text: text, type: 'warning' });
});
}
/**
* Show danger alert.
*/
static danger(text: ReactNode) {
// To avoid 'Cannot update during an existing state transition' errors, run after current event through setTimeout
setTimeout(() => {
let instance = Alert.instance(); // Get rendered Alert component instance
if (instance) instance.alerts.push({ id: instance.nextId++, text: text, type: 'danger' });
});
}
}
import * as React from 'react';
import { Alert } from '../src/widgets';
import { shallow } from 'enzyme';
describe('Alert tests', () => {
test('No alerts initially', () => {
const wrapper = shallow(<Alert />);
expect(wrapper.matchesElement(<div></div>)).toEqual(true);
});
test('Show alert message', (done) => {
const wrapper = shallow(<Alert />);
Alert.danger('test');
// Wait for events to complete
setTimeout(() => {
expect(
wrapper.matchesElement(
<div>
<div>
test
<button />
</div>
</div>
)
).toEqual(true);
done();
});
});
test('Close alert message', (done) => {
const wrapper = shallow(<Alert />);
Alert.danger('test');
// Wait for events to complete
setTimeout(() => {
expect(
wrapper.matchesElement(
<div>
<div>
test
<button />
</div>
</div>
)
).toEqual(true);
wrapper.find('button.btn-close').simulate('click');
expect(wrapper.matchesElement(<div></div>)).toEqual(true);
done();
});
});
});
import { configure } from 'enzyme';
import Adapter from '@cfaester/enzyme-adapter-react-18';
configure({ adapter: new Adapter() });
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"esModuleInterop": true,
"jsx": "react",
"strict": true,
"sourceMap": true,
"baseUrl": ".",
"paths": {
"react-simplified": ["@types/react-simplified.d.ts"]
}
}
}
// @flow
/**
* Configuration file for webpack.
*
* Webpack bundles several JavaScript files into a single file
* for easier script embedding in an index.html file.
*/
const path = require('path');
module.exports = {
entry: './src/index.tsx', // Initial file to bundle
resolve: {
extensions: ['.js', '.jsx', '.ts', '.tsx'],
},
output: {
// Output file: ./public/bundle.js
path: path.resolve(__dirname, 'public'),
filename: 'bundle.js',
},
// Makes original source code available to the browser for easier identification of error causes.
devtool: 'source-map',
module: {
rules: [
{
// Use babel to parse .tsx files in the src folder
test: /\.tsx$/,
include: path.resolve(__dirname, 'src'),
use: ['babel-loader'],
},
],
},
};
{
"presets": ["@babel/preset-env", "@babel/preset-typescript"]
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment