Skip to content

Commit

Permalink
Updates to Board Data
Browse files Browse the repository at this point in the history
  • Loading branch information
rakib committed Feb 8, 2025
1 parent ceca2c0 commit fadb052
Show file tree
Hide file tree
Showing 11 changed files with 150 additions and 166 deletions.
12 changes: 6 additions & 6 deletions components/boards/board.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -232,12 +232,12 @@ export default function Board(props) {
});
}

useEffect(() => {
let thisBoard = boards.find(brd => brd.id == board.id);
if (thisBoard) {
setBoard(thisBoard);
}
}, [boards])
// useEffect(() => {
// let thisBoard = boards.find(brd => brd.id == board.id);
// if (thisBoard) {
// setBoard(thisBoard);
// }
// }, [boards])

useEffect(() => {
if (updates > 0) {
Expand Down
50 changes: 28 additions & 22 deletions components/boards/boards.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -104,29 +104,35 @@ export default function Boards({ }) {
setRte(replaceAll(router.route, `/`, `_`));

if (updates > 0) {
let updatedBoards = boards;
let boardsHaveCreator = boards.every(brd => isValid(brd?.creator));

if (user != null) {
if (!boardsHaveCreator) {
updatedBoards = boards.map(brd => ({
...brd,
creator: {
id: user?.id,
uid: user?.uid,
name: user?.name,
email: user?.email,
},
}))
// let singleUpdate = updates % 2 !== 0;
// if (singleUpdate) {
let updatedBoards = boards;

if (user != null) {
let boardsHaveCreator = boards.every(brd => isValid(brd?.creator));
if (!boardsHaveCreator) {
updatedBoards = boards.map(brd => ({
...brd,
creator: {
id: user?.id,
uid: user?.uid,
name: user?.name,
email: user?.email,
},
}))
}
updateUserFields(user?.id, { boards: updatedBoards });
localStorage.setItem(`user`, JSON.stringify({ ...user, boards: updatedBoards }));
} else {
localStorage.setItem(`local_boards`, JSON.stringify(updatedBoards));
}
updateUserFields(user?.id, { boards: updatedBoards });
localStorage.setItem(`user`, JSON.stringify({ ...user, boards: updatedBoards }));
} else {
localStorage.setItem(`local_boards`, JSON.stringify(updatedBoards));
}

localStorage.setItem(`boards`, JSON.stringify(updatedBoards));
dev() && updatedBoards?.length > 0 && console.log(`Updated Boards`, updatedBoards);

localStorage.setItem(`boards`, JSON.stringify(updatedBoards));
// dev() && updatedBoards?.length > 0 && console.log(`Updated Boards`, {
// updates,
// updatedBoards,
// });
// }
}

setUpdates(updates + 1);
Expand Down
9 changes: 4 additions & 5 deletions components/boards/item.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -221,11 +221,10 @@ export default function Item({ item, count, column, itemIndex, board, setBoard }
<div id={`itemElement_${item.id}`} className={`itemComponent itemInnerRow flex row`} onContextMenu={(e) => onRightClick(e, item, column)}>
<span className={`itemOrder rowIndexOrder`}>
<i className={`itemIndex ${item.complete ? `completedIndex` : `activeIndex`}`}>
{(item?.type == ItemTypes.Item) && (
<span className={`itemIconType ${item?.type}`}>
{getTypeIcon(item?.type)}
</span>
)} {itemIndex + 1}
<span className={`itemIconType ${item?.type}`}>
+
</span>
{itemIndex + 1}
</i>
</span>
{item?.image && (
Expand Down
17 changes: 10 additions & 7 deletions components/boards/tasks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ const SortableSubtaskItem = ({ item, subtask, isLast, column, index, changeLabel

export default function Tasks(props) {
let { item, column, board, showForm = true } = props;
let { user, boards, setLoading, setSystemStatus } = useContext<any>(StateContext);
let { user, boards, setBoards, setLoading, setSystemStatus } = useContext<any>(StateContext);

let [deletedTaskIDs, setDeletedTaskIDs] = useState<string[]>([]);
let [subtasks, setSubtasks] = useState(item?.subtasks?.length ? item.subtasks : []);
Expand All @@ -112,12 +112,13 @@ export default function Tasks(props) {
// Capitalize words
const capitalizeAllWords = capWords;

const updateBoards = (user, dynamicScrollbars = false) => {
localStorage.setItem(`boards`, JSON.stringify(boards));
const updateBoards = (user, dynamicScrollbars = false, bords = boards) => {
localStorage.setItem(`boards`, JSON.stringify(bords));
if (dynamicScrollbars) addBoardScrollBars();
if (user != null) {
updateUserFields(user?.id, { boards });
localStorage.setItem(`user`, JSON.stringify({ ...user, boards }));
// setBoards(bords);
updateUserFields(user?.id, { boards: bords });
localStorage.setItem(`user`, JSON.stringify({ ...user, boards: bords }));
}
}

Expand Down Expand Up @@ -194,8 +195,10 @@ export default function Tasks(props) {
setSubtasks(updatedTasks);
item.subtasks = updatedTasks;
item.updated = formatDate(new Date());
board.items[item?.id] = item;
let updatedBoards = boards.map(brd => brd.id == board?.id ? board : brd);

updateBoards(user, true);
updateBoards(user, true, updatedBoards);

// Reset form
e.target.reset();
Expand Down Expand Up @@ -260,7 +263,7 @@ export default function Tasks(props) {

updateBoards(user, true);

dev() && console.log(`Dragged and Reordered`, updated);
// dev() && console.log(`Dragged & Reordered`, updated);
};

return (
Expand Down
2 changes: 1 addition & 1 deletion components/footer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export default function Footer(props) {
</a>
</div>
<div className={`right`}>
Piratechs <i className={`fas fa-copyright`} />2023
Piratechs <i className={`fas fa-copyright`} />{new Date()?.getFullYear()}
</div>
</footer>
)
Expand Down
154 changes: 73 additions & 81 deletions components/form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import { toast } from 'react-toastify';
import { User } from '../shared/models/User';
import { addUserToDatabase, auth, db } from '../firebase';
import { addUserToDatabase, auth } from '../firebase';
import { useContext, useEffect, useRef, useState } from 'react';
import { formatDate, StateContext, showAlert } from '../pages/_app';
import { createUserWithEmailAndPassword, signInWithEmailAndPassword } from 'firebase/auth';
Expand Down Expand Up @@ -45,10 +45,10 @@ export const renderErrorMessage = (erMsg: string) => {
}

export default function Form(props?: any) {
const { id, navForm, className, style } = props;
const loadedRef = useRef(false);
const [loaded, setLoaded] = useState(false);
const { user, setUser, setBoards, updates, setUpdates, setContent, authState, setAuthState, emailField, setEmailField, users, setColor, setDark, useDatabase } = useContext<any>(StateContext);
const { id, navForm, className, style } = props;
const { user, setUser, setBoards, updates, setUpdates, setContent, authState, setAuthState, emailField, setEmailField, users } = useContext<any>(StateContext);

// const changeColor = (colorRangePickerEvent?: any) => {
// let currentColor: any = colorRangePickerEvent.target.value;
Expand Down Expand Up @@ -101,90 +101,82 @@ export default function Form(props?: any) {
}

const onSignIn = (email, password) => {
if (useDatabase == true) {
signInWithEmailAndPassword(auth, email, password).then((userCredential: any) => {
if (userCredential != null) {
let existingUser = users.find(usr => usr?.email?.toLowerCase() == email?.toLowerCase());
if (existingUser != null) {
signInUser(existingUser);
toast.success(`Successfully Signed In`);
} else {
setEmailField(true);
setAuthState(`Sign Up`);
}
}
}).catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
if (errorMessage) {
toast.error(renderErrorMessage(errorMessage));
console.log(`Error Signing In`, {
error,
errorCode,
errorMessage
});
signInWithEmailAndPassword(auth, email, password).then((userCredential: any) => {
if (userCredential != null) {
let existingUser = users.find(usr => usr?.email?.toLowerCase() == email?.toLowerCase());
if (existingUser != null) {
signInUser(existingUser);
toast.success(`Successfully Signed In`);
} else {
setEmailField(true);
setAuthState(`Sign Up`);
}
return;
});
} else {
toast.error(`Database not connected or not being used`);
}
}
}).catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
if (errorMessage) {
toast.error(renderErrorMessage(errorMessage));
console.log(`Error Signing In`, {
error,
errorCode,
errorMessage
});
}
return;
});
}

const onSignUp = (email, password) => {
if (useDatabase == true) {
createUserWithEmailAndPassword(auth, email, password).then(async (userCredential: any) => {
if (userCredential != null) {
let {
uid,
photoURL: avatar,
displayName: name,
accessToken: token,
phoneNumber: phone,
isAnonymous: anonymous,
emailVerified: verified,
} = userCredential?.user;
createUserWithEmailAndPassword(auth, email, password).then(async (userCredential: any) => {
if (userCredential != null) {
let {
uid,
photoURL: avatar,
displayName: name,
accessToken: token,
phoneNumber: phone,
isAnonymous: anonymous,
emailVerified: verified,
} = userCredential?.user;

let highestRank = await findHighestNumberInArrayByKey(users, `rank`);
let userData = {
uid,
name,
email,
phone,
avatar,
rank: highestRank + 1,
auth: {
token,
verified,
anonymous,
}
let highestRank = await findHighestNumberInArrayByKey(users, `rank`);
let userData = {
uid,
name,
email,
phone,
avatar,
rank: highestRank + 1,
auth: {
token,
verified,
anonymous,
}
}

let cleanedUser = removeNullAndUndefinedProperties(userData);
let newUser = new User(cleanedUser);
let cleanedUser = removeNullAndUndefinedProperties(userData);
let newUser = new User(cleanedUser);

await addUserToDatabase(newUser).then(() => {
toast.success(`Signed Up & In as: ${newUser?.name}`);
console.log(`New User`, newUser);
signInUser(newUser);
form.reset();
});
} else {
toast.error(`Error on Sign Up`);
}
}).catch((error) => {
console.log(`Error Signing Up`, error);
const errorMessage = error.message;
if (errorMessage) {
toast.error(renderErrorMessage(errorMessage));
} else {
toast.error(`Error Signing Up`);
}
return;
});
} else {
toast.error(`Database not connected or not being used`);
}
await addUserToDatabase(newUser).then(() => {
toast.success(`Signed Up & In as: ${newUser?.name}`);
console.log(`New User`, newUser);
signInUser(newUser);
form.reset();
});
} else {
toast.error(`Error on Sign Up`);
}
}).catch((error) => {
console.log(`Error Signing Up`, error);
const errorMessage = error.message;
if (errorMessage) {
toast.error(renderErrorMessage(errorMessage));
} else {
toast.error(`Error Signing Up`);
}
return;
});
}

switch(clicked?.value) {
Expand Down Expand Up @@ -267,7 +259,7 @@ export default function Form(props?: any) {
}, [user, users, authState]);

return <>
<form id={id} onSubmit={authForm} className={`flex authForm customButtons ${className}`} style={style}>
<form {...id && { id }} onSubmit={authForm} className={`flex authForm customButtons ${className}`} style={style}>

{!user && <input placeholder="Email" type="email" name="email" autoComplete={`email`} required />}
{!user && emailField && <input placeholder="Password" type="password" minLength={6} name="password" autoComplete={`current-password`} />}
Expand All @@ -286,7 +278,7 @@ export default function Form(props?: any) {

<input className={(user && window?.location?.href?.includes(`profile`) || (authState == `Sign In` || authState == `Sign Up`)) ? `submit half` : `submit full`} type="submit" name="authFormSubmit" value={user ? `Sign Out` : authState} />

{(authState == `Sign In` || authState == `Sign Up`) && <input id={`back`} className={`back authFormBack`} type="submit" name="authFormBack" value={`Back`} />}
{(authState == `Sign In` || authState == `Sign Up`) && <input className={`back authFormBack`} type="submit" name="authFormBack" value={`Back`} />}

</form>
</>
Expand Down
2 changes: 1 addition & 1 deletion firebase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export const db = getFirestore(firebaseApp);
export const auth = getAuth(firebaseApp);

export const isProduction = process.env.NODE_ENV == `production`;
export const environment = isProduction ? Environments.alpha : Environments.beta;
export const environment = isProduction ? Environments.alpha : Environments.alpha;

export const usersTable = environment + Tables.users;

Expand Down
Loading

0 comments on commit fadb052

Please sign in to comment.