├── .gitignore
├── README.md
├── package-lock.json
├── package.json
├── public
├── favicon.ico
├── index.html
├── logo192.png
├── logo512.png
├── manifest.json
└── robots.txt
└── src
├── App.css
├── App.js
├── App.test.js
├── assets
├── bot.jpeg
└── logo.png
├── components
├── MessageForm.css
├── MessageForm.js
├── Navigation.js
├── Sidebar.css
└── Sidebar.js
├── context
└── appContext.js
├── features
└── userSlice.js
├── index.css
├── index.js
├── logo.svg
├── pages
├── Chat.js
├── Home.css
├── Home.js
├── Login.css
├── Login.js
├── Signup.css
└── Signup.js
├── reportWebVitals.js
├── services
└── appApi.js
├── setupTests.js
└── store.js
/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 | /.pnp
6 | .pnp.js
7 |
8 | # testing
9 | /coverage
10 |
11 | # production
12 | /build
13 |
14 | # misc
15 | .DS_Store
16 | .env.local
17 | .env.development.local
18 | .env.test.local
19 | .env.production.local
20 |
21 | npm-debug.log*
22 | yarn-debug.log*
23 | yarn-error.log*
24 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Getting Started with Create React App
2 |
3 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
4 |
5 | ## Available Scripts
6 |
7 | In the project directory, you can run:
8 |
9 | ### `npm start`
10 |
11 | Runs the app in the development mode.\
12 | Open [http://localhost:3000](http://localhost:3000) to view it in your browser.
13 |
14 | The page will reload when you make changes.\
15 | You may also see any lint errors in the console.
16 |
17 | ### `npm test`
18 |
19 | Launches the test runner in the interactive watch mode.\
20 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
21 |
22 | ### `npm run build`
23 |
24 | Builds the app for production to the `build` folder.\
25 | It correctly bundles React in production mode and optimizes the build for the best performance.
26 |
27 | The build is minified and the filenames include the hashes.\
28 | Your app is ready to be deployed!
29 |
30 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
31 |
32 | ### `npm run eject`
33 |
34 | **Note: this is a one-way operation. Once you `eject`, you can't go back!**
35 |
36 | If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
37 |
38 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.
39 |
40 | You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.
41 |
42 | ## Learn More
43 |
44 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
45 |
46 | To learn React, check out the [React documentation](https://reactjs.org/).
47 |
48 | ### Code Splitting
49 |
50 | This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
51 |
52 | ### Analyzing the Bundle Size
53 |
54 | This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
55 |
56 | ### Making a Progressive Web App
57 |
58 | This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
59 |
60 | ### Advanced Configuration
61 |
62 | This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
63 |
64 | ### Deployment
65 |
66 | This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
67 |
68 | ### `npm run build` fails to minify
69 |
70 | This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
71 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "mern-chat-frontend",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "@reduxjs/toolkit": "^1.7.2",
7 | "@testing-library/jest-dom": "^5.16.2",
8 | "@testing-library/react": "^12.1.3",
9 | "@testing-library/user-event": "^13.5.0",
10 | "bootstrap": "^5.1.3",
11 | "react": "^17.0.2",
12 | "react-bootstrap": "^2.1.2",
13 | "react-dom": "^17.0.2",
14 | "react-redux": "^7.2.6",
15 | "react-router-bootstrap": "^0.26.0",
16 | "react-router-dom": "^6.2.1",
17 | "react-scripts": "5.0.0",
18 | "redux": "^4.1.2",
19 | "redux-persist": "^6.0.0",
20 | "redux-thunk": "^2.4.1",
21 | "socket.io-client": "^4.4.1",
22 | "web-vitals": "^2.1.4"
23 | },
24 | "scripts": {
25 | "start": "react-scripts start",
26 | "build": "react-scripts build",
27 | "test": "react-scripts test",
28 | "eject": "react-scripts eject"
29 | },
30 | "eslintConfig": {
31 | "extends": [
32 | "react-app",
33 | "react-app/jest"
34 | ]
35 | },
36 | "browserslist": {
37 | "production": [
38 | ">0.2%",
39 | "not dead",
40 | "not op_mini all"
41 | ],
42 | "development": [
43 | "last 1 chrome version",
44 | "last 1 firefox version",
45 | "last 1 safari version"
46 | ]
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/learnthiscode/mern-chat-frontend/499f533582be817b1aaf59dd8c1b08150347d215/public/favicon.ico
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
16 |
17 |
21 |
22 |
31 | React App
32 |
33 |
34 | You need to enable JavaScript to run this app.
35 |
36 |
46 |
47 |
--------------------------------------------------------------------------------
/public/logo192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/learnthiscode/mern-chat-frontend/499f533582be817b1aaf59dd8c1b08150347d215/public/logo192.png
--------------------------------------------------------------------------------
/public/logo512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/learnthiscode/mern-chat-frontend/499f533582be817b1aaf59dd8c1b08150347d215/public/logo512.png
--------------------------------------------------------------------------------
/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "short_name": "React App",
3 | "name": "Create React App Sample",
4 | "icons": [
5 | {
6 | "src": "favicon.ico",
7 | "sizes": "64x64 32x32 24x24 16x16",
8 | "type": "image/x-icon"
9 | },
10 | {
11 | "src": "logo192.png",
12 | "type": "image/png",
13 | "sizes": "192x192"
14 | },
15 | {
16 | "src": "logo512.png",
17 | "type": "image/png",
18 | "sizes": "512x512"
19 | }
20 | ],
21 | "start_url": ".",
22 | "display": "standalone",
23 | "theme_color": "#000000",
24 | "background_color": "#ffffff"
25 | }
26 |
--------------------------------------------------------------------------------
/public/robots.txt:
--------------------------------------------------------------------------------
1 | # https://www.robotstxt.org/robotstxt.html
2 | User-agent: *
3 | Disallow:
4 |
--------------------------------------------------------------------------------
/src/App.css:
--------------------------------------------------------------------------------
1 | .App {
2 | text-align: center;
3 | }
4 |
5 | .App-logo {
6 | height: 40vmin;
7 | pointer-events: none;
8 | }
9 |
10 | @media (prefers-reduced-motion: no-preference) {
11 | .App-logo {
12 | animation: App-logo-spin infinite 20s linear;
13 | }
14 | }
15 |
16 | .App-header {
17 | background-color: #282c34;
18 | min-height: 100vh;
19 | display: flex;
20 | flex-direction: column;
21 | align-items: center;
22 | justify-content: center;
23 | font-size: calc(10px + 2vmin);
24 | color: white;
25 | }
26 |
27 | .App-link {
28 | color: #61dafb;
29 | }
30 |
31 | @keyframes App-logo-spin {
32 | from {
33 | transform: rotate(0deg);
34 | }
35 | to {
36 | transform: rotate(360deg);
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/App.js:
--------------------------------------------------------------------------------
1 | import logo from "./logo.svg";
2 | import "./App.css";
3 | import { BrowserRouter, Routes, Route } from "react-router-dom";
4 | import Navigation from "./components/Navigation";
5 | import Home from "./pages/Home";
6 | import Login from "./pages/Login";
7 | import Signup from "./pages/Signup";
8 | import Chat from "./pages/Chat";
9 | import { useSelector } from "react-redux";
10 | import { useState } from "react";
11 | import { AppContext, socket } from "./context/appContext";
12 |
13 | function App() {
14 | const [rooms, setRooms] = useState([]);
15 | const [currentRoom, setCurrentRoom] = useState([]);
16 | const [members, setMembers] = useState([]);
17 | const [messages, setMessages] = useState([]);
18 | const [privateMemberMsg, setPrivateMemberMsg] = useState({});
19 | const [newMessages, setNewMessages] = useState({});
20 | const user = useSelector((state) => state.user);
21 | return (
22 |
23 |
24 |
25 |
26 | } />
27 | {!user && (
28 | <>
29 | } />
30 | } />
31 | >
32 | )}
33 | } />
34 |
35 |
36 |
37 | );
38 | }
39 |
40 | export default App;
41 |
--------------------------------------------------------------------------------
/src/App.test.js:
--------------------------------------------------------------------------------
1 | import { render, screen } from '@testing-library/react';
2 | import App from './App';
3 |
4 | test('renders learn react link', () => {
5 | render( );
6 | const linkElement = screen.getByText(/learn react/i);
7 | expect(linkElement).toBeInTheDocument();
8 | });
9 |
--------------------------------------------------------------------------------
/src/assets/bot.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/learnthiscode/mern-chat-frontend/499f533582be817b1aaf59dd8c1b08150347d215/src/assets/bot.jpeg
--------------------------------------------------------------------------------
/src/assets/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/learnthiscode/mern-chat-frontend/499f533582be817b1aaf59dd8c1b08150347d215/src/assets/logo.png
--------------------------------------------------------------------------------
/src/components/MessageForm.css:
--------------------------------------------------------------------------------
1 | .messages-output {
2 | height: 80vh;
3 | border: 1px solid lightgray;
4 | overflow-y: scroll;
5 | margin-bottom: 20px;
6 | }
7 |
8 | .message-inner {
9 | margin-left: 20px;
10 | margin-bottom: 10px;
11 | padding: 10px;
12 | min-width: 200px;
13 | max-width: 90%;
14 | text-align: left;
15 | min-height: 80px;
16 | font: 400 1em, sans-serif;
17 | display: inline-block;
18 | border-radius: 10px;
19 | background-color: #d1e7dd;
20 | }
21 |
22 | .incoming-message .message-inner {
23 | background-color: #ffdab9;
24 | }
25 |
26 | .incoming-message {
27 | display: flex;
28 | justify-content: flex-end;
29 | margin-right: 20px;
30 | }
31 |
32 | .message-timestamp-left {
33 | font-size: 0.85em;
34 | font-weight: 300;
35 | margin-top: 10px;
36 | }
37 |
38 | .message-sender {
39 | margin-bottom: 5px;
40 | font-weight: bold;
41 | }
42 |
43 | .message-date-indicator {
44 | width: 150px;
45 | margin: 0 auto;
46 | }
47 |
48 | .conversation-info {
49 | padding: 0;
50 | margin: 0 auto;
51 | text-align: center;
52 | height: 100px;
53 | }
54 |
55 | .conversation-profile-pic {
56 | width: 60px;
57 | height: 60px;
58 | object-fit: cover;
59 | margin: 10px auto;
60 | margin-bottom: 30px;
61 | border-radius: 50%;
62 | margin-left: 10px;
63 | }
64 |
--------------------------------------------------------------------------------
/src/components/MessageForm.js:
--------------------------------------------------------------------------------
1 | import React, { useContext, useEffect, useRef, useState } from "react";
2 | import { Button, Col, Form, Row } from "react-bootstrap";
3 | import { useSelector } from "react-redux";
4 | import { AppContext } from "../context/appContext";
5 | import "./MessageForm.css";
6 | function MessageForm() {
7 | const [message, setMessage] = useState("");
8 | const user = useSelector((state) => state.user);
9 | const { socket, currentRoom, setMessages, messages, privateMemberMsg } = useContext(AppContext);
10 | const messageEndRef = useRef(null);
11 | useEffect(() => {
12 | scrollToBottom();
13 | }, [messages]);
14 |
15 | function getFormattedDate() {
16 | const date = new Date();
17 | const year = date.getFullYear();
18 | let month = (1 + date.getMonth()).toString();
19 |
20 | month = month.length > 1 ? month : "0" + month;
21 | let day = date.getDate().toString();
22 |
23 | day = day.length > 1 ? day : "0" + day;
24 |
25 | return month + "/" + day + "/" + year;
26 | }
27 |
28 | function handleSubmit(e) {
29 | e.preventDefault();
30 | }
31 |
32 | function scrollToBottom() {
33 | messageEndRef.current?.scrollIntoView({ behavior: "smooth" });
34 | }
35 |
36 | const todayDate = getFormattedDate();
37 |
38 | socket.off("room-messages").on("room-messages", (roomMessages) => {
39 | setMessages(roomMessages);
40 | });
41 |
42 | function handleSubmit(e) {
43 | e.preventDefault();
44 | if (!message) return;
45 | const today = new Date();
46 | const minutes = today.getMinutes() < 10 ? "0" + today.getMinutes() : today.getMinutes();
47 | const time = today.getHours() + ":" + minutes;
48 | const roomId = currentRoom;
49 | socket.emit("message-room", roomId, message, user, time, todayDate);
50 | setMessage("");
51 | }
52 | return (
53 | <>
54 |
55 | {user && !privateMemberMsg?._id &&
You are in the {currentRoom} room
}
56 | {user && privateMemberMsg?._id && (
57 | <>
58 |
59 |
60 | Your conversation with {privateMemberMsg.name}
61 |
62 |
63 | >
64 | )}
65 | {!user &&
Please login
}
66 |
67 | {user &&
68 | messages.map(({ _id: date, messagesByDate }, idx) => (
69 |
70 |
{date}
71 | {messagesByDate?.map(({ content, time, from: sender }, msgIdx) => (
72 |
73 |
74 |
75 |
76 |
{sender._id == user?._id ? "You" : sender.name}
77 |
78 |
{content}
79 |
{time}
80 |
81 |
82 | ))}
83 |
84 | ))}
85 |
86 |
87 |
101 | >
102 | );
103 | }
104 |
105 | export default MessageForm;
106 |
--------------------------------------------------------------------------------
/src/components/Navigation.js:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import { Nav, Navbar, Container, Button, NavDropdown } from "react-bootstrap";
3 | import { useLogoutUserMutation } from "../services/appApi";
4 | import { useSelector } from "react-redux";
5 | import { LinkContainer } from "react-router-bootstrap";
6 | import logo from "../assets/logo.png";
7 | function Navigation() {
8 | const user = useSelector((state) => state.user);
9 | const [logoutUser] = useLogoutUserMutation();
10 | async function handleLogout(e) {
11 | e.preventDefault();
12 | await logoutUser(user);
13 | // redirect to home page
14 | window.location.replace("/");
15 | }
16 | return (
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 | {!user && (
28 |
29 | Login
30 |
31 | )}
32 |
33 | Chat
34 |
35 | {user && (
36 |
39 |
40 | {user.name}
41 | >
42 | }
43 | id="basic-nav-dropdown"
44 | >
45 | Action
46 | Another action
47 | Something
48 |
49 |
50 |
51 | Logout
52 |
53 |
54 |
55 | )}
56 |
57 |
58 |
59 |
60 | );
61 | }
62 |
63 | export default Navigation;
64 |
--------------------------------------------------------------------------------
/src/components/Sidebar.css:
--------------------------------------------------------------------------------
1 | .member-status-img {
2 | width: 30px;
3 | height: 30px;
4 | border-radius: 50%;
5 | object-fit: cover;
6 | }
7 |
8 | .member-status {
9 | margin-bottom: 0;
10 | position: relative;
11 | }
12 |
13 | .sidebar-online-status {
14 | color: green;
15 | }
16 |
17 | .sidebar-offline-status {
18 | color: #e3b505;
19 | }
20 |
21 | .sidebar-offline-status,
22 | .sidebar-online-status {
23 | font-size: 11px;
24 | position: absolute;
25 | z-index: 99;
26 | bottom: 0;
27 | left: 12px;
28 | }
29 |
--------------------------------------------------------------------------------
/src/components/Sidebar.js:
--------------------------------------------------------------------------------
1 | import React, { useContext, useEffect } from "react";
2 | import { Col, ListGroup, Row } from "react-bootstrap";
3 | import { useDispatch, useSelector } from "react-redux";
4 | import { AppContext } from "../context/appContext";
5 | import { addNotifications, resetNotifications } from "../features/userSlice";
6 | import "./Sidebar.css";
7 |
8 | function Sidebar() {
9 | const user = useSelector((state) => state.user);
10 | const dispatch = useDispatch();
11 | const { socket, setMembers, members, setCurrentRoom, setRooms, privateMemberMsg, rooms, setPrivateMemberMsg, currentRoom } = useContext(AppContext);
12 |
13 | function joinRoom(room, isPublic = true) {
14 | if (!user) {
15 | return alert("Please login");
16 | }
17 | socket.emit("join-room", room, currentRoom);
18 | setCurrentRoom(room);
19 |
20 | if (isPublic) {
21 | setPrivateMemberMsg(null);
22 | }
23 | // dispatch for notifications
24 | dispatch(resetNotifications(room));
25 | }
26 |
27 | socket.off("notifications").on("notifications", (room) => {
28 | if (currentRoom != room) dispatch(addNotifications(room));
29 | });
30 |
31 | useEffect(() => {
32 | if (user) {
33 | setCurrentRoom("general");
34 | getRooms();
35 | socket.emit("join-room", "general");
36 | socket.emit("new-user");
37 | }
38 | }, []);
39 |
40 | socket.off("new-user").on("new-user", (payload) => {
41 | setMembers(payload);
42 | });
43 |
44 | function getRooms() {
45 | fetch("http://localhost:5001/rooms")
46 | .then((res) => res.json())
47 | .then((data) => setRooms(data));
48 | }
49 |
50 | function orderIds(id1, id2) {
51 | if (id1 > id2) {
52 | return id1 + "-" + id2;
53 | } else {
54 | return id2 + "-" + id1;
55 | }
56 | }
57 |
58 | function handlePrivateMemberMsg(member) {
59 | setPrivateMemberMsg(member);
60 | const roomId = orderIds(user._id, member._id);
61 | joinRoom(roomId, false);
62 | }
63 |
64 | if (!user) {
65 | return <>>;
66 | }
67 | return (
68 | <>
69 | Available rooms
70 |
71 | {rooms.map((room, idx) => (
72 | joinRoom(room)} active={room == currentRoom} style={{ cursor: "pointer", display: "flex", justifyContent: "space-between" }}>
73 | {room} {currentRoom !== room && {user.newMessages[room]} }
74 |
75 | ))}
76 |
77 | Members
78 | {members.map((member) => (
79 | handlePrivateMemberMsg(member)} disabled={member._id === user._id}>
80 |
81 |
82 |
83 | {member.status == "online" ? : }
84 |
85 |
86 | {member.name}
87 | {member._id === user?._id && " (You)"}
88 | {member.status == "offline" && " (Offline)"}
89 |
90 |
91 | {user.newMessages[orderIds(member._id, user._id)]}
92 |
93 |
94 |
95 | ))}
96 | >
97 | );
98 | }
99 |
100 | export default Sidebar;
101 |
--------------------------------------------------------------------------------
/src/context/appContext.js:
--------------------------------------------------------------------------------
1 | import { io } from "socket.io-client";
2 | import React from "react";
3 | const SOCKET_URL = "http://localhost:5001";
4 | export const socket = io(SOCKET_URL);
5 | // app context
6 | export const AppContext = React.createContext();
7 |
--------------------------------------------------------------------------------
/src/features/userSlice.js:
--------------------------------------------------------------------------------
1 | import { createSlice } from "@reduxjs/toolkit";
2 | import appApi from "../services/appApi";
3 |
4 | export const userSlice = createSlice({
5 | name: "user",
6 | initialState: null,
7 | reducers: {
8 | addNotifications: (state, { payload }) => {
9 | if (state.newMessages[payload]) {
10 | state.newMessages[payload] = state.newMessages[payload] + 1;
11 | } else {
12 | state.newMessages[payload] = 1;
13 | }
14 | },
15 | resetNotifications: (state, { payload }) => {
16 | delete state.newMessages[payload];
17 | },
18 | },
19 |
20 | extraReducers: (builder) => {
21 | // save user after signup
22 | builder.addMatcher(appApi.endpoints.signupUser.matchFulfilled, (state, { payload }) => payload);
23 | // save user after login
24 | builder.addMatcher(appApi.endpoints.loginUser.matchFulfilled, (state, { payload }) => payload);
25 | // logout: destroy user session
26 | builder.addMatcher(appApi.endpoints.logoutUser.matchFulfilled, () => null);
27 | },
28 | });
29 |
30 | export const { addNotifications, resetNotifications } = userSlice.actions;
31 | export default userSlice.reducer;
32 |
--------------------------------------------------------------------------------
/src/index.css:
--------------------------------------------------------------------------------
1 | body {
2 | margin: 0;
3 | font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
4 | 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
5 | sans-serif;
6 | -webkit-font-smoothing: antialiased;
7 | -moz-osx-font-smoothing: grayscale;
8 | }
9 |
10 | code {
11 | font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
12 | monospace;
13 | }
14 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import ReactDOM from "react-dom";
3 | import "./index.css";
4 | import App from "./App";
5 | import reportWebVitals from "./reportWebVitals";
6 | import "bootstrap/dist/css/bootstrap.min.css";
7 | import { Provider } from "react-redux";
8 | import { PersistGate } from "redux-persist/integration/react";
9 | import persistStore from "redux-persist/es/persistStore";
10 | import store from "./store";
11 |
12 | const persistedStore = persistStore(store);
13 |
14 | ReactDOM.render(
15 |
16 |
17 |
18 |
19 |
20 |
21 | ,
22 | document.getElementById("root")
23 | );
24 |
25 | // If you want to start measuring performance in your app, pass a function
26 | // to log results (for example: reportWebVitals(console.log))
27 | // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
28 | reportWebVitals();
29 |
--------------------------------------------------------------------------------
/src/logo.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/src/pages/Chat.js:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import { Container, Row, Col } from "react-bootstrap";
3 | import Sidebar from "../components/Sidebar";
4 | import MessageForm from "../components/MessageForm";
5 |
6 | function Chat() {
7 | return (
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 | );
19 | }
20 |
21 | export default Chat;
22 |
--------------------------------------------------------------------------------
/src/pages/Home.css:
--------------------------------------------------------------------------------
1 | .home__bg {
2 | background-image: url(https://images.unsplash.com/photo-1529156069898-49953e39b3ac?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1932&q=80);
3 | height: 92vh;
4 | background-position: center;
5 | background-size: cover;
6 | background-repeat: no-repeat;
7 | overflow-x: hidden;
8 | }
9 |
10 | .home-message-icon {
11 | margin-left: 10px;
12 | display: inline-block;
13 | }
14 |
--------------------------------------------------------------------------------
/src/pages/Home.js:
--------------------------------------------------------------------------------
1 | import React from "react";
2 | import { Row, Col, Button } from "react-bootstrap";
3 | import { LinkContainer } from "react-router-bootstrap";
4 | import "./Home.css";
5 |
6 | function Home() {
7 | return (
8 |
9 |
10 |
11 |
Share the world with your friends
12 |
Chat App lets you connect with the world
13 |
14 |
15 | Get Started
16 |
17 |
18 |
19 |
20 |
21 |
22 | );
23 | }
24 |
25 | export default Home;
26 |
--------------------------------------------------------------------------------
/src/pages/Login.css:
--------------------------------------------------------------------------------
1 | .login__bg {
2 | background-image: url(https://images.unsplash.com/photo-1577563908411-5077b6dc7624?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1740&q=80);
3 | height: 92vh;
4 | background-position: center;
5 | background-size: cover;
6 | background-repeat: no-repeat;
7 | overflow-x: hidden;
8 | }
9 |
--------------------------------------------------------------------------------
/src/pages/Login.js:
--------------------------------------------------------------------------------
1 | import React, { useContext, useState } from "react";
2 | import { Col, Container, Form, Row, Button, Spinner } from "react-bootstrap";
3 | import { useLoginUserMutation } from "../services/appApi";
4 | import { Link, useNavigate } from "react-router-dom";
5 | import "./Login.css";
6 | import { AppContext } from "../context/appContext";
7 |
8 | function Login() {
9 | const [email, setEmail] = useState("");
10 | const [password, setPassword] = useState("");
11 | const navigate = useNavigate();
12 | const { socket } = useContext(AppContext);
13 | const [loginUser, { isLoading, error }] = useLoginUserMutation();
14 | function handleLogin(e) {
15 | e.preventDefault();
16 | // login logic
17 | loginUser({ email, password }).then(({ data }) => {
18 | if (data) {
19 | // socket work
20 | socket.emit("new-user");
21 | // navigate to the chat
22 | navigate("/chat");
23 | }
24 | });
25 | }
26 |
27 | return (
28 |
29 |
30 |
31 |
32 |
34 | {error && {error.data}
}
35 | Email address
36 | setEmail(e.target.value)} value={email} required />
37 | We'll never share your email with anyone else.
38 |
39 |
40 |
41 | Password
42 | setPassword(e.target.value)} value={password} required />
43 |
44 |
45 | {isLoading ? : "Login"}
46 |
47 |
48 |
49 | Don't have an account ? Signup
50 |
51 |
52 |
53 |
54 |
55 |
56 | );
57 | }
58 |
59 | export default Login;
60 |
--------------------------------------------------------------------------------
/src/pages/Signup.css:
--------------------------------------------------------------------------------
1 | .signup__bg {
2 | background-image: url(https://images.unsplash.com/photo-1622556498246-755f44ca76f3?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MzJ8fG1lc3NhZ2UlMjBhcHB8ZW58MHx8MHx8&auto=format&fit=crop&w=800&q=60);
3 | height: 92vh;
4 | background-position: center;
5 | background-size: cover;
6 | background-repeat: no-repeat;
7 | overflow-x: hidden;
8 | }
9 |
10 | .signup-profile-pic__container {
11 | width: 100px;
12 | height: 100px;
13 | margin: 0 auto;
14 | position: relative;
15 | }
16 |
17 | .signup-profile-pic {
18 | width: 100px;
19 | border-radius: 50%;
20 | border: 2px solid gray;
21 | object-fit: cover;
22 | height: 100px;
23 | }
24 |
25 | .add-picture-icon {
26 | position: absolute;
27 | bottom: 0;
28 | right: 10px;
29 | color: green;
30 | background: white;
31 | cursor: pointer;
32 | z-index: 99;
33 | }
34 |
--------------------------------------------------------------------------------
/src/pages/Signup.js:
--------------------------------------------------------------------------------
1 | import React, { useState } from "react";
2 | import { Col, Container, Form, Row, Button } from "react-bootstrap";
3 | import { useSignupUserMutation } from "../services/appApi";
4 | import { Link, useNavigate } from "react-router-dom";
5 | import "./Signup.css";
6 | import botImg from "../assets/bot.jpeg";
7 |
8 | function Signup() {
9 | const [email, setEmail] = useState("");
10 | const [password, setPassword] = useState("");
11 | const [name, setName] = useState("");
12 | const [signupUser, { isLoading, error }] = useSignupUserMutation();
13 | const navigate = useNavigate();
14 | //image upload states
15 | const [image, setImage] = useState(null);
16 | const [upladingImg, setUploadingImg] = useState(false);
17 | const [imagePreview, setImagePreview] = useState(null);
18 |
19 | function validateImg(e) {
20 | const file = e.target.files[0];
21 | if (file.size >= 1048576) {
22 | return alert("Max file size is 1mb");
23 | } else {
24 | setImage(file);
25 | setImagePreview(URL.createObjectURL(file));
26 | }
27 | }
28 |
29 | async function uploadImage() {
30 | const data = new FormData();
31 | data.append("file", image);
32 | data.append("upload_preset", "your-preset-here");
33 | try {
34 | setUploadingImg(true);
35 | let res = await fetch("https://api.cloudinary.com/v1_1/your-username-here/image/upload", {
36 | method: "post",
37 | body: data,
38 | });
39 | const urlData = await res.json();
40 | setUploadingImg(false);
41 | return urlData.url;
42 | } catch (error) {
43 | setUploadingImg(false);
44 | console.log(error);
45 | }
46 | }
47 |
48 | async function handleSignup(e) {
49 | e.preventDefault();
50 | if (!image) return alert("Please upload your profile picture");
51 | const url = await uploadImage(image);
52 | console.log(url);
53 | // signup the user
54 | signupUser({ name, email, password, picture: url }).then(({ data }) => {
55 | if (data) {
56 | console.log(data);
57 | navigate("/chat");
58 | }
59 | });
60 | }
61 |
62 | return (
63 |
64 |
65 |
66 |
77 | Name
78 | setName(e.target.value)} value={name} />
79 |
80 |
81 | Email address
82 | setEmail(e.target.value)} value={email} />
83 | We'll never share your email with anyone else.
84 |
85 |
86 |
87 | Password
88 | setPassword(e.target.value)} value={password} />
89 |
90 |
91 | {upladingImg || isLoading ? "Signing you up..." : "Signup"}
92 |
93 |
94 |
95 | Already have an account ? Login
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 | );
104 | }
105 |
106 | export default Signup;
107 |
--------------------------------------------------------------------------------
/src/reportWebVitals.js:
--------------------------------------------------------------------------------
1 | const reportWebVitals = onPerfEntry => {
2 | if (onPerfEntry && onPerfEntry instanceof Function) {
3 | import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
4 | getCLS(onPerfEntry);
5 | getFID(onPerfEntry);
6 | getFCP(onPerfEntry);
7 | getLCP(onPerfEntry);
8 | getTTFB(onPerfEntry);
9 | });
10 | }
11 | };
12 |
13 | export default reportWebVitals;
14 |
--------------------------------------------------------------------------------
/src/services/appApi.js:
--------------------------------------------------------------------------------
1 | import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
2 |
3 | // define a service user a base URL
4 |
5 | const appApi = createApi({
6 | reducerPath: "appApi",
7 | baseQuery: fetchBaseQuery({
8 | baseUrl: "http://localhost:5001",
9 | }),
10 |
11 | endpoints: (builder) => ({
12 | // creating the user
13 | signupUser: builder.mutation({
14 | query: (user) => ({
15 | url: "/users",
16 | method: "POST",
17 | body: user,
18 | }),
19 | }),
20 |
21 | // login
22 | loginUser: builder.mutation({
23 | query: (user) => ({
24 | url: "/users/login",
25 | method: "POST",
26 | body: user,
27 | }),
28 | }),
29 |
30 | // logout
31 |
32 | logoutUser: builder.mutation({
33 | query: (payload) => ({
34 | url: "/logout",
35 | method: "DELETE",
36 | body: payload,
37 | }),
38 | }),
39 | }),
40 | });
41 |
42 | export const { useSignupUserMutation, useLoginUserMutation, useLogoutUserMutation } = appApi;
43 |
44 | export default appApi;
45 |
--------------------------------------------------------------------------------
/src/setupTests.js:
--------------------------------------------------------------------------------
1 | // jest-dom adds custom jest matchers for asserting on DOM nodes.
2 | // allows you to do things like:
3 | // expect(element).toHaveTextContent(/react/i)
4 | // learn more: https://github.com/testing-library/jest-dom
5 | import '@testing-library/jest-dom';
6 |
--------------------------------------------------------------------------------
/src/store.js:
--------------------------------------------------------------------------------
1 | import { configureStore } from "@reduxjs/toolkit";
2 | import userSlice from "./features/userSlice";
3 | import appApi from "./services/appApi";
4 |
5 | // persist our store
6 | import storage from "redux-persist/lib/storage";
7 | import { combineReducers } from "redux";
8 | import { persistReducer } from "redux-persist";
9 | import thunk from "redux-thunk";
10 |
11 | // reducers
12 | const reducer = combineReducers({
13 | user: userSlice,
14 | [appApi.reducerPath]: appApi.reducer,
15 | });
16 |
17 | const persistConfig = {
18 | key: "root",
19 | storage,
20 | blackList: [appApi.reducerPath],
21 | };
22 |
23 | // persist our store
24 |
25 | const persistedReducer = persistReducer(persistConfig, reducer);
26 |
27 | // creating the store
28 |
29 | const store = configureStore({
30 | reducer: persistedReducer,
31 | middleware: [thunk, appApi.middleware],
32 | });
33 |
34 | export default store;
35 |
--------------------------------------------------------------------------------