feat(my-todo-list-ui): initial commit

This commit is contained in:
dancingCycle 2023-08-15 10:17:33 +02:00
parent a3d147f7e3
commit cf3770fb6d
32 changed files with 24401 additions and 0 deletions

View File

@ -0,0 +1,6 @@
{
"presets": [
"@babel/preset-env",
"@babel/preset-react"
]
}

107
my-todo-list-ui-no-ux/.gitignore vendored Normal file
View File

@ -0,0 +1,107 @@
# Others
build*
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript v1 declaration files
typings/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.env.test
# parcel-bundler cache (https://parceljs.org/)
.cache
# Next.js build output
.next
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port

View File

@ -0,0 +1,16 @@
import React from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom'
import Home from './pages/home';
import PrivateRoute from './components/private-route'
export default function App() {
return (
<Router>
<Routes>
<Route path="/" element={<PrivateRoute><Home /></PrivateRoute>} />
<Route path="*" element={<Navigate to="/" />} />
</Routes>
</Router>
)
}

View File

@ -0,0 +1,17 @@
import React from 'react'
import { useAuth } from "react-oidc-context"
export default function AuthBar() {
const auth = useAuth()
return (
<div>
Hi {auth.user?.profile.preferred_username} .
<button
onClick={() => auth.signoutRedirect()}
>
Logout
</button>
</div>
)
}

View File

@ -0,0 +1,34 @@
import React from 'react'
import { useAuth } from "react-oidc-context"
function PrivateRoute({ children }) {
const auth = useAuth()
if (auth.isLoading) {
return (
<div>
<p>Keycloak is loading</p>
<p>or running authorization code flow with PKCE</p>
</div>
)
}
if (auth.error) {
return (
<div>
<p>Oops ...</p>
<p>{auth.error.message}</p>
</div>
)
}
if (!auth.isAuthenticated) {
auth.signinRedirect()
return null
}
return children
}
export default PrivateRoute

View File

@ -0,0 +1,38 @@
import React from 'react';
import ReactDOM from 'react-dom';
import App from './app';
import { AuthProvider } from "react-oidc-context";
//TODO remove debugging
if (process.env.NODE_ENV !== 'production') {
console.log('development mode');
}
//since react 18
import { createRoot } from 'react-dom/client';
//create root container
const root = createRoot(document.getElementById("root"));
//open id connect config
const oidcConfig = {
authority: "https://kc.swingbe.de/realms/Ivan-Franchin",
client_id: "my-todo-list",
redirect_uri: "http://localhost:8080",
onSigninCallback: () => {
window.history.replaceState(
{},
document.title,
window.location.pathname
)
}
}
//render root app
root.render(
<AuthProvider {...oidcConfig}>
<React.StrictMode>
<App />
</React.StrictMode>
</AuthProvider>
);

View File

@ -0,0 +1,17 @@
import React from 'react';
import { useAuth } from "react-oidc-context"
import AuthBar from '../components/auth-bar'
const Home = () => {
const auth = useAuth()
const access_token = auth.user.access_token
return (
<>
<AuthBar />
<h2>Home</h2>
</>
);
}
export default Home

View File

@ -0,0 +1,41 @@
//generate a HTML5 file including all webpack bundles in the body using script tags
const HtmlWebpackPlugin = require('html-webpack-plugin');
//path is used to resolve properly across the OS
const path = require('path');
module.exports = {
//bundle *.js from this entry point
entry: path.resolve(__dirname, '../app/index.jsx'),
//create output file to be linked to index.html
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, '../dist'),
clean: true,
},
module: {
rules: [
{
//test all *.js using babel-loader
//test all *.jsx (e.g. React.js) using babel-loader
test: /\.(js|jsx)$/,
exclude: /node_modules/,
include: path.resolve(__dirname, '../app'),
use: ['babel-loader'],
},
{
//test all *.css using style-loader and css-loader
test: /\.css$/i,
use: ["style-loader", "css-loader"],
},
]
},
resolve: {
extensions: ['*', '.js', '.jsx'],
},
plugins: [
// create a plugin instance so that you can use it several times anywhere
new HtmlWebpackPlugin({
title: 'Production',
template: path.resolve(__dirname, "../public/index.html")
}),
],
};

