Guest User

Untitled

a guest
Nov 12th, 2018
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.15 KB | None | 0 0
  1. // Establish a Socket.io connection
  2. const socket = io();
  3. // Initialize our Feathers client application through Socket.io
  4. // with hooks and authentication.
  5. const client = feathers();
  6.  
  7. client.configure(feathers.socketio(socket));
  8. // Use localStorage to store our login token
  9. client.configure(feathers.authentication({
  10. storage: window.localStorage
  11. }));
  12.  
  13. // Login screen
  14. const loginHTML = `<main class="login container">
  15. <div id="particle">
  16. <div class="row">
  17. <div class="col-12 col-6-tablet push-3-tablet text-center heading">
  18. <br><br><br><br>
  19. <h1 class="Georgia">muChat</h1>
  20. <br>
  21. </div>
  22. </div>
  23. <div class="row">
  24. <div class="col-12 col-6-tablet push-3-tablet col-4-desktop push-4-desktop">
  25. <form class="form">
  26. <fieldset>
  27. <input class="block" type="email" name="email" placeholder="Username">
  28. </fieldset>
  29.  
  30. <fieldset>
  31. <input class="block" type="password" name="password" placeholder="Password">
  32. </fieldset>
  33.  
  34. <fieldset>
  35. <input type="file" id="customAvatar">
  36. </fieldset>
  37.  
  38. <button type="button" id="login" class="button button-primary block signup">
  39. Log in
  40. </button>
  41.  
  42. <button type="button" id="signup" class="button button-primary block signup">
  43. Sign up
  44. </button>
  45. </form>
  46. </div>
  47. </div>
  48. </div>
  49. </main>`;
  50.  
  51. // Chat base HTML (without user list and messages)
  52. const chatHTML = `<main class="flex flex-column">
  53. <header class="title-bar flex flex-row flex-center">
  54. <div class="title-wrapper block center-element">
  55. <img class="logo" src="icon.png" height="50" width="50"
  56. alt="muChat icon">
  57. <span class="title">muChat</span>
  58. </div>
  59. </header>
  60.  
  61. <div class="flex flex-row flex-1 clear">
  62. <aside class="sidebar col col-3 flex flex-column flex-space-between">
  63. <header class="flex flex-row flex-center">
  64. <h4 class="font-300 text-center">
  65. <span class="font-600 online-count">0</span> users
  66. </h4>
  67. </header>
  68.  
  69. <ul class="flex flex-column flex-1 list-unstyled user-list"></ul>
  70. <footer class="flex flex-row flex-center">
  71. <a href="#" id="logout" class="button button-primary">
  72. Sign Out
  73. </a>
  74. </footer>
  75. </aside>
  76.  
  77. <div class="flex flex-column col col-9">
  78. <main class="chat flex flex-column flex-1 clear"></main>
  79.  
  80. <form class="flex flex-row flex-space-between" id="send-message">
  81. <input type="text" name="text" class="flex flex-1">
  82. <button class="button-primary" type="submit">Send</button>
  83. <button class="button-primary" onclick="addMessage('x',1)">Reset</button>
  84. </form>
  85. </div>
  86. </div>
  87. </main>`;
  88.  
  89. // Add a new user to the list
  90. const addUser = user => {
  91. const userList = document.querySelector('.user-list');
  92.  
  93. if(userList) {
  94. // Add the user to the list
  95. userList.insertAdjacentHTML('beforeend', `<li>
  96. <a class="block relative" href="#">
  97. <img src="${user.avatar}" alt="" class="avatar">
  98. <span class="absolute username">${user.email}</span>
  99. </a>
  100. </li>`);
  101.  
  102. // Update the number of users
  103. const userCount = document.querySelectorAll('.user-list li').length;
  104.  
  105. document.querySelector('.online-count').innerHTML = userCount;
  106. }
  107. };
  108.  
  109. // Renders a new message and finds the user that belongs to the message
  110. const addMessage = (message, x) => {
  111. // Find the user belonging to this message or use the anonymous user if not found
  112. const { user = {} } = message;
  113. const chat = document.querySelector('.chat');
  114. // Escape HTML
  115. if(x==1) chat.innerHTML = "";
  116. else {
  117. const text = message.text
  118. .replace(/&/g, '&')
  119. .replace(/</g, '<').replace(/>/g, '>');
  120.  
  121. if(chat) {
  122. chat.insertAdjacentHTML( 'beforeend', `<div class="message flex flex-row">
  123. <img src="${user.avatar}" alt="${user.email}" class="avatar">
  124. <div class="message-wrapper">
  125. <p class="message-header">
  126. <span class="username font-600">${user.email}</span>
  127. <span class="sent-date font-300">${moment(message.createdAt).format('MMM Do, hh:mm:ss')}</span>
  128. </p>
  129. <p class="message-content font-300">${text}</p>
  130. </div>
  131. </div>`);
  132.  
  133. chat.scrollTop = chat.scrollHeight - chat.clientHeight;
  134. }
  135. }
  136. };
  137.  
  138. // Show the login page
  139. const showLogin = (error = {}) => {
  140. if(document.querySelectorAll('.login').length) {
  141. document.querySelector('.heading').insertAdjacentHTML('beforeend', `<p>There was an error: ${error.message}</p>`);
  142. } else {
  143. document.getElementById('app').innerHTML = loginHTML;
  144. }
  145. };
  146.  
  147. // Shows the chat page
  148. const showChat = async (x) => {
  149. if(x==1) document.getElementById('app').innerHTML = "";
  150. else document.getElementById('app').innerHTML = chatHTML;
  151.  
  152. // Find the latest 25 messages. They will come with the newest first
  153. // which is why we have to reverse before adding them
  154. const messages = await client.service('messages').find({
  155. query: {
  156. $sort: { createdAt: -1 },
  157. $limit: 25
  158. }
  159. });
  160.  
  161. // We want to show the newest message last
  162. messages.data.reverse().forEach(addMessage);
  163.  
  164. // Find all users
  165. const users = await client.service('users').find();
  166.  
  167. users.data.forEach(addUser);
  168. };
  169.  
  170. // Retrieve email/password object from the login/signup page
  171. const getCredentials = () => {
  172. const user = {
  173. email: document.querySelector('[name="email"]').value,
  174. password: document.querySelector('[name="password"]').value
  175. };
  176.  
  177. return user;
  178. };
  179.  
  180. // Log in either using the given email/password or the token from storage
  181. const login = async credentials => {
  182. try {
  183. if(!credentials) {
  184. // Try to authenticate using the JWT from localStorage
  185. await client.authenticate();
  186. } else {
  187. // If we get login information, add the strategy we want to use for login
  188. const payload = Object.assign({ strategy: 'local' }, credentials);
  189.  
  190. await client.authenticate(payload);
  191. }
  192.  
  193. // If successful, show the chat page
  194. showChat();
  195. } catch(error) {
  196. // If we got an error, show the login page
  197. showLogin(error);
  198. }
  199. };
  200.  
  201. document.addEventListener('click', async ev => {
  202. switch(ev.target.id) {
  203. case 'signup': {
  204. // For signup, create a new user and then log them in
  205. const credentials = getCredentials();
  206.  
  207. // First create the user
  208. await client.service('users').create(credentials);
  209. // If successful log them in
  210. await login(credentials);
  211.  
  212. break;
  213. }
  214. case 'login': {
  215. const user = getCredentials();
  216.  
  217. await login(user);
  218.  
  219. break;
  220. }
  221. case 'logout': {
  222. await client.logout();
  223.  
  224. document.getElementById('app').innerHTML = loginHTML;
  225.  
  226. break;
  227. }
  228. }
  229. });
  230.  
  231. document.addEventListener('submit', async ev => {
  232. if(ev.target.id === 'send-message') {
  233. // This is the message text input field
  234. const input = document.querySelector('[name="text"]');
  235.  
  236. ev.preventDefault();
  237.  
  238. // Create a new message and then clear the input field
  239. await client.service('messages').create({
  240. text: input.value
  241. });
  242.  
  243. input.value = '';
  244. }
  245. });
  246.  
  247. // Listen to created events and add the new message in real-time
  248. client.service('messages').on('created', addMessage);
  249.  
  250. // We will also see when new users get created in real-time
  251. client.service('users').on('created', addUser);
  252.  
  253. login();
Add Comment
Please, Sign In to add comment