[ ADD ] react configuration

This commit is contained in:
Kuroi488
2020-11-16 17:14:34 +01:00
parent 89c9cfe099
commit 5078a1a96e
71 changed files with 16891 additions and 0 deletions

39
react/src/Theme.js Normal file
View File

@ -0,0 +1,39 @@
import React, { useState, useEffect } from "react";
import { createMuiTheme } from "@material-ui/core/styles";
import { ThemeProvider } from "@material-ui/styles";
import rtl from "jss-rtl";
import { create } from "jss";
import { StylesProvider, jssPreset } from "@material-ui/styles";
import { useSelector } from "react-redux";
import App from "./containers/App";
function ThemeApp() {
const jss = create({ plugins: [...jssPreset().plugins, rtl()] });
const lang = useSelector(state => state.lang);
const [direction, setDirection] = useState(lang === "en" ? "ltr" : "rtl");
useEffect(() => {
setDirection(lang === "en" ? "ltr" : "rtl");
}, [lang]);
const theme = createMuiTheme({
direction: direction,
palette: {
primary: {
main: "#1976d2"
},
secondary: {
main: "#ac4556"
}
}
});
return (
<StylesProvider jss={jss}>
<ThemeProvider theme={theme}>
<App />
</ThemeProvider>
</StylesProvider>
);
}
export default ThemeApp;

View File

@ -0,0 +1,13 @@
export default {
ar: {
hello: "مرحبا",
langBtn : "English",
home: {
content:
'لوريم إيبسوم(Lorem Ipsum) هو ببساطة نص شكلي (بمعنى أن الغاية هي الشكل وليس المحتوى) ويُستخدم في صناعات المطابع ودور النشر. كان لوريم إيبسوم ولايزال المعيار للنص الشكلي منذ القرن الخامس عشر عندما قامت مطبعة مجهولة برص مجموعة من الأحرف بشكل عشوائي أخذتها من نص، لتكوّن كتيّب بمثابة دليل أو مرجع شكلي لهذه الأحرف. خمسة قرون من الزمن لم تقضي على هذا النص، بل انه حتى صار مستخدماً وبشكله الأصلي في الطباعة والتنضيد الإلكتروني. انتشر بشكل كبير في ستينيّات هذا القرن مع إصدار رقائق "ليتراسيت" (Letraset) البلاستيكية تحوي مقاطع من هذا النص، وعاد لينتشر مرة أخرى مؤخراَ مع ظهور برامج النشر الإلكتروني مثل "ألدوس بايج مايكر" (Aldus PageMaker) والتي حوت أيضاً على نسخ من نص لوريم إيبسوم.'
},
snackbar: {
'success' : 'تم بنجاح'
}
}
};

View File

@ -0,0 +1,13 @@
export default {
en: {
hello : 'Hello',
langBtn : "عربى",
home: {
content:
"What is Lorem Ipsum?Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
},
snackbar: {
'success' : 'Done successfully'
}
}
}

View File

@ -0,0 +1,9 @@
import en from './en';
import ar from './ar';
const messages = {
...ar,
...en
}
export default messages;

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 134 KiB

View File

@ -0,0 +1,10 @@
import React from "react";
import Button from '@material-ui/core/Button';
export const Btn = ({text , handleClick}) => {
return (
<Button variant="contained" color="primary" onClick={handleClick}>
{text}
</Button>
);
};

View File

@ -0,0 +1,32 @@
import React from "react";
import { TextField } from "@material-ui/core";
export const InputField = ({
name,
label,
value,
error,
handleChange,
helperText,
isMultiline,
isRequired
}) => {
return (
<TextField
className="my-3"
name={name}
type="text"
label={isRequired ? label+"*" : label}
inputProps={{ maxLength: isMultiline ? 500 : 50 }}
variant="outlined"
fullWidth
value={value}
error={error}
helperText={error && helperText}
onChange={handleChange}
multiline={isMultiline}
rows={isMultiline ? 3 : 1}
/>
);
};

View File

@ -0,0 +1,14 @@
import React from "react";
import "./Loader.scss";
const Loader = () => {
return (
<div className="spinnerContainer d-flex justify-content-center align-items-center h-100">
<div className="spinner-border text-primary" role="status">
<span className="sr-only">Loading...</span>
</div>
</div>
);
};
export default Loader;

View File

@ -0,0 +1,31 @@
.spinnerContainer {
height: 100vh;
width: 100%;
}
.loading-indicator:before {
content: "";
background: #000000cc;
position: fixed;
width: 100%;
height: 100%;
top: 0;
left: 0;
z-index: 1000;
}
.loading-indicator:after {
content: "\f1ce";
font-family: FontAwesome;
position: fixed;
width: 100%;
top: 50%;
left: 0;
z-index: 1001;
color: white;
text-align: center;
font-weight: 100;
font-size: 4rem;
-webkit-animation: fa-spin 1s infinite linear;
animation: fa-spin 1s infinite linear;
}

View File

@ -0,0 +1,33 @@
import React from "react";
import messages from "./../../assets/Local/messages";
import { useSelector, useDispatch } from "react-redux";
import { setCurrentLang } from "../../store/Lang/LangAction";
import { Link } from "react-router-dom";
import { Btn } from "../Controls/Button/Button";
export default function Navbar() {
const lang = useSelector(state => state.lang);
const dispatch = useDispatch();
const message = messages[lang];
const switchLanguage = lang => {
dispatch(setCurrentLang(lang === "ar" ? "en" : "ar"));
};
return (
<>
<nav className="navbar navbar-dark bg-dark">
<a className="navbar-brand">{message.hello}</a>
<div className="d-flex align-items-center">
{/* This private route won't be accessible if no token in lcoal storage */}
<Link to="/" className="text-white mx-3">
Private Route
</Link>
<Btn
handleClick={() => switchLanguage(lang)}
text={message.langBtn}
/>
</div>
</nav>
</>
);
}

View File

@ -0,0 +1,12 @@
import React from "react";
const NotFound = () => {
return (
<React.Fragment>
<div className="text-center">
<h1 className="my-5 pt-5">Sorry we cant find this page</h1>
</div>
</React.Fragment>
);
};
export default NotFound;

View File

@ -0,0 +1,33 @@
import React from "react";
import Snackbar from "@material-ui/core/Snackbar";
import MuiAlert from "@material-ui/lab/Alert";
import { useSelector, useDispatch } from "react-redux";
import { hideSnackbarAction } from "../../store/Snackbar/SnackbarAction";
function Alert(props) {
return <MuiAlert elevation={6} variant="filled" {...props} />;
}
export function MaterialSnackbar(props) {
const { isOpen, message, type } = useSelector(state => state.snackbar);
const dispatch = useDispatch();
const handleClose = (event, reason) => {
if (reason === "clickaway") {
return;
}
dispatch(hideSnackbarAction());
};
return (
<Snackbar
open={isOpen}
autoHideDuration={4000}
anchorOrigin={{ vertical: "bottom", horizontal: "center" }}
key={`bottom,center`}
onClose={() => handleClose}
>
<Alert onClose={handleClose} severity={type} className="medium_font">
{message}
</Alert>
</Snackbar>
);
}

View File

@ -0,0 +1,40 @@
import React from "react";
import Navbar from "../components/Navbar/Navbar";
import { Router } from "react-router-dom";
import history from "../routes/History";
import Routes from "../routes/Routes";
import { IntlProvider } from "react-intl";
import messages from "../assets/Local/messages";
import { MaterialSnackbar } from "../components/Snackbar/Snackbar";
import Loader from "../components/Loader/Loader";
import "./App.scss";
import { connect } from "react-redux";
class App extends React.Component {
// App contains routes and also wrapped with snackbar and intl for localization
render() {
const { lang , loading } = this.props;
return (
<IntlProvider locale={lang} messages={messages[lang]}>
<div
className={lang === "ar" ? "rtl" : "ltr"}
dir={lang === "ar" ? "rtl" : "ltr"}
>
{loading ? <Loader /> : null}
<Router history={history}>
<MaterialSnackbar />
<Navbar />
{Routes}
</Router>
</div>
</IntlProvider>
);
}
}
const mapStateToProps = ({ lang, loading }) => ({
lang,
loading
});
export default connect(mapStateToProps, null)(App);

View File

@ -0,0 +1 @@
@import '../scss/base.scss';

View File

@ -0,0 +1,23 @@
import React from 'react';
import messages from "./../../assets/Local/messages";
import { connect } from 'react-redux';
class Home extends React.Component {
render(){
const { lang } = this.props;
const message = messages[lang]
return(
<div className="container my-5">
<p>{message.home.content}</p>
</div>
)
}
}
const mapStateToProps = (state) => {
return {
lang : state.lang
}
}
export default connect(mapStateToProps,null)(Home);

View File

@ -0,0 +1,23 @@
import React from 'react';
import {Btn} from '../../components/Controls/Button/Button';
import History from '../../routes/History';
class Login extends React.Component {
// this method is only to trigger route guards , remove and use your own logic
handleLogin = () => {
localStorage.setItem('token','token');
History.push('/')
}
render(){
return(
<div className="container my-5">
<h1>Login Page</h1>
<Btn text='Login' handleClick={this.handleLogin}/>
</div>
)
}
}
export default Login;

12
react/src/index.js Normal file
View File

@ -0,0 +1,12 @@
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import store from "./store";
import ThemeApp from "./Theme";
ReactDOM.render(
<Provider store={store}>
<ThemeApp />
</Provider>,
document.querySelector('#root')
);

View File

@ -0,0 +1,19 @@
import axios from "axios";
import { requestHandler, successHandler, errorHandler } from "../interceptors";
import { BASE_URL } from "../../utils/Constants";
//add your BASE_URL to Constants file
export const axiosInstance = axios.create({
baseURL: BASE_URL,
headers: {
"Content-Type": "application/json"
}
});
// Handle request process
axiosInstance.interceptors.request.use(request => requestHandler(request));
// Handle response process
axiosInstance.interceptors.response.use(
response => successHandler(response),
error => errorHandler(error)
);

View File

@ -0,0 +1,35 @@
import store from "../../store";
import { loader } from "../../store/Loader/LoaderAction";
import Auth from "../../utils/Auth";
export const isHandlerEnabled = (config = {}) => {
return config.hasOwnProperty("handlerEnabled") && !config.handlerEnabled
? false
: true;
};
export const requestHandler = request => {
if (isHandlerEnabled(request)) {
// Modify request here
store.dispatch(loader(true));
}
return request;
};
export const successHandler = response => {
if (isHandlerEnabled(response)) {
// Hanlde Response
store.dispatch(loader(false));
}
return response;
};
export const errorHandler = error => {
if (isHandlerEnabled(error.config)) {
store.dispatch(loader(false));
// You can decide what you need to do to handle errors.
// here's example for unautherized user to log them out .
// error.response.status === 401 && Auth.signOut();
}
return Promise.reject({ ...error });
};

View File

@ -0,0 +1,2 @@
import { createBrowserHistory } from "history";
export default createBrowserHistory();

View File

@ -0,0 +1,22 @@
import React, { Suspense } from "react";
import { Router, Switch } from "react-router-dom";
import history from "./History";
import * as LazyComponent from "../utils/LazyLoaded";
import Loader from "../components/Loader/Loader";
import PrivateRoute from "../utils/PrivateRoute";
const Routes = (
<Suspense fallback={<Loader />}>
<Router history={history}>
<Switch>
{/* For private routes */}
<PrivateRoute component={LazyComponent.Home} path="/" exact />
{/* Public routes that doesn't need any auth */}
<LazyComponent.Login path="/login" exact />
<LazyComponent.NotFound path="**" title="This page doesn't exist..." exact />
</Switch>
</Router>
</Suspense>
);
export default Routes;

View File

@ -0,0 +1 @@
// Add you general and shared styles here

4
react/src/scss/_rtl.scss Normal file
View File

@ -0,0 +1,4 @@
.rtl{
font-family: Arial, Helvetica, sans-serif;
text-align: right;
}

View File

@ -0,0 +1,2 @@
$primaryColor: rgb(50, 61, 165);
$secondaryColor : rgba(62, 62, 62, 1);

4
react/src/scss/base.scss Normal file
View File

@ -0,0 +1,4 @@
@import 'bootstrap/scss/bootstrap';
@import './variables';
@import './rtl';
@import './general';

View File

@ -0,0 +1,11 @@
import * as types from "./FeatureTypes";
//Replace action name and update action types
export const actionRequest = () => ({
type: types.GET_DATA_REQUEST
});
export const actionReceive = payload => ({
type: types.GET_DATA_REQUEST,
payload
});

View File

@ -0,0 +1,11 @@
import {axiosInstance} from '../../network/apis';
const handlerEnabled = false;
// Replace endpoint and change api name
const apiExampleRequest = async () => {
return await axiosInstance.get(`ENDPOINT`, { handlerEnabled });
};
export default {
apiExampleRequest
};

View File

@ -0,0 +1,16 @@
import * as types from "./FeatureTypes";
const INITIAL_STATE = {};
// Replace with you own reducer
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case types.GET_DATA_RECEIVE:
return {
...state,
...action.payload
};
default:
return state;
}
};

View File

@ -0,0 +1,21 @@
import { call, put } from "redux-saga/effects";
import API from "./FeatureApis";
import * as ACTIONS from "./FeatureAction";
import { dispatchSnackbarError } from "../../utils/Shared";
import { takeLatest } from "redux-saga/effects";
import * as TYPES from "./FeatureTypes";
// Replace with your sagas
export function* sagasRequestExample() {
try {
const response = yield call(API.apiExampleRequest);
yield put(ACTIONS.actionReceive(response.data));
} catch (err) {
dispatchSnackbarError(err.response.data);
}
}
export function* FeatureSaga1() {
yield takeLatest(TYPES.GET_DATA_REQUEST, sagasRequestExample);
}

View File

@ -0,0 +1,3 @@
// Replace with your request types
export const GET_DATA_REQUEST = 'GET_DATA_REQUEST';
export const GET_DATA_RECEIVE = 'GET_DATA_RECEIVE';

View File

@ -0,0 +1,10 @@
import * as types from './LangTypes';
export const setCurrentLang = payload => {
localStorage.setItem('lang', payload);
return { type: types.SET_LANG, payload };
}
export const getCurrentLang = () => {
return { type: types.GET_LANG };
};

View File

@ -0,0 +1,14 @@
import * as types from "./LangTypes";
const INITIAL_STATE = localStorage.getItem("lang") || "en";
export default function locale(state = INITIAL_STATE, action) {
switch (action.type) {
case types.SET_LANG:
return action.payload;
case types.GET_LANG:
return action.payload;
default:
return state;
}
}

View File

@ -0,0 +1,2 @@
export const SET_LANG = 'SET_LANG';
export const GET_LANG = 'GET_LANG';

View File

@ -0,0 +1,13 @@
import * as types from "./LoaderTypes";
export const loader = isLoading => {
return isLoading
? {
type: types.SHOW_LOADER,
data: isLoading
}
: {
type: types.HIDE_LOADER,
data: isLoading
};
};

View File

@ -0,0 +1,14 @@
import * as types from "./LoaderTypes";
const INITIAL_STATE = false;
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case types.SHOW_LOADER:
return action.data;
case types.HIDE_LOADER:
return action.data;
default:
return state;
}
};

View File

@ -0,0 +1,2 @@
export const SHOW_LOADER = 'SHOW_LOADER';
export const HIDE_LOADER = 'HIDE_LOADER';

View File

@ -0,0 +1,15 @@
import * as types from './SnackbarTypes';
export const showSnackbarAction = (message , snacknarType) => {
return {
type: types.SHOW_SNACKBAR,
message ,
snacknarType
};
};
export const hideSnackbarAction = () => {
return {
type: types.HIDE_SNACKBAR
};
};

View File

@ -0,0 +1,21 @@
import * as types from "./SnackbarTypes";
export default (state = {}, action) => {
switch (action.type) {
case types.SHOW_SNACKBAR:
return {
...state,
isOpen: true,
message: action.message,
type: action.snacknarType
};
case types.HIDE_SNACKBAR:
return {
...state,
isOpen: false
};
default:
return state;
}
};

View File

@ -0,0 +1,2 @@
export const SHOW_SNACKBAR = 'SHOW_SNACKBAR';
export const HIDE_SNACKBAR = 'HIDE_SNACKBAR';

17
react/src/store/index.js Normal file
View File

@ -0,0 +1,17 @@
import { createStore, applyMiddleware, compose } from "redux";
import reducers from "./reducers";
import createSagaMiddleware from "redux-saga";
import { watchSagas } from "./sagas";
const saga = createSagaMiddleware();
//redux dev tool
const composeEnhancers =
typeof window === "object" && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({})
: compose;
const enhancer = composeEnhancers(applyMiddleware(saga));
const store = createStore(reducers, enhancer);
saga.run(watchSagas);
export default store;

View File

@ -0,0 +1,12 @@
import { combineReducers } from "redux";
import lang from "../Lang/LangReducer";
import loader from "../Loader/LoaderReducer";
import snackbar from "../Snackbar/SnackbarReducer";
import Feature1 from "../Feature1/FeatureReducer";
export default combineReducers({
lang,
loader,
snackbar,
Feature1
});

View File

@ -0,0 +1,9 @@
import { FeatureSaga1 } from '../Feature1/FeatureSagas';
import { fork, all } from "redux-saga/effects";
export function* watchSagas() {
//Combine sagas with
yield all([FeatureSaga1()]);
// OR
// yield all([fork(FeatureSaga1)]);
}

10
react/src/utils/Auth.js Normal file
View File

@ -0,0 +1,10 @@
// Service to check authentication for user and to signOut
const Auth = {
signOut() {
localStorage.removeItem("token");
},
isAuth() {
return localStorage.getItem("token");
}
};
export default Auth;

View File

@ -0,0 +1 @@
export const BASE_URL = 'BASE_URL';

View File

@ -0,0 +1,5 @@
import React from "react";
export const Home = React.lazy(() => import('../containers/Home/Home'));
export const Login = React.lazy(() => import('../containers/Login/Login'));
export const NotFound = React.lazy(() => import('../components/NotFound/NotFound'));

View File

@ -0,0 +1,18 @@
import React from "react";
import { Route, Redirect } from "react-router-dom";
import Auth from "../utils/Auth";
const PrivateRoute = ({ component: Component, ...rest }) => {
return (
// Show the component only when the user is logged in
// Otherwise, redirect the user to /signin page
<Route
{...rest}
render={props =>
Auth.isAuth() ? <Component {...props} /> : <Redirect to="/login" />
}
/>
);
};
export default PrivateRoute;

18
react/src/utils/Shared.js Normal file
View File

@ -0,0 +1,18 @@
import store from "../store";
import { showSnackbarAction } from "../store/Snackbar/SnackbarAction";
import messages from "../assets/Local/messages";
// To show error message that returned from backend
export function dispatchSnackbarError(data) {
if (data) {
const errorMsg = data.error.message;
store.dispatch(showSnackbarAction(errorMsg, "error"));
}
}
// To show success message after any success request if needed and rendered from locale files
export function dispatchSnackbarSuccess(message) {
const lang = store.getState().lang;
store.dispatch(
showSnackbarAction(messages[lang].snackbar[message], "success")
);
}