View File

@ -0,0 +1,16 @@
//path is used to resolve properly across the OS
const path = require('path');
const { merge } = require('webpack-merge');
const common = require('./webpack.common.js');
//merge() calls in the environment-specific configuration to include commons
module.exports = merge(common, {
//set development mode
mode: 'development',
//enable strong source mapping
devtool: 'inline-source-map',
devServer: {
static: path.resolve(__dirname, '../dist'),
//When using the HTML5 History API, the index.html page will likely have to be served in place of any 404 responses. Enable devServer.historyApiFallback by setting it to true.
historyApiFallback: true,
},
});

View File

@ -0,0 +1,8 @@
const { merge } = require('webpack-merge');
const common = require('./webpack.common.js');
module.exports = merge(common, {
mode: 'production',
//source maps encouraged in production
//choose mapping with fairly quick build speed like source-map
devtool: 'source-map',
});

10848
my-todo-list-ui-no-ux/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,37 @@
{
"private": true,
"name": "react-example",
"description": "React.js example",
"version": "0.1.0",
"main": "index.js",
"keywords": [
"react",
"webpack"
],
"author": "Software Ingenieur Begerad <dialog@SwIngBe.de>",
"license": "GPL-3.0-or-later",
"scripts": {
"start": "webpack serve --config config/webpack.dev.js",
"build": "webpack --config config/webpack.prod.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"devDependencies": {
"@babel/core": "7.22.10",
"@babel/preset-env": "7.22.10",
"@babel/preset-react": "7.22.5",
"babel-loader": "9.1.3",
"html-webpack-plugin": "5.5.3",
"webpack": "5.88.2",
"webpack-cli": "5.1.4",
"webpack-dev-server": "4.15.1",
"webpack-merge": "5.9.0"
},
"dependencies": {
"oidc-client-ts": "2.2.4",
"prop-types": "15.8.1",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-oidc-context": "2.2.2",
"react-router-dom": "6.15.0"
}
}

View File

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>title</title>
</head>
<body>
<div id="root"></div>
</body>
</html>

View File

@ -0,0 +1,15 @@
# React.js Example
## Table of Contents
0. [General](#general)
1. [Links](#links)
# General
# Links
* [React setup with webpack for beginners](https://dev.to/deepanjangh/react-setup-with-webpack-for-beginners-2a8k)
* [Production](https://webpack.js.org/guides/production/)
* [Setup Development and Production Environment for React App](https://medium.com/freestoneinfotech/setup-development-and-production-environment-for-react-app-397c4cc9e382)
* [HtmlWebpackPlugin](https://webpack.js.org/plugins/html-webpack-plugin/)
* [Using Keycloak to secure React](https://medium.com/p/6b2d80fc5c12)

6
my-todo-list-ui/.babelrc Normal file
View File

@ -0,0 +1,6 @@
{
"presets": [
"@babel/preset-env",
"@babel/preset-react"
]
}

107
my-todo-list-ui/.gitignore vendored Normal file
View File

@ -0,0 +1,107 @@
# Others
build*
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript v1 declaration files
typings/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.env.test
# parcel-bundler cache (https://parceljs.org/)
.cache
# Next.js build output
.next
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port

View File

@ -0,0 +1,18 @@
import React from 'react'
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom'
import Home from './components/home'
import PrivateRoute from './components/private-route'
function App() {
return (
<Router>
<Routes>
<Route path="/" element={<PrivateRoute><Home /></PrivateRoute>} />
<Route path="*" element={<Navigate to="/" />} />
</Routes>
</Router>
)
}
export default App

View File

@ -0,0 +1,30 @@
import React from 'react'
import { useAuth } from "react-oidc-context"
import { Space, Typography, Button } from 'antd'
const { Text } = Typography
function AuthBar() {
const auth = useAuth()
const spaceStyle = {
background: "lightgrey",
justifyContent: "end",
paddingRight: "10px"
}
return (
<Space wrap style={spaceStyle}>
<Text>Hi {auth.user?.profile.preferred_username}</Text>
<Button
type="primary"
size="small"
onClick={() => auth.signoutRedirect()}
danger
>
Logout
</Button>
</Space>
)
}
export default AuthBar

View File

@ -0,0 +1,98 @@
import React, { useEffect, useState } from 'react'
import { Layout, Col, Row } from 'antd'
import { useAuth } from "react-oidc-context"
import AuthBar from './auth-bar'
import { myToDoListApi } from './to-do-list-api'
import ToDoForm from './to-do-form'
import ToDoTable from './to-do-table'
const { Header, Content } = Layout
function Home() {
const [todos, setTodos] = useState([])
const auth = useAuth()
const access_token = auth.user.access_token
useEffect(() => {
handleToDos()
}, [])
const handleToDos = async () => {
try {
const response = await myToDoListApi.getToDos(access_token)
setTodos(response.data)
} catch (error) {
handleLogError(error)
}
}
const onFinish = async (addToDoRequest) => {
try {
await myToDoListApi.addToDo(addToDoRequest, access_token)
await handleToDos()
} catch (error) {
handleLogError(error)
}
}
const onComplete = async (key) => {
try {
await myToDoListApi.updateToDo(key, true, access_token)
await handleToDos()
} catch (error) {
handleLogError(error)
}
}
const onDelete = async (key) => {
try {
await myToDoListApi.deleteToDo(key, access_token)
await handleToDos()
} catch (error) {
handleLogError(error)
}
}
const handleLogError = (error) => {
if (error.response) {
console.log(error.response.data)
} else if (error.request) {
console.log(error.request)
} else {
console.log(error.message)
}
}
const headerStyle = {
textAlign: 'center',
color: '#fff',
backgroundColor: '#333',
fontSize: '3em'
}
return (
<Layout>
<Header style={headerStyle}>MyToDoList</Header>
<AuthBar />
<Content>
<Row justify="space-evenly">
<Col span={6}>
<ToDoForm
onFinish={onFinish}
/>
</Col>
<Col span={17}>
<ToDoTable
todos={todos}
onComplete={onComplete}
onDelete={onDelete}
/>
</Col>
</Row>
</Content>
</Layout>
)
}
export default Home

View File

@ -0,0 +1,39 @@
import React from 'react'
import { useAuth } from "react-oidc-context"
import { Spin, Typography } from 'antd'
const { Title } = Typography
function PrivateRoute({ children }) {
const auth = useAuth()
const textAlignStyle = { textAlign: "center" }
const subTitleStyle = { color: 'grey' }
if (auth.isLoading) {
return (
<div style={textAlignStyle}>
<Title>Keycloak is loading</Title>
<Title level={2} style={subTitleStyle}>or running authorization code flow with PKCE</Title>
<Spin size="large"></Spin>
</div>
)
}
if (auth.error) {
return (
<div style={textAlignStyle}>
<Title>Oops ...</Title>
<Title level={2} style={subTitleStyle}>{auth.error.message}</Title>
</div>
)
}
if (!auth.isAuthenticated) {
auth.signinRedirect()
return null
}
return children
}
export default PrivateRoute

View File

@ -0,0 +1,36 @@
import React from 'react'
import { Typography, Form, Input, Button } from 'antd'
const { Title } = Typography
function ToDoForm({ onFinish }) {
return (
<>
<Title level={3}>Add ToDo</Title>
<Form
name="basic"
autoComplete="off"
onFinish={onFinish}
>
<Form.Item
label="Description"
name="description"
rules={[{ required: true, message: 'Please write the description!' }]}
>
<Input />
</Form.Item>
<Form.Item>
<Button
type="primary"
shape="round"
htmlType="submit"
>
Submit
</Button>
</Form.Item>
</Form>
</>
)
}
export default ToDoForm

View File

@ -0,0 +1,38 @@
import axios from 'axios'
export const myToDoListApi = {
getToDos,
addToDo,
deleteToDo,
updateToDo
}
function getToDos(access_token) {
return instance.get('/api/todos', {
headers: { 'Authorization': `Bearer ${access_token}` }
})
}
function addToDo(addToDoRequest, access_token) {
return instance.post('/api/todos', addToDoRequest, {
headers: { 'Content-type': 'application/json', 'Authorization': `Bearer ${access_token}` }
})
}
function deleteToDo(id, access_token) {
return instance.delete(`/api/todos/${id}`, {
headers: { 'Authorization': `Bearer ${access_token}` }
})
}
function updateToDo(id, completed, access_token) {
return instance.patch(`/api/todos/${id}?completed=${completed}`, {}, {
headers: { 'Authorization': `Bearer ${access_token}` }
})
}
// -- Axios
const instance = axios.create({
baseURL: 'http://localhost:8080'
})

View File

@ -0,0 +1,72 @@
import React from 'react'
import { Typography, Button, Table, Tag } from 'antd'
import { CheckOutlined, DeleteOutlined } from '@ant-design/icons'
const { Title } = Typography
function ToDoTable({ todos, onComplete, onDelete }) {
const columns = [
{
title: 'Description',
dataIndex: 'description',
key: 'description',
},
{
title: 'Completed',
dataIndex: 'completed',
key: 'completed',
align: 'center',
},
{
title: 'Complete',
dataIndex: '',
key: 'v',
align: 'center',
render: (text, record) => (
<Button
icon={<CheckOutlined />}
type='primary'
shape="circle"
onClick={(e) => { onComplete(record.key, e) }}
>
</Button>
),
},
{
title: 'Delete',
dataIndex: '',
key: 'x',
align: 'center',
render: (text, record) => (
<Button
icon={<DeleteOutlined />}
type='primary'
shape="circle"
onClick={(e) => { onDelete(record.key, e) }}
danger
>
</Button>
),
},
]
const dataSource = todos.map(todo => {
return {
key: todo.id,
description: todo.description,
completed: todo.completed ?
<Tag color="green">true</Tag> : <Tag color="red">false</Tag>
}
})
return (
<>
<Title level={3}>ToDo Table</Title>
<Table
dataSource={dataSource}
columns={columns}
/>
</>
)
}
export default ToDoTable

View File

@ -0,0 +1,39 @@
import React from 'react';
import ReactDOM from 'react-dom';
import { AuthProvider } from "react-oidc-context";
import App from './app';
//TODO remove debugging
if (process.env.NODE_ENV !== 'production') {
console.log('development mode');
}
//since react 18
import { createRoot } from 'react-dom/client';
//create root container
const root = createRoot(document.getElementById("root"));
//open id connect config
const oidcConfig = {
authority: "https://kc.swingbe.de/realms/Ivan-Franchin",
client_id: "my-todo-list",
redirect_uri: "http://localhost:8080",
onSigninCallback: () => {
window.history.replaceState(
{},
document.title,
window.location.pathname
)
}
}
//render root app
root.render(
<AuthProvider {...oidcConfig}>
<React.StrictMode>
<App />
</React.StrictMode>
</AuthProvider>
);

View File

@ -0,0 +1,14 @@
import React from 'react';
import Hello from '../components/hello';
const Home = () => {
return (
<>
<h2>Home</h2>
<h3>(React.js Lambda Function Component)</h3>
<Hello msg="Hello World!" />
</>
);
}
export default Home

View File

@ -0,0 +1,41 @@
//generate a HTML5 file including all webpack bundles in the body using script tags
const HtmlWebpackPlugin = require('html-webpack-plugin');
//path is used to resolve properly across the OS
const path = require('path');
module.exports = {
//bundle *.js from this entry point
entry: path.resolve(__dirname, '../app/index.jsx'),
//create output file to be linked to index.html
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, '../dist'),
clean: true,
},
module: {
rules: [
{
//test all *.js using babel-loader
//test all *.jsx (e.g. React.js) using babel-loader
test: /\.(js|jsx)$/,
exclude: /node_modules/,
include: path.resolve(__dirname, '../app'),
use: ['babel-loader'],
},
{
//test all *.css using style-loader and css-loader
test: /\.css$/i,
use: ["style-loader", "css-loader"],
},
]
},
resolve: {
extensions: ['*', '.js', '.jsx'],
},
plugins: [
// create a plugin instance so that you can use it several times anywhere
new HtmlWebpackPlugin({
title: 'Production',
template: path.resolve(__dirname, "../public/index.html")
}),
],
};

View File

@ -0,0 +1,16 @@
//path is used to resolve properly across the OS
const path = require('path');
const { merge } = require('webpack-merge');
const common = require('./webpack.common.js');
//merge() calls in the environment-specific configuration to include commons
module.exports = merge(common, {
//set development mode
mode: 'development',
//enable strong source mapping
devtool: 'inline-source-map',
devServer: {
static: path.resolve(__dirname, '../dist'),
//When using the HTML5 History API, the index.html page will likely have to be served in place of any 404 responses. Enable devServer.historyApiFallback by setting it to true.
historyApiFallback: true,
},
});

View File

@ -0,0 +1,8 @@
const { merge } = require('webpack-merge');
const common = require('./webpack.common.js');
module.exports = merge(common, {
mode: 'production',
//source maps encouraged in production
//choose mapping with fairly quick build speed like source-map
devtool: 'source-map',
});

12565
my-todo-list-ui/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,39 @@
{
"private": true,
"name": "react-example",
"description": "React.js example",
"version": "0.1.0",
"main": "index.js",
"keywords": [
"react",
"webpack"
],
"author": "Software Ingenieur Begerad <dialog@SwIngBe.de>",
"license": "GPL-3.0-or-later",
"scripts": {
"start": "webpack serve --config config/webpack.dev.js",
"build": "webpack --config config/webpack.prod.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"devDependencies": {
"@babel/core": "7.22.10",
"@babel/preset-env": "7.22.10",
"@babel/preset-react": "7.22.5",
"babel-loader": "9.1.3",
"html-webpack-plugin": "5.5.3",
"webpack": "5.88.2",
"webpack-cli": "5.1.4",
"webpack-dev-server": "4.15.1",
"webpack-merge": "5.9.0"
},
"dependencies": {
"antd": "5.8.3",
"axios": "1.4.0",
"oidc-client-ts": "2.2.4",
"prop-types": "15.8.1",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-oidc-context": "2.2.2",
"react-router-dom": "6.15.0"
}
}

View File

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>title</title>
</head>
<body>
<div id="root"></div>
</body>
</html>

15
my-todo-list-ui/readme.md Normal file
View File

@ -0,0 +1,15 @@
# React.js Example
## Table of Contents
0. [General](#general)
1. [Links](#links)
# General
# Links
* [React setup with webpack for beginners](https://dev.to/deepanjangh/react-setup-with-webpack-for-beginners-2a8k)
* [Production](https://webpack.js.org/guides/production/)
* [Setup Development and Production Environment for React App](https://medium.com/freestoneinfotech/setup-development-and-production-environment-for-react-app-397c4cc9e382)
* [HtmlWebpackPlugin](https://webpack.js.org/plugins/html-webpack-plugin/)
* [Using Keycloak to secure React](https://medium.com/p/6b2d80fc5c12)