├── .gitignore
├── .idea
├── chat-app.iml
├── inspectionProfiles
│ └── Project_Default.xml
├── misc.xml
├── modules.xml
├── vcs.xml
└── workspace.xml
├── README.md
├── package.json
├── public
├── favicon.ico
├── index.html
├── logo192.png
├── logo512.png
├── manifest.json
└── robots.txt
└── src
├── App.css
├── App.js
├── App.test.js
├── components
├── Navbar
│ ├── Navbar.js
│ └── Navbar.scss
├── PrivateRoute
│ └── PrivateRoute.js
└── Spinner
│ ├── Spinner.js
│ └── spinner.gif
├── firebase
└── firebase.utils.js
├── index.css
├── index.js
├── logo.svg
├── pages
├── Chat
│ ├── Chat.js
│ └── components
│ │ ├── ChatInput
│ │ ├── ChatInput.js
│ │ └── ChatInput.scss
│ │ ├── ChatMessage
│ │ ├── ChatMessage.js
│ │ └── ChatMessage.scss
│ │ ├── ChatroomList
│ │ ├── ChatroomList.js
│ │ └── ChatroomList.scss
│ │ ├── ChatroomTitleBar
│ │ ├── ChatroomTitleBar.js
│ │ └── ChatroomTitleBar.scss
│ │ └── ChatroomWindow
│ │ ├── ChatroomWindow.js
│ │ └── ChatroomWindow.scss
├── EditProfile
│ ├── EditProfile.js
│ └── EditProfile.scss
├── Login
│ ├── Login.js
│ └── Login.scss
├── Profile
│ ├── Profile.js
│ └── Profile.scss
└── Signup
│ ├── Signup.js
│ └── Signup.scss
├── redux
├── chatroom
│ ├── chatroom.actions.js
│ └── chatroom.reducer.js
├── rootReducer.js
├── store.js
└── user
│ ├── user.actions.js
│ └── user.reducer.js
├── serviceWorker.js
├── setupTests.js
├── styles
├── styles.scss
└── variables.scss
└── utils
└── utils.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 |
25 | # Local Netlify folder
26 | .netlify
--------------------------------------------------------------------------------
/.idea/chat-app.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/Project_Default.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/workspace.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 | true
29 |
30 | true
31 | true
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 | 1593452419265
106 |
107 |
108 | 1593452419265
109 |
110 |
111 |
112 |
113 |
114 |
115 | 1593635828851
116 |
117 |
118 |
119 | 1593635828851
120 |
121 |
122 | 1593642054381
123 |
124 |
125 |
126 | 1593642054381
127 |
128 |
129 | 1593644000579
130 |
131 |
132 |
133 | 1593644000579
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 |
151 |
152 |
153 |
154 |
155 |
156 |
157 |
158 |
159 |
160 |
161 |
162 |
163 |
164 |
165 |
166 |
167 |
168 |
169 |
170 |
171 |
172 |
173 |
174 |
175 |
176 |
177 |
178 |
179 |
180 |
181 |
182 |
183 |
184 |
185 |
186 |
187 |
188 | file://$PROJECT_DIR$/src/index.js
189 |
190 |
191 |
192 |
193 |
194 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Here is the live demo CLICK TO SEE DEMO
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 | ### `yarn start`
10 |
11 | Runs the app in the development mode.
12 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
13 |
14 | The page will reload if you make edits.
15 | You will also see any lint errors in the console.
16 |
17 | ### `yarn 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 | ### `yarn 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 | ### `yarn 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
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
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
59 |
60 | ### Advanced Configuration
61 |
62 | This section has moved here: 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
67 |
68 | ### `yarn 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
71 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "chat-app",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "@testing-library/jest-dom": "^4.2.4",
7 | "@testing-library/react": "^9.3.2",
8 | "@testing-library/user-event": "^7.1.2",
9 | "bootstrap": "^4.5.0",
10 | "firebase": "^7.15.5",
11 | "react": "^16.13.1",
12 | "react-dom": "^16.13.1",
13 | "react-redux": "^7.2.0",
14 | "react-redux-toastr": "^7.6.5",
15 | "react-router-dom": "^5.2.0",
16 | "react-scripts": "3.4.1",
17 | "redux": "^4.0.5",
18 | "redux-thunk": "^2.3.0",
19 | "sass": "^1.26.9"
20 | },
21 | "devDependencies": {
22 | "redux-devtools-extension": "^2.13.8"
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": "react-app"
32 | },
33 | "browserslist": {
34 | "production": [
35 | ">0.2%",
36 | "not dead",
37 | "not op_mini all"
38 | ],
39 | "development": [
40 | "last 1 chrome version",
41 | "last 1 firefox version",
42 | "last 1 safari version"
43 | ]
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheCoderDream/React-Chat-App-With-Redux-And-Firebase/3f137ea2d8f81760105b6ee9ca0be90a67314cdd/public/favicon.ico
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
17 |
18 |
27 | React App
28 |
29 |
30 | You need to enable JavaScript to run this app.
31 |
32 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/public/logo192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheCoderDream/React-Chat-App-With-Redux-And-Firebase/3f137ea2d8f81760105b6ee9ca0be90a67314cdd/public/logo192.png
--------------------------------------------------------------------------------
/public/logo512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheCoderDream/React-Chat-App-With-Redux-And-Firebase/3f137ea2d8f81760105b6ee9ca0be90a67314cdd/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 |
2 |
--------------------------------------------------------------------------------
/src/App.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import {connect} from "react-redux"
3 | import firebase from "firebase";
4 | import { createUserProfileDocument } from './firebase/firebase.utils';
5 | import {Switch,Route,withRouter,Redirect} from "react-router-dom"
6 | import ReduxToastr from 'react-redux-toastr'
7 | import Navbar from "./components/Navbar/Navbar";
8 | import { setCurrentUser, clearUser } from './redux/user/user.actions';
9 | import "./styles/styles.scss";
10 | import Chat from "./pages/Chat/Chat";
11 | import Login from "./pages/Login/Login";
12 | import Signup from "./pages/Signup/Signup";
13 | import Profile from "./pages/Profile/Profile";
14 | import PrivateRoute from "./components/PrivateRoute/PrivateRoute";
15 | import EditProfile from "./pages/EditProfile/EditProfile";
16 |
17 |
18 |
19 | function App({setUser, history, removeUser,auth }) {
20 | React.useEffect(() => {
21 | firebase.auth().onAuthStateChanged(async user => {
22 | if (user) {
23 | const userRef = await createUserProfileDocument(user);
24 | userRef.onSnapshot(snapShot => {
25 | setUser({ id: snapShot.id, ...snapShot.data() });
26 | });
27 | history.push('/');
28 | } else {
29 | history.push('/login');
30 | removeUser();
31 | }
32 | });
33 | }, []);
34 | return (
35 |
36 |
37 |
38 |
39 |
40 |
41 |
43 |
44 | } />
45 |
46 |
state.toastr}
52 | transitionIn="fadeIn"
53 | transitionOut="fadeOut"
54 | progressBar
55 | closeOnToastrClick/>
56 |
57 | )
58 |
59 | }
60 |
61 | const mapStateToProps = state => ({
62 | currentUser: state.user.currentUser,
63 | auth: {
64 | isAuthenticated: state.user.currentUser,
65 | loading: state.user.loading
66 | }
67 |
68 | });
69 |
70 | const mapDispatchToProps = dispatch => ({
71 | setUser: user => dispatch(setCurrentUser(user)),
72 | removeUser: () => dispatch(clearUser())
73 | });
74 |
75 | export default connect(mapStateToProps, mapDispatchToProps)(withRouter(App));
76 |
--------------------------------------------------------------------------------
/src/App.test.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { render } from '@testing-library/react';
3 | import App from './App';
4 |
5 | test('renders learn react link', () => {
6 | const { getByText } = render( );
7 | const linkElement = getByText(/learn react/i);
8 | expect(linkElement).toBeInTheDocument();
9 | });
10 |
--------------------------------------------------------------------------------
/src/components/Navbar/Navbar.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import {connect} from "react-redux"
3 | import {toastr} from "react-redux-toastr";
4 | import {auth} from '../../firebase/firebase.utils';
5 | import {NavLink, withRouter} from "react-router-dom"
6 | import "./Navbar.scss"
7 |
8 | const loggedOut = (
9 |
10 |
11 | Login
16 |
17 |
18 | Sign Up
22 |
23 |
24 | );
25 |
26 | const Navbar = ({history, currentUser}) => {
27 | const logout = async () => {
28 | try {
29 | await auth.signOut();
30 | toastr.success('Success!', 'Succesfully logged out');
31 | history.push("/login");
32 | } catch (e) {
33 | toastr.error('Success!', 'Something went wrong while logging out.');
34 | }
35 | }
36 | return (
37 |
38 |
39 |
ChatApp
40 |
41 | {
42 | currentUser ?
43 |
44 |
45 | Profile
50 |
51 |
52 | Chat Rooms
57 |
58 |
59 | Logout
60 |
61 | :
62 | loggedOut
63 | }
64 |
65 |
66 |
67 | );
68 | };
69 |
70 | export default connect(
71 | (state) => ({
72 | currentUser: state.user.currentUser
73 | })
74 | )(withRouter(Navbar));
75 |
--------------------------------------------------------------------------------
/src/components/Navbar/Navbar.scss:
--------------------------------------------------------------------------------
1 | @import '../../styles/variables';
2 |
3 | .nav-item, span {
4 | color: #ffffff;
5 | }
6 |
7 | ul {
8 | li {
9 | a {
10 | color: $light-grey;
11 | margin-left: 3em;
12 | cursor: pointer;
13 |
14 |
15 | &.active {
16 | border-bottom: 3px solid $gold;
17 | }
18 | }
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/src/components/PrivateRoute/PrivateRoute.js:
--------------------------------------------------------------------------------
1 | import Spinner from "../Spinner/Spinner";
2 | import React from "react";
3 | import { Redirect, Route } from "react-router-dom"
4 |
5 | export default (
6 | {
7 | component: Component,
8 | redirectTo = '/login',
9 | auth,
10 | ...rest
11 | }
12 | ) => {
13 | return (
14 |
17 | auth.loading ? (
18 |
19 | ) : auth.isAuthenticated ? (
20 |
21 | ) : (
22 |
23 | )
24 | }
25 | />
26 | )
27 | };
28 |
--------------------------------------------------------------------------------
/src/components/Spinner/Spinner.js:
--------------------------------------------------------------------------------
1 | import React, { Fragment } from 'react';
2 | import spinner from './spinner.gif';
3 |
4 | export default () => (
5 |
6 |
11 |
12 | );
13 |
--------------------------------------------------------------------------------
/src/components/Spinner/spinner.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheCoderDream/React-Chat-App-With-Redux-And-Firebase/3f137ea2d8f81760105b6ee9ca0be90a67314cdd/src/components/Spinner/spinner.gif
--------------------------------------------------------------------------------
/src/firebase/firebase.utils.js:
--------------------------------------------------------------------------------
1 | import firebase from 'firebase/app';
2 | import 'firebase/firestore';
3 | import 'firebase/auth';
4 | import 'firebase/storage';
5 |
6 | const config = {
7 | apiKey: "AIzaSyDybjfeq8utIazhlFPMVx9BPs-Iyd6oNoY",
8 | authDomain: "chat-874ea.firebaseapp.com",
9 | databaseURL: "https://chat-874ea.firebaseio.com",
10 | projectId: "chat-874ea",
11 | storageBucket: "chat-874ea.appspot.com",
12 | messagingSenderId: "779355726888",
13 | appId: "1:779355726888:web:3683ee55b8dad1d612c11d"
14 | };
15 |
16 | export const createUserProfileDocument = async (userAuth, additionalData) => {
17 | if (!userAuth) return;
18 | const userRef = firestore.doc(`users/${userAuth.uid}`);
19 | const snapShot = await userRef.get();
20 | if (!snapShot.exists) {
21 | const { displayName, email } = userAuth;
22 | const createdAt = new Date();
23 | try {
24 | await userRef.set({
25 | displayName,
26 | email,
27 | createdAt,
28 | ...additionalData
29 | });
30 | } catch (error) {
31 | // console.log('error creating user', error.message);
32 | }
33 | }
34 | return userRef;
35 | };
36 |
37 | export const imageUpload = (image, filePath) => {
38 | const storageRef = firebase.storage().ref();
39 | const uploadTask = storageRef.child(filePath).put(image);
40 |
41 | return uploadTask;
42 | };
43 |
44 | export const sendMessage = (chatroomId, message) => {
45 | return firestore.collection(`chatrooms/${chatroomId}/messages`).add(message);
46 | }
47 |
48 | export const addCollectionAndDocuments = async (
49 | collectionKey,
50 | objectsToAdd
51 | ) => {
52 | const collectionRef = firestore.collection(collectionKey);
53 |
54 | const batch = firestore.batch();
55 | objectsToAdd.forEach(obj => {
56 | const newDocRef = collectionRef.doc();
57 | batch.set(newDocRef, obj);
58 | });
59 |
60 | return await batch.commit();
61 | };
62 |
63 | export const convertCollectionsSnapshotToMap = collections => {
64 | const transformedCollection = collections.docs.map(doc => {
65 | const { title, items } = doc.data();
66 |
67 | return {
68 | routeName: encodeURI(title.toLowerCase()),
69 | id: doc.id,
70 | title,
71 | items
72 | };
73 | });
74 | return transformedCollection.reduce((accumulator, collection) => {
75 | accumulator[collection.title.toLowerCase()] = collection;
76 | return accumulator;
77 | }, {});
78 | };
79 |
80 | firebase.initializeApp(config);
81 |
82 | export const auth = firebase.auth();
83 | export const firestore = firebase.firestore();
84 |
85 | const provider = new firebase.auth.GoogleAuthProvider();
86 |
87 | provider.setCustomParameters({
88 | prompt: 'select_account'
89 | });
90 |
91 | export const signInWithGoogle = () => auth.signInWithPopup(provider);
92 |
93 | export default firebase;
94 |
--------------------------------------------------------------------------------
/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 'bootstrap/dist/css/bootstrap.css';
2 | import React from 'react';
3 | import ReactDOM from 'react-dom';
4 | import './index.css';
5 | import {Provider} from "react-redux"
6 | import {BrowserRouter} from "react-router-dom"
7 | import store from "./redux/store";
8 | import App from './App';
9 |
10 | import * as serviceWorker from './serviceWorker';
11 |
12 | ReactDOM.render(
13 |
14 |
15 |
16 |
17 |
18 |
19 | ,
20 | document.getElementById('root')
21 | );
22 |
23 | // If you want your app to work offline and load faster, you can change
24 | // unregister() to register() below. Note this comes with some pitfalls.
25 | // Learn more about service workers: https://bit.ly/CRA-PWA
26 | serviceWorker.unregister();
27 |
--------------------------------------------------------------------------------
/src/logo.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/src/pages/Chat/Chat.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import {connect} from "react-redux"
3 | import ChatroomList from "./components/ChatroomList/ChatroomList";
4 | import ChatroomWindow from "./components/ChatroomWindow/ChatroomWindow";
5 | import {fetchChatRooms} from "../../redux/chatroom/chatroom.actions";
6 |
7 | const Chat = ({fetchChatRooms,chatRooms}) => {
8 | React.useEffect(() => {
9 | fetchChatRooms()
10 | },[fetchChatRooms])
11 | return (
12 |
13 |
14 |
15 |
16 | );
17 | };
18 |
19 | const mapStateToProps = state => ({
20 | chatRooms: state.chatRooms.chatRooms
21 | })
22 |
23 | const mapDispatchToProps = dispatch => ({
24 | fetchChatRooms: () => dispatch(fetchChatRooms())
25 | })
26 |
27 | export default connect(mapStateToProps,mapDispatchToProps)(Chat);
28 |
--------------------------------------------------------------------------------
/src/pages/Chat/components/ChatInput/ChatInput.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import {connect} from 'react-redux';
3 | import {toastr} from 'react-redux-toastr'
4 | import "./ChatInput.scss";
5 | import {sendMessage} from "../../../../firebase/firebase.utils";
6 |
7 | class ChatInput extends React.Component{
8 | state = {
9 | message: '',
10 | inProgress: false
11 | };
12 |
13 | onSendMessage = (event) => {
14 | if ((event.keyCode === 13 || event.type === 'click') && this.state.message.trim() && !this.state.inProgress) {
15 | this.setState({
16 | ...this.state,
17 | inProgress: true
18 | });
19 | const chatroomId = this.props.selectedChatroom.id;
20 | const messageData = {
21 | message: this.state.message,
22 | createdAt: new Date(),
23 | sender: {
24 | email: this.props.currentUser.email,
25 | firstName: this.props.currentUser.firstName,
26 | lastName: this.props.currentUser.lastName,
27 | id: this.props.currentUser.id,
28 | photoUrl: this.props.currentUser.photoUrl
29 | }
30 | };
31 |
32 | sendMessage(chatroomId, messageData)
33 | .then(result => {
34 | }).catch(err => {
35 | toastr.error(
36 | 'Error!',
37 | err.message
38 | )
39 | }).finally(() => {
40 | this.setState( {
41 | message: '',
42 | inProgress: false
43 | });
44 | })
45 | }
46 |
47 | };
48 |
49 | handleChange = (e) => {
50 | this.setState({
51 | ...this.state,
52 | message: e.target.value
53 | }
54 | );
55 | };
56 |
57 | render() {
58 | return (
59 |
60 |
61 |
67 |
68 | Enter
69 |
70 |
71 |
72 | );
73 | }
74 | };
75 |
76 | export default connect(
77 | (state) => ({
78 | selectedChatroom: state.chatRooms.selectedChatroom,
79 | currentUser: state.user.currentUser
80 | })
81 | )(ChatInput);
82 |
--------------------------------------------------------------------------------
/src/pages/Chat/components/ChatInput/ChatInput.scss:
--------------------------------------------------------------------------------
1 | @import "../../../../styles/variables";
2 |
3 | .new-message-wrapper {
4 | margin-top: auto ;
5 | .input-group {
6 | align-self: flex-end;
7 |
8 | .form-control {
9 | border-radius: 0;
10 | border: 0;
11 | background-color: $light-grey;
12 |
13 | &:focus {
14 | outline: 0;
15 | box-shadow: none;
16 | }
17 | }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/pages/Chat/components/ChatMessage/ChatMessage.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import "./ChatMessage.scss"
3 | import {connect} from "react-redux";
4 | import {formatDate} from "../../../../utils/utils";
5 |
6 | const ChatMessage = ({messagesByUsers}) => {
7 | return (
8 | messagesByUsers && messagesByUsers.map(m => (
9 |
10 |
11 |
12 |
13 |
14 |
15 | {m.sender.firstName} {m.sender.lastName}
16 |
17 |
18 | {
19 | m.messages.map(
20 | me => (
21 | (
22 |
23 | {me.message} {formatDate(me.createdAt.toDate())}
24 |
25 | )
26 | )
27 | )
28 | }
29 |
30 |
31 |
32 | ))
33 | );
34 | };
35 |
36 | export default connect(
37 | (state) => ({
38 | messagesByUsers: state.chatRooms.messagesByUsers
39 | })
40 | )(ChatMessage);
41 |
--------------------------------------------------------------------------------
/src/pages/Chat/components/ChatMessage/ChatMessage.scss:
--------------------------------------------------------------------------------
1 | @import "../../../../styles/variables";
2 |
3 | .chat-message {
4 | padding: 1.5em;
5 |
6 | .image-wrapper {
7 | margin-right: 1em;
8 | height: 50px;
9 | width: 50px;
10 |
11 | img {
12 | height: 50px;
13 | width: 50px;
14 | }
15 | }
16 | .name {
17 | text-decoration: underline;
18 | font-weight: 600;
19 | }
20 | .timestamp {
21 | margin-bottom: 1.5em;
22 | color: darken($light-grey, 15%);
23 | }
24 | .message {
25 | font-size: 1.2em;
26 | display: flex;
27 | flex-flow: column-reverse;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/pages/Chat/components/ChatroomList/ChatroomList.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import {connect} from "react-redux"
3 | import {setChatRoom} from "../../../../redux/chatroom/chatroom.actions"
4 | import Spinner from "../../../../components/Spinner/Spinner";
5 | import './ChatroomList.scss'
6 |
7 | const ChatroomList = ({chatrooms, setChatRoom}) => {
8 | return (
9 | <>
10 | {
11 | chatrooms ?
12 |
13 | {
14 | chatrooms.map(c => (
15 |
24 | ))
25 | }
26 |
:
27 |
28 | }
29 | >
30 | );
31 | };
32 |
33 | const mapStateToProps = state => ({
34 | selectedChatroom: state.chatRooms.selectedChatroom
35 | })
36 |
37 | const mapDispatchToProps = dispatch => ({
38 | setChatRoom: (channel) => dispatch(setChatRoom(channel))
39 | })
40 |
41 | export default connect(mapStateToProps,mapDispatchToProps)(ChatroomList);
42 |
--------------------------------------------------------------------------------
/src/pages/Chat/components/ChatroomList/ChatroomList.scss:
--------------------------------------------------------------------------------
1 | @import "../../../../styles/variables";
2 |
3 | .chatroom-list {
4 | border-right: 2px solid $light-grey;
5 | overflow-y: scroll;
6 |
7 | .chatroom-list-item {
8 | border-bottom: 1px solid $light-grey;
9 | padding: 1em;
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/src/pages/Chat/components/ChatroomTitleBar/ChatroomTitleBar.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import "./ChatroomTitleBar.scss"
3 |
4 | const ChatroomTitleBar = ({title}) => {
5 | return (
6 |
7 |
{title}
8 |
9 | );
10 | };
11 |
12 | export default ChatroomTitleBar;
13 |
--------------------------------------------------------------------------------
/src/pages/Chat/components/ChatroomTitleBar/ChatroomTitleBar.scss:
--------------------------------------------------------------------------------
1 | @import "../../../../styles/variables";
2 |
3 | .room-title {
4 | padding: 1em 1em 1em 2em;
5 | border-bottom: 2px solid $grey;
6 | }
7 |
--------------------------------------------------------------------------------
/src/pages/Chat/components/ChatroomWindow/ChatroomWindow.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { connect } from 'react-redux'
3 | import ChatroomTitleBar from "../ChatroomTitleBar/ChatroomTitleBar";
4 | import {fetchMessagesAsync} from "../../../../redux/chatroom/chatroom.actions";
5 | import ChatMessage from "../ChatMessage/ChatMessage";
6 | import ChatInput from "../ChatInput/ChatInput";
7 | import "./ChatroomWindow.scss"
8 |
9 | const NoChatRoom = (
10 |
11 |
12 | Select a Room
13 |
14 |
15 | );
16 |
17 |
18 | class ChatroomWindow extends React.Component {
19 | scrollContainer = React.createRef();
20 |
21 |
22 | componentDidUpdate(prevProps) {
23 | if (this.props.selectedChatroom && this.props.selectedChatroom !== prevProps.selectedChatroom) {
24 | this.props.fetchMessagesAsync();
25 | }
26 |
27 | if (this.scrollContainer.current && this.props.messages) {
28 | setTimeout(() => {
29 | this.scrollContainer.current.scrollTop = this.scrollContainer.current.scrollHeight;
30 | }, 0)
31 | }
32 | }
33 |
34 | render() {
35 | return (
36 |
37 | {
38 | this.props.selectedChatroom ?
39 |
40 |
41 |
42 |
43 |
44 |
45 |
:
46 | NoChatRoom
47 | }
48 |
49 | );
50 | }
51 | };
52 |
53 | const mapDispatchToProps = dispatch => ({
54 | fetchMessagesAsync: () => dispatch(fetchMessagesAsync())
55 | })
56 |
57 | export default connect(
58 | (state) => (
59 | {
60 | selectedChatroom: state.chatRooms.selectedChatroom,
61 | messages: state.chatRooms.messages,
62 | messagesByUsers: state.chatRooms.messagesByUsers
63 | }
64 | ),mapDispatchToProps
65 | )(ChatroomWindow);
66 |
--------------------------------------------------------------------------------
/src/pages/Chat/components/ChatroomWindow/ChatroomWindow.scss:
--------------------------------------------------------------------------------
1 | @import "../../../../styles/variables";
2 |
3 | .message-wrapper {
4 | overflow-y: scroll;
5 | height: 100%;
6 | display: flex;
7 | flex-direction: column-reverse;
8 | }
9 |
10 | .select-room {
11 | .select-room-message {
12 | width: 30%;
13 | height: 5%;
14 | margin-bottom: 10%;
15 | border: 2px solid $gold;
16 | display: flex;
17 | justify-content: center;
18 | align-items: center;
19 | font-size: 1.2em;
20 | }
21 | }
22 |
23 | .chatroom-window {
24 | display: flex;
25 | flex-flow: column;
26 | width: 100%;
27 | }
28 |
--------------------------------------------------------------------------------
/src/pages/EditProfile/EditProfile.js:
--------------------------------------------------------------------------------
1 | import React, {Component} from 'react';
2 | import {connect} from "react-redux";
3 | import {withRouter} from "react-router-dom"
4 | import {toastr} from 'react-redux-toastr'
5 | import {firestore, imageUpload} from "../../firebase/firebase.utils";
6 |
7 | import "./EditProfile.scss"
8 |
9 | class EditProfile extends Component {
10 | state = {
11 | firstName: this.props.user.firstName,
12 | lastName: this.props.user.lastName,
13 | quote: this.props.user.quote,
14 | bio: this.props.user.bio,
15 | photoUrl: this.props.user.photoUrl,
16 | isImageUploading: false,
17 | imageUploadedPercentage: 0
18 | };
19 |
20 | handleChange = e => {
21 | this.setState({[e.target.name]: e.target.value})
22 | };
23 |
24 | updateUser = () => {
25 | const {id} = this.props.user;
26 | const updateRef = firestore.collection('users').doc(id);
27 | return updateRef
28 | .update({
29 | ...this.state
30 | })
31 | .then(this.props.history.push('/'))
32 | .catch(function (error) {
33 | toastr.error('Error updating document: ', error);
34 | });
35 | };
36 |
37 | uploadImage = (e) => {
38 | const file = e.target.files[0];
39 | const filePath = `${file.name}_${this.props.user.id}`;
40 | const uploadTask = imageUpload(file, filePath);
41 |
42 | this.setState({
43 | isImageUploading: true
44 | })
45 |
46 | uploadTask.on('state_changed',
47 | (snapshot) => {
48 | // in proggress
49 | const progress = ((snapshot.bytesTransferred / snapshot.totalBytes) * 100).toFixed(2);
50 | this.setState({
51 | imageUploadedPercentage: progress
52 | });
53 | },
54 | (error) => {
55 | // error
56 | toastr.error('Error!', error.message);
57 | this.setState({
58 | isImageUploading: false
59 | })
60 | },
61 | () => {
62 | // completed
63 | uploadTask.snapshot.ref.getDownloadURL().then((downloadURL) => {
64 | this.setState({
65 | photoUrl: downloadURL,
66 | isImageUploading: false
67 | }, () => toastr.success('Success!', 'Image successfully uploaded'));
68 | })
69 | }
70 | )
71 | };
72 |
73 | render() {
74 | const {firstName, lastName, quote, bio, photoUrl} = this.state;
75 | return (
76 |
77 |
78 |
79 |
80 |
81 |
82 |
87 |
88 | {
89 | this.state.isImageUploading &&
90 |
91 |
93 |
{this.imageUploadedPercentage}%
99 |
100 |
101 |
102 | }
103 |
104 |
109 |
114 |
119 |
124 |
125 |
126 | Save Profile
127 |
128 |
129 |
);
130 | }
131 | }
132 |
133 | const mapStateToProps = (state) => {
134 | return {
135 | user: state.user.currentUser
136 | }
137 | };
138 |
139 | export default connect(mapStateToProps)(withRouter(EditProfile));
140 |
--------------------------------------------------------------------------------
/src/pages/EditProfile/EditProfile.scss:
--------------------------------------------------------------------------------
1 | @import '../../styles/variables';
2 |
3 | .no-photo {
4 | height: 150px;
5 | width: 150px;
6 | background: $grey;
7 | margin: 1em 0;
8 | color: white;
9 | border-radius: 50%;
10 | }
11 |
12 | .profile-pic {
13 | max-width: 150px;
14 | max-height: 150px;
15 | margin: 1em 0;
16 | }
17 |
18 | input, textarea {
19 | border: 2px solid $light-grey;
20 | border-radius: 5px;
21 | padding: .25em .5em;
22 | margin-bottom: 1em;
23 | width: 100%;
24 | font-weight: 200;
25 | }
26 |
--------------------------------------------------------------------------------
/src/pages/Login/Login.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import {Link} from "react-router-dom"
3 | import {toastr} from 'react-redux-toastr'
4 | import { auth } from '../../firebase/firebase.utils';
5 | import "./Login.scss"
6 |
7 | const Login = () => {
8 | const [email, setEmail] = React.useState('');
9 | const [password, setPassword] = React.useState('');
10 | const [error, setError] = React.useState("");
11 |
12 | const handleChangeEmail = e => {
13 | setEmail(e.target.value);
14 | };
15 | const handleChangePassword = e => {
16 | setPassword(e.target.value);
17 | };
18 |
19 | const handleSubmit = async e => {
20 | e.preventDefault();
21 | if(email === "" || password === ""){
22 | return setError('Please fill in all the blanks');
23 | }
24 | try {
25 | await auth.signInWithEmailAndPassword(email, password);
26 | setPassword('');
27 | setEmail('');
28 | } catch (error) {
29 | const message = error ? error.message : 'Can\'t login';
30 | toastr.error('Error!', message);
31 | }
32 | };
33 |
34 | return (
35 |
36 |
37 |
Login
38 |
48 |
Need an Account?
49 | {error.length ? (
50 |
{error}
51 | ) : null}
52 |
53 |
54 | );
55 | };
56 |
57 | export default Login;
58 |
--------------------------------------------------------------------------------
/src/pages/Login/Login.scss:
--------------------------------------------------------------------------------
1 | @import '../../styles/variables';
2 |
3 | h2 {
4 | color: $secondary;
5 | margin-bottom: 1em;
6 | }
7 |
8 | .form-wrapper {
9 | min-width: 40%;
10 | margin-bottom: 10%;
11 | border: 2px solid $light-grey;
12 | padding: 1em 2em;
13 | }
14 |
--------------------------------------------------------------------------------
/src/pages/Profile/Profile.js:
--------------------------------------------------------------------------------
1 | import React, {Component} from 'react';
2 | import {connect} from "react-redux"
3 | import "./Profile.scss"
4 | import {Link} from "react-router-dom";
5 | import Spinner from "../../components/Spinner/Spinner";
6 |
7 | const NoFoto = (
8 | No Photo
9 |
);
10 |
11 | class Profile extends Component {
12 |
13 |
14 | render() {
15 | const {photoUrl, firstName, lastName, quote, id,bio} = this.props.user;
16 | return (
17 | <>
18 | {
19 | this.props.user ?
20 |
21 |
22 | {
23 | photoUrl ?
24 | (
25 |
27 |
) : NoFoto
28 | }
29 |
30 |
31 |
32 | {firstName} {lastName}
33 |
34 |
35 |
36 |
37 |
38 |
39 | {quote}
40 |
41 |
42 |
43 |
44 |
45 |
46 | {bio}
47 |
48 |
49 |
50 |
51 | Edit Profile
52 |
53 |
54 |
:
55 |
56 | }
57 |
58 | >
59 | );
60 | }
61 | }
62 |
63 | const mapStateToProps = (state) => {
64 | return {
65 | user: state.user.currentUser
66 | }
67 | }
68 |
69 | export default connect(mapStateToProps, null)(Profile);
70 |
--------------------------------------------------------------------------------
/src/pages/Profile/Profile.scss:
--------------------------------------------------------------------------------
1 | @import '../../styles/variables';
2 |
3 | .no-photo {
4 | height: 150px;
5 | width: 150px;
6 | background: $grey;
7 | margin: 1em 0;
8 | color: white;
9 | border-radius: 50%;
10 | }
11 |
12 | .profile-pic {
13 | max-width: 150px;
14 | max-height: 150px;
15 | margin: 1em 0;
16 | }
17 |
18 | .name {
19 | font-size: 1.4em;
20 | font-weight: 200;
21 | }
22 |
23 | .quote {
24 | margin-bottom: 2em;
25 | }
26 |
27 | .bio {
28 | margin-bottom: 2em;
29 | font-weight: 200;
30 | }
31 |
--------------------------------------------------------------------------------
/src/pages/Signup/Signup.js:
--------------------------------------------------------------------------------
1 | import React, {Component} from 'react';
2 | import {Link} from "react-router-dom"
3 | import { auth, createUserProfileDocument } from '../../firebase/firebase.utils';
4 | import "./Signup.scss"
5 | import {toastr} from "react-redux-toastr";
6 |
7 | class Signup extends Component {
8 | constructor(props) {
9 | super(props);
10 | this.state = {
11 | firstName: "",
12 | lastName: "",
13 | email: "",
14 | password: "",
15 | confirmPassword:"",
16 | error: ""
17 | }
18 | }
19 |
20 | handleChange = (e) => {
21 | this.setState({[e.target.name] : e.target.value})
22 | };
23 |
24 | handleSubmit = async e => {
25 | e.preventDefault();
26 | const {firstName,email,password,lastName,confirmPassword} = this.state;
27 | if (
28 | firstName === '' ||
29 | lastName === '' ||
30 | email === '' ||
31 | password === '' ||
32 | confirmPassword === ""
33 |
34 | ) {
35 | return this.setState({error: 'Please fill in all the blanks'});
36 | } else if (password.length < 6 || confirmPassword.length < 6) {
37 | return this.setState({error: 'Please enter at least 6 characters...'});
38 | } else if (password !== confirmPassword) {
39 | return this.setState({error: 'Both passwords should match...'});
40 | } else {
41 | try {
42 | const {user} = await auth.createUserWithEmailAndPassword(
43 | email,
44 | password
45 | );
46 | await createUserProfileDocument(user, {
47 | firstName,
48 | lastName,
49 | // default avatar
50 | photoUrl: 'https://firebasestorage.googleapis.com/v0/b/chat-874ea.appspot.com/o/default-avatar.jpg?alt=media&token=e294ee8a-3a09-4225-a768-85bbc9988c22',
51 | quote: 'Quote is under construction...',
52 | bio: 'Bio is under construction...'
53 | });
54 | await user.updateProfile({
55 | displayName: firstName + " " + lastName,
56 | });
57 | this.setState({
58 | firstName: "",
59 | lastName: "",
60 | email: "",
61 | password: "",
62 | confirmPassword: ""
63 | })
64 | } catch (error) {
65 | const message = error ? error.message : 'Can\'t register';
66 | toastr.error('Error!', message);
67 | }
68 | }
69 | };
70 |
71 | render() {
72 | return (
73 |
74 |
75 |
Sign Up
76 |
134 |
Already have an Account?
135 | {this.state.error.length ? (
136 |
{this.state.error}
137 | ) : null}
138 |
139 |
140 | );
141 | }
142 | }
143 |
144 | export default Signup;
145 |
--------------------------------------------------------------------------------
/src/pages/Signup/Signup.scss:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/TheCoderDream/React-Chat-App-With-Redux-And-Firebase/3f137ea2d8f81760105b6ee9ca0be90a67314cdd/src/pages/Signup/Signup.scss
--------------------------------------------------------------------------------
/src/redux/chatroom/chatroom.actions.js:
--------------------------------------------------------------------------------
1 | import {firestore} from "../../firebase/firebase.utils";
2 |
3 | export const SET_CHAT_ROOM = 'SET_CHAT_ROOM';
4 | export const FETCH_COLLECTIONS_START = 'FETCH_COLLECTIONS_START';
5 | export const FETCHING_COLLECTIONS_SUCCESS = 'FETCHING_COLLECTIONS_SUCCESS';
6 | export const FETCHING_COLLECTIONS_FAILURE = 'FETCHING_COLLECTIONS_FAILURE';
7 | export const FETCHING_MESSAGES_SUCCESS = 'FETCHING_MESSAGES_SUCCESS';
8 |
9 | export const setChatRoom = (channel) => ({
10 | type: SET_CHAT_ROOM,
11 | payload:channel
12 | })
13 |
14 | export const fetchCollectionsStart = () => ({
15 | type: FETCH_COLLECTIONS_START
16 | });
17 |
18 | export const fetchCollectionsSuccess = collectionsMap => ({
19 | type: FETCHING_COLLECTIONS_SUCCESS,
20 | payload: collectionsMap
21 | });
22 |
23 | export const fetchCollectionsFailure = errorMessage => ({
24 | type: FETCHING_COLLECTIONS_FAILURE,
25 | payload: errorMessage
26 | });
27 |
28 | export const fetchMessagesSuccess = collectionsMap => ({
29 | type: FETCHING_MESSAGES_SUCCESS,
30 | payload: collectionsMap
31 | });
32 |
33 |
34 | export const fetchChatRooms = () => {
35 | return dispatch => {
36 | const chatRef = firestore.collection("chatrooms");
37 | dispatch(fetchCollectionsStart());
38 |
39 | chatRef.get().then(snapShot => {
40 | const collectionsMap = snapShot.docs.map(doc => {
41 | const data = doc.data();
42 | data.id = doc.id;
43 | return data;
44 | });
45 | dispatch(fetchCollectionsSuccess(collectionsMap))
46 | })
47 | .catch(error => dispatch(fetchCollectionsFailure(error.Message)));
48 |
49 |
50 | }
51 | };
52 |
53 | export const fetchMessagesAsync = () => {
54 | return (dispatch, getState) => {
55 | firestore.collection(`chatrooms/${getState().chatRooms.selectedChatroom.id}/messages`).orderBy("createdAt", "desc").onSnapshot(function(snapshot) {
56 | const collectionsMap = snapshot.docs.map(doc => {
57 | const data = doc.data();
58 | data.id = doc.id;
59 | return data
60 | }
61 | );
62 | dispatch(fetchMessagesSuccess(collectionsMap))
63 | })
64 | }
65 | };
66 |
--------------------------------------------------------------------------------
/src/redux/chatroom/chatroom.reducer.js:
--------------------------------------------------------------------------------
1 | import {
2 | SET_CHAT_ROOM,
3 | FETCH_COLLECTIONS_START,
4 | FETCHING_COLLECTIONS_FAILURE,
5 | FETCHING_COLLECTIONS_SUCCESS,
6 | FETCHING_MESSAGES_SUCCESS
7 | } from './chatroom.actions';
8 |
9 | const initialState = {
10 | chatRooms: null,
11 | selectedChatroom: null,
12 | selectedChatroomMessages: null,
13 | messages: null,
14 | messagesByUsers: null
15 | };
16 |
17 | export default (state = initialState, action) => {
18 | switch (action.type) {
19 | case FETCH_COLLECTIONS_START:
20 | return {
21 | ...state,
22 | };
23 | case FETCHING_COLLECTIONS_SUCCESS:
24 | return {
25 | ...state,
26 | chatRooms: action.payload
27 | };
28 | case FETCHING_COLLECTIONS_FAILURE:
29 | return {
30 | ...state,
31 | errorMessage: action.payload
32 | };
33 | case SET_CHAT_ROOM:
34 | return {
35 | ...state,
36 | selectedChatroom: action.payload
37 | };
38 | case FETCHING_MESSAGES_SUCCESS:
39 | return {
40 | ...state,
41 | messages: action.payload,
42 | messagesByUsers: groupMessagesByUser(action.payload)
43 | };
44 | default:
45 | return state
46 | }
47 | }
48 |
49 |
50 | function groupMessagesByUser(messages) {
51 | let result = [];
52 | let messageGroup = {sender: null, messages: []};
53 | for (let i = 0; i < messages.length; i++) {
54 | const prevMessage = messages[i -1];
55 | const currentMessage = messages[i];
56 | if (!prevMessage) {
57 | messageGroup.sender = currentMessage.sender;
58 | messageGroup.messages.push({
59 | createdAt: currentMessage.createdAt,
60 | message: currentMessage.message
61 | });
62 | if (i === messages.length -1 ) {
63 | result.push(messageGroup);
64 | }
65 | } else if (currentMessage.sender.id === prevMessage.sender.id ) {
66 | messageGroup.messages.push({
67 | createdAt: currentMessage.createdAt,
68 | message: currentMessage.message
69 | });
70 | if (i === messages.length -1 ) {
71 | result.push(messageGroup);
72 | }
73 | } else {
74 | result.push(messageGroup);
75 | messageGroup = {sender: null, messages: []};
76 | messageGroup.sender = currentMessage.sender;
77 | messageGroup.messages.push({
78 | createdAt: currentMessage.createdAt,
79 | message: currentMessage.message
80 | });
81 | }
82 | }
83 | return result;
84 | }
85 |
--------------------------------------------------------------------------------
/src/redux/rootReducer.js:
--------------------------------------------------------------------------------
1 | import {combineReducers} from "redux"
2 |
3 | import {reducer as toastrReducer} from 'react-redux-toastr'
4 | import userReducer from "./user/user.reducer";
5 | import chatroomReducer from './chatroom/chatroom.reducer'
6 |
7 | const rootReducer = combineReducers({
8 | user: userReducer,
9 | chatRooms: chatroomReducer,
10 | toastr: toastrReducer
11 | });
12 |
13 | export default rootReducer;
14 |
--------------------------------------------------------------------------------
/src/redux/store.js:
--------------------------------------------------------------------------------
1 | import {createStore, applyMiddleware} from "redux"
2 | import { composeWithDevTools } from 'redux-devtools-extension';
3 | import thunk from "redux-thunk"
4 | import rootReducer from "./rootReducer";
5 |
6 | const store = createStore(rootReducer,composeWithDevTools(
7 | applyMiddleware(thunk)));
8 |
9 | export default store;
10 |
--------------------------------------------------------------------------------
/src/redux/user/user.actions.js:
--------------------------------------------------------------------------------
1 | export const USER_LOADED = "USER_LOADED";
2 | export const CLEAR_USER = "CLEAR_USER";
3 |
4 | export const setCurrentUser = user => ({
5 | type: USER_LOADED,
6 | payload: user
7 | });
8 |
9 | export const clearUser = () => ({
10 | type: CLEAR_USER,
11 | });
12 |
--------------------------------------------------------------------------------
/src/redux/user/user.reducer.js:
--------------------------------------------------------------------------------
1 | import {
2 | USER_LOADED,
3 | CLEAR_USER
4 | } from './user.actions'
5 |
6 | const INITIAL_STATE = {
7 | currentUser: null,
8 | isAuthenticated: null,
9 | loading: true
10 | };
11 |
12 | const userReducer = (state = INITIAL_STATE, action) => {
13 | const { type, payload } = action;
14 | switch (type) {
15 | case USER_LOADED:
16 | return {
17 | ...state,
18 | currentUser: payload,
19 | loading: false
20 | };
21 | case CLEAR_USER:
22 | return {
23 | ...state,
24 | currentUser: null,
25 | loading: false,
26 | };
27 | default:
28 | return state;
29 | }
30 | };
31 | export default userReducer;
32 |
--------------------------------------------------------------------------------
/src/serviceWorker.js:
--------------------------------------------------------------------------------
1 | // This optional code is used to register a service worker.
2 | // register() is not called by default.
3 |
4 | // This lets the app load faster on subsequent visits in production, and gives
5 | // it offline capabilities. However, it also means that developers (and users)
6 | // will only see deployed updates on subsequent visits to a page, after all the
7 | // existing tabs open on the page have been closed, since previously cached
8 | // resources are updated in the background.
9 |
10 | // To learn more about the benefits of this model and instructions on how to
11 | // opt-in, read https://bit.ly/CRA-PWA
12 |
13 | const isLocalhost = Boolean(
14 | window.location.hostname === 'localhost' ||
15 | // [::1] is the IPv6 localhost address.
16 | window.location.hostname === '[::1]' ||
17 | // 127.0.0.0/8 are considered localhost for IPv4.
18 | window.location.hostname.match(
19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
20 | )
21 | );
22 |
23 | export function register(config) {
24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
25 | // The URL constructor is available in all browsers that support SW.
26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
27 | if (publicUrl.origin !== window.location.origin) {
28 | // Our service worker won't work if PUBLIC_URL is on a different origin
29 | // from what our page is served on. This might happen if a CDN is used to
30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374
31 | return;
32 | }
33 |
34 | window.addEventListener('load', () => {
35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
36 |
37 | if (isLocalhost) {
38 | // This is running on localhost. Let's check if a service worker still exists or not.
39 | checkValidServiceWorker(swUrl, config);
40 |
41 | // Add some additional logging to localhost, pointing developers to the
42 | // service worker/PWA documentation.
43 | navigator.serviceWorker.ready.then(() => {
44 | console.log(
45 | 'This web app is being served cache-first by a service ' +
46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA'
47 | );
48 | });
49 | } else {
50 | // Is not localhost. Just register service worker
51 | registerValidSW(swUrl, config);
52 | }
53 | });
54 | }
55 | }
56 |
57 | function registerValidSW(swUrl, config) {
58 | navigator.serviceWorker
59 | .register(swUrl)
60 | .then(registration => {
61 | registration.onupdatefound = () => {
62 | const installingWorker = registration.installing;
63 | if (installingWorker == null) {
64 | return;
65 | }
66 | installingWorker.onstatechange = () => {
67 | if (installingWorker.state === 'installed') {
68 | if (navigator.serviceWorker.controller) {
69 | // At this point, the updated precached content has been fetched,
70 | // but the previous service worker will still serve the older
71 | // content until all client tabs are closed.
72 | console.log(
73 | 'New content is available and will be used when all ' +
74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
75 | );
76 |
77 | // Execute callback
78 | if (config && config.onUpdate) {
79 | config.onUpdate(registration);
80 | }
81 | } else {
82 | // At this point, everything has been precached.
83 | // It's the perfect time to display a
84 | // "Content is cached for offline use." message.
85 | console.log('Content is cached for offline use.');
86 |
87 | // Execute callback
88 | if (config && config.onSuccess) {
89 | config.onSuccess(registration);
90 | }
91 | }
92 | }
93 | };
94 | };
95 | })
96 | .catch(error => {
97 | console.error('Error during service worker registration:', error);
98 | });
99 | }
100 |
101 | function checkValidServiceWorker(swUrl, config) {
102 | // Check if the service worker can be found. If it can't reload the page.
103 | fetch(swUrl, {
104 | headers: { 'Service-Worker': 'script' },
105 | })
106 | .then(response => {
107 | // Ensure service worker exists, and that we really are getting a JS file.
108 | const contentType = response.headers.get('content-type');
109 | if (
110 | response.status === 404 ||
111 | (contentType != null && contentType.indexOf('javascript') === -1)
112 | ) {
113 | // No service worker found. Probably a different app. Reload the page.
114 | navigator.serviceWorker.ready.then(registration => {
115 | registration.unregister().then(() => {
116 | window.location.reload();
117 | });
118 | });
119 | } else {
120 | // Service worker found. Proceed as normal.
121 | registerValidSW(swUrl, config);
122 | }
123 | })
124 | .catch(() => {
125 | console.log(
126 | 'No internet connection found. App is running in offline mode.'
127 | );
128 | });
129 | }
130 |
131 | export function unregister() {
132 | if ('serviceWorker' in navigator) {
133 | navigator.serviceWorker.ready
134 | .then(registration => {
135 | registration.unregister();
136 | })
137 | .catch(error => {
138 | console.error(error.message);
139 | });
140 | }
141 | }
142 |
--------------------------------------------------------------------------------
/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/extend-expect';
6 |
--------------------------------------------------------------------------------
/src/styles/styles.scss:
--------------------------------------------------------------------------------
1 | /* You can add global styles to this file, and also import other style files */
2 | @import 'variables';
3 | @import '../../node_modules/bootstrap/scss/bootstrap';
4 | @import 'react-redux-toastr/src/styles/index';
5 |
6 | body {
7 | color: $secondary;
8 | }
9 |
10 | .container-wrapper {
11 | height: calc(100vh - 80px) !important;
12 | }
13 |
14 | .navbar {
15 | height: 80px;
16 | }
17 |
18 | button {
19 | width: 100%;
20 | &.btn {
21 | border-radius: 0;
22 | &:focus {
23 | box-shadow: none;
24 | }
25 | }
26 | }
27 |
28 | @mixin scrollbar($width: 6px, $bg: transparent, $margin: 0, $thumbBorderRadius: 6px, $thumbBg: rgba(0, 0, 0, .3)) {
29 | ::-webkit-scrollbar {
30 | width: $width;
31 | height: $width;
32 | background: $bg;
33 | margin: $margin;
34 | cursor: pointer;
35 | }
36 | ::-webkit-scrollbar-thumb {
37 | border-radius: $thumbBorderRadius;
38 | background: $thumbBg;
39 | }
40 | }
41 |
42 | @include scrollbar;
43 |
--------------------------------------------------------------------------------
/src/styles/variables.scss:
--------------------------------------------------------------------------------
1 | $primary: #328CC1;
2 | $secondary: #0B3C5D;
3 | $gold: #D9B310;
4 | $light-grey: #efefef;
5 | $grey: darken($light-grey, 30%);
6 | $black: #1D2731;
7 |
8 | $navbar-height: 80px;
--------------------------------------------------------------------------------
/src/utils/utils.js:
--------------------------------------------------------------------------------
1 | export function formatDate(date) {
2 | const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
3 | const hours = date.getHours();
4 | const minutes = date.getMinutes();
5 | const seconds = date.getSeconds();
6 | const paddedSeconds = seconds < 10 ? '0' + seconds: seconds;
7 | const ampm = hours >= 12 ? 'PM' : 'AM';
8 | return `
9 | ${months[date.getMonth()]} ${date.getDate()}, ${date.getFullYear()}, ${hours}:${minutes}:${paddedSeconds} ${ampm}
10 | `
11 | }
12 |
--------------------------------------------------------------------------------