Skip to content

Instantly share code, notes, and snippets.

@ac205
Created March 23, 2020 16:02
Show Gist options
  • Save ac205/27c948c7053b219f6c12c5205dd3524e to your computer and use it in GitHub Desktop.
Save ac205/27c948c7053b219f6c12c5205dd3524e to your computer and use it in GitHub Desktop.
Google Auth
import React, { useState, useEffect, Fragment } from 'react';
import './App.css';
import Topbar from './components/Topbar';
import Sidebar from './components/Sidebar';
import MainWindow from './components/MainWindow';
import BottomBar from './components/Bottombar';
import Messages from './components/Messages';
import Timer from './components/Timer';
import History from './components/History';
import EditExercise from './components/EditExercise';
import AddExercise from './components/AddExercise';
import ConfirmDelete from './components/ConfirmDelete';
import StyledFirebaseAuth from 'react-firebaseui/StyledFirebaseAuth';
import FitnessCenterIcon from '@material-ui/icons/FitnessCenter';
import Typography from '@material-ui/core/Typography';
import firebase from 'firebase/app';
import 'firebase/database';
import 'firebase/auth';
//dotenv initialization
const ENV = require('dotenv');
ENV.config();
//firebase initialization
const config = {
apiKey: process.env.REACT_APP_API_KEY,
authDomain: process.env.REACT_APP_AUTH_DOMAIN,
databaseURL: process.env.REACT_APP_DATABASE_URL,
projectId: process.env.REACT_APP_PROJECT_ID,
storageBucket: process.env.REACT_APP_STORAGEBUCKET,
messagingSenderId: process.env.REACT_APP_MESSAGING_SENDER_ID,
appId: process.env.REACT_APP_APP_ID
};
firebase.initializeApp(config);
//firebase load todays workout activity
let todayDate = new Date().toLocaleDateString('en-US').toString().replace(/\//g, '-');
let workoutref = 'workouts/' + todayDate;
const exerciseDB = firebase.database();
let ref = exerciseDB.ref(workoutref);
const exref = exerciseDB.ref('exercises/');
let currentData = [];
//Beginning of App
function App() {
const [todayComplete, setTodayComplete] = useState([]);
const [exerciseList, setExerciseList] = useState([]);
const [user, setUser] = useState();
const uiConfig = {
// Popup signin flow rather than redirect flow.
signInFlow: 'popup',
// Redirect to /signedIn after sign in is successful. Alternatively you can provide a callbacks.signInSuccess function.
// We will display Google and Facebook as auth providers.
signInOptions: [firebase.auth.GoogleAuthProvider.PROVIDER_ID],
callbacks: {
signInSuccessWithAuthResult: () => false
}
};
useEffect(() => {
firebase.auth().onAuthStateChanged(user => {
if (user) {
const handleHistory = (e) => {
setHistory(false);
let date = new Date(e)
.toLocaleDateString('en-US', { year: 'numeric', month: 'numeric', day: 'numeric' })
.replace(/\//g, '-');
setHistoryDate(date.replace(/-/g, '/'));
setDisplayDate(e);
todayDate = date;
workoutref = 'workouts/' + user.uid + '/' + date;
const ref = exerciseDB.ref(workoutref);
const gotData = (data) => {
currentData = data.val();
currentData === null ? setTodayComplete([]) : setTodayComplete(currentData);
};
const errData = (error) => {
console.log('Error!', error);
};
if (user !== null && user !== undefined) {
ref.on('value', gotData, errData);
}
};
setUser(user);
handleHistory(new Date());
setMsgGood(true);
setMessage('Welcome Back ' + user.displayName);
setPopMessage(true);
}
});
}, []);
//Component Mounted Run Once - Firebase Load Data if OK set Sidebar Date and Load todays workout activity to "todayComplete"
useEffect(() => {
const gotData = (data) => {
currentData = data.val();
currentData === null ? setExerciseList([]) : setExerciseList(currentData);
};
const errData = (error) => {
console.log('Error!', error);
};
exref.on('value', gotData, errData);
}, []);
//Delcare all states
const [menuOpen, setMenuOpen] = useState(false);
const [currentExercise, setCurrentExercise] = useState();
const [isActive, setIsActive] = useState(false);
const [muscle, setMuscle] = useState('ALL');
const [edit, setEdit] = useState();
const [editID, setEditID] = useState();
const [editExercise, setEditExercise] = useState({ weight: 0, reps: 0, mins: 0 });
const [confirm, setConfirm] = useState(false);
const [tempList, setTempList] = useState();
const [historyDate, setHistoryDate] = useState();
const [displayDate, setDisplayDate] = useState();
const [add, setAdd] = useState(false);
const [weight, setWeight] = useState(0);
const [mins, setMins] = useState(0);
const [cardio, setCardio] = useState(false);
const [reps, setReps] = useState(0);
const [bodyWeight, setBodyWeight] = useState(false);
const [history, setHistory] = useState();
const [message, setMessage] = useState('');
const [msgGood, setMsgGood] = useState(true);
const [timer, setTimer] = useState(false);
const [seconds, setSeconds] = useState(60);
const [popMessage, setPopMessage] = useState(false);
const timerSound = new Audio('./timer.ogg');
//Sidebar Handlers
const [drawerSide, setDrawerSide] = useState({
left: false
});
const toggleDrawer = (side, open) => (event) => {
if (event && event.type === 'keydown' && (event.key === 'Tab' || event.key === 'Shift')) {
return;
}
setDrawerSide({ ...drawerSide, [side]: open });
};
const handleExercise = (e) => {
const { id } = e.currentTarget;
let newExercise = exerciseList[id];
if (exerciseList[id].type === 'cardio') {
setCardio(true);
setWeight(null);
setReps(null);
setMins(0);
setBodyWeight(true);
setCurrentExercise(newExercise);
} else if (exerciseList[id].bodyWeight === true) {
setWeight(null);
setMins(null);
setCardio(false);
setBodyWeight(true);
setReps(0);
setCurrentExercise(newExercise);
} else {
setBodyWeight(false);
setCardio(false);
setMins(null);
setWeight(0);
setReps(0);
setCurrentExercise(newExercise);
}
};
//Add New Exercise to Exercise List
const handleAddOpen = () => {
setAdd(true);
};
const handleAddClose = () => {
setAdd(false);
};
const handleAddExercise = () => {
setAdd(false);
};
//Add Exercise to Completed List Handlers
const handleConfirmedAdd = (itemID) => {
setTodayComplete([
...todayComplete,
{
id: itemID + 54 * Math.random(),
name: currentExercise.name,
reps: reps,
weight: weight,
mins: mins,
date: todayDate
}
]);
if (mins >= 1) {
return;
} else {
setSeconds(60);
handleTimerOpen();
}
};
const handleAdd = (e) => {
let itemID = Number(e.currentTarget.id);
if (currentExercise.type === 'cardio' && mins === 0) {
setMsgGood(false);
setMessage('Minutes Cannot Equal 0');
setPopMessage(true);
return;
} else if (currentExercise.type !== 'cardio' && currentExercise.bodyWeight === true && reps === 0) {
setMsgGood(false);
setMessage('Reps Cannot Equal 0');
setPopMessage(true);
return;
} else if (currentExercise.bodyWeight === false && reps === 0) {
setMsgGood(false);
setMessage('Reps Cannot Equal 0');
setPopMessage(true);
return;
} else if (currentExercise.bodyWeight === false && weight === 0) {
setMsgGood(false);
setMessage('Weight Cannot Equal 0lbs');
setPopMessage(true);
return;
} else handleConfirmedAdd(itemID);
setReps(0);
setMins(0);
return;
};
//Save Exercises from Completed List Handlers
const handleSave = () => {
if (todayComplete.length <= 0) {
setMsgGood(false);
setMessage('Nothing to Save!');
setPopMessage(true);
return;
}
workoutref = 'workouts/' + user.uid + '/' + todayDate;
ref = exerciseDB.ref(workoutref);
ref.set(todayComplete);
setMsgGood(true);
setMessage('Workout Saved!');
setPopMessage(true);
};
//Delete Exercise from Completed List Handlers
const handleConfirmDeleteClose = () => {
setConfirm(false);
}
const handleConfirm = (e) => {
setConfirm(true);
let itemID = Number(e.currentTarget.id);
let newList = todayComplete.filter((exercise) => exercise.id !== itemID);
setTempList(newList);
}
const handleDelete = (e) => {
setConfirm(false);
setTodayComplete(tempList);
};
//History Handlers
const handleHistoryOpen = (e) => {
setHistory(true);
};
const handleHistoryClose = (e) => {
setHistory(false);
};
const handleHistoryDate = (date) => {
let test = new Date(date.replace(/-/g, '/'));
let month = test.getMonth() + 1;
let day = test.getDate();
let year = test.getFullYear();
let newdate = (year + '/' + month + '/' + day).replace(/\//g, '-');
setHistoryDate(newdate);
};
const handleHistory = (e) => {
setHistory(false);
let date = new Date(e)
.toLocaleDateString('en-US', { year: 'numeric', month: 'numeric', day: 'numeric' })
.replace(/\//g, '-');
setHistoryDate(date.replace(/-/g, '/'));
setDisplayDate(e);
todayDate = date;
const workoutref = 'workouts/' + user.uid + '/' + date;
const ref = exerciseDB.ref(workoutref);
const gotData = (data) => {
currentData = data.val();
currentData === null ? setTodayComplete([]) : setTodayComplete(currentData);
};
const errData = (error) => {
console.log('Error!', error);
};
ref.on('value', gotData, errData);
};
//Edit Handlers
const handleEditOpen = (e) => {
setEditID(e.currentTarget.id);
todayComplete.map((exercise) => {
if (exercise.id === Number(e.currentTarget.id)) {
setEditExercise({
weight: exercise.weight,
reps: exercise.reps,
mins: exercise.mins
});
}
return exercise;
});
setEdit(true);
};
const handleEditClose = () => {
setEdit(false);
};
const handleEditUpdate = () => {
todayComplete.map((exercise) => {
let num = Number(editID);
if (exercise.id === num) {
if (exercise.weight === null && exercise.mins === null) {
let reps = document.getElementById('editReps').value;
exercise.reps = reps;
} else {
if (!exercise.reps !== undefined && exercise.mins > 0) {
let mins = document.getElementById('editMins').value;
exercise.mins = mins
}
else if (exercise.weight !== undefined && exercise.weight > 0) {
let reps = document.getElementById('editReps').value;
let weight = document.getElementById('editWeight').value;
exercise.weight = weight;
exercise.reps = reps;
} else {
let reps = document.getElementById('editReps').value;
exercise.reps = reps;
}
// exercise.reps = reps;
// exercise.weight = weight;
// exercise.mins = mins;
}
}
return exercise;
});
setEdit(false);
};
//Timer Handlers
const handleTimeUp = () => {
timerSound.loop = false;
timerSound.play();
};
const handleTimerOpen = () => {
setTimer(true);
setIsActive(true);
};
const handleTimerClose = (value) => {
setTimer(false);
};
//Rendering of App
return (
<div className="App">
{user === null || user === undefined ? <div className="loginScreen">
<Typography variant="h3" gutterBottom><FitnessCenterIcon fontSize="large" />Workout Tracker</Typography>
<Typography variant="h5" gutterBottom>v 1.0</Typography>
<StyledFirebaseAuth
uiConfig={uiConfig}
firebaseAuth={firebase.auth()}
uiCallback={(ui) => ui.disableAutoSignIn()}
/>
</div> :
<Fragment>
<Topbar
menuOpen={menuOpen}
setMenuOpen={setMenuOpen}
style={{ height: '15vh' }}
toggleDrawer={toggleDrawer}
handleTimerOpen={handleTimerOpen}
handleSave={handleSave}
/>
<Timer
timer={timer}
setTimer={setTimer}
handleTimerOpen={handleTimerOpen}
handleTimerClose={handleTimerClose}
isActive={isActive}
setIsActive={setIsActive}
seconds={seconds}
setSeconds={setSeconds}
setPopMessage={setPopMessage}
handleTimeUp={handleTimeUp}
setMessage={setMessage}
setMsgGood={setMsgGood}
/>
<EditExercise
edit={edit}
handleEditClose={handleEditClose}
handleEditUpdate={handleEditUpdate}
editExercise={editExercise}
/>
<AddExercise
add={add}
handleAddClose={handleAddClose}
handleAddExercise={handleAddExercise}
exerciseList={exerciseList}
setPopMessage={setPopMessage}
setMessage={setMessage}
setMsgGood={setMsgGood}
exref={exref}
/>
<ConfirmDelete
confirm={confirm}
handleConfirmDeleteClose={handleConfirmDeleteClose}
handleConfirm={handleConfirm}
handleDelete={handleDelete}
/>
<History
handleHistoryClose={handleHistoryClose}
history={history}
handleHistory={handleHistory}
handleHistoryDate={handleHistoryDate}
displayDate={displayDate}
/>
<Sidebar
exerciseList={exerciseList}
todayDate={todayDate}
drawerSide={drawerSide}
toggleDrawer={toggleDrawer}
handleExercise={handleExercise}
muscle={muscle}
historyDate={historyDate}
handleHistoryOpen={handleHistoryOpen}
handleAddOpen={handleAddOpen}
uiConfig={uiConfig}
user={user}
setUser={setUser}
/>
<MainWindow
currentExercise={currentExercise}
handleAdd={handleAdd}
toggleDrawer={toggleDrawer}
todayComplete={todayComplete}
setTodayComplete={setTodayComplete}
reps={reps}
setReps={setReps}
weight={weight}
setWeight={setWeight}
mins={mins}
setMins={setMins}
cardio={cardio}
handleEditOpen={handleEditOpen}
handleHistory={handleHistory}
handleHistoryOpen={handleHistoryOpen}
handleConfirm={handleConfirm}
bodyWeight={bodyWeight}
/>
<Messages popMessage={popMessage} setPopMessage={setPopMessage} message={message} msgGood={msgGood} />
<BottomBar toggleDrawer={toggleDrawer} muscle={muscle} setMuscle={setMuscle} />
</Fragment>}
</div>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment