You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Chat.js 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. /* global APP, $ */
  2. import { processReplacements, linkify } from './Replacement';
  3. import CommandsProcessor from './Commands';
  4. import VideoLayout from '../../videolayout/VideoLayout';
  5. import UIUtil from '../../util/UIUtil';
  6. import UIEvents from '../../../../service/UI/UIEvents';
  7. import { smileys } from './smileys';
  8. import { addMessage, markAllRead } from '../../../../react/features/chat';
  9. import {
  10. dockToolbox,
  11. getToolboxHeight,
  12. setSubject
  13. } from '../../../../react/features/toolbox';
  14. let unreadMessages = 0;
  15. const sidePanelsContainerId = 'sideToolbarContainer';
  16. const htmlStr = `
  17. <div id="chat_container" class="sideToolbarContainer__inner">
  18. <div id="nickname">
  19. <span data-i18n="chat.nickname.title"></span>
  20. <form>
  21. <input type='text'
  22. class="input-control" id="nickinput" autofocus
  23. data-i18n="[placeholder]chat.nickname.popover">
  24. </form>
  25. </div>
  26. <div id="chatconversation"></div>
  27. <textarea id="usermsg" autofocus
  28. data-i18n="[placeholder]chat.messagebox"></textarea>
  29. <div id="smileysarea">
  30. <div id="smileys">
  31. <img src="images/smile.svg"/>
  32. </div>
  33. </div>
  34. </div>`;
  35. /**
  36. *
  37. */
  38. function initHTML() {
  39. $(`#${sidePanelsContainerId}`)
  40. .append(htmlStr);
  41. }
  42. /**
  43. * The container id, which is and the element id.
  44. */
  45. const CHAT_CONTAINER_ID = 'chat_container';
  46. /**
  47. * Updates visual notification, indicating that a message has arrived.
  48. */
  49. function updateVisualNotification() {
  50. // XXX The rewrite of the toolbar in React delayed the availability of the
  51. // element unreadMessages. In order to work around the delay, I introduced
  52. // and utilized unreadMsgSelector in addition to unreadMsgElement.
  53. const unreadMsgSelector = $('#unreadMessages');
  54. const unreadMsgElement
  55. = unreadMsgSelector.length > 0 ? unreadMsgSelector[0] : undefined;
  56. if (unreadMessages && unreadMsgElement) {
  57. unreadMsgElement.innerHTML = unreadMessages.toString();
  58. APP.store.dispatch(dockToolbox(true));
  59. const chatButtonElement
  60. = document.getElementById('toolbar_button_chat');
  61. const leftIndent
  62. = (UIUtil.getTextWidth(chatButtonElement)
  63. - UIUtil.getTextWidth(unreadMsgElement)) / 2;
  64. const topIndent
  65. = ((UIUtil.getTextHeight(chatButtonElement)
  66. - UIUtil.getTextHeight(unreadMsgElement)) / 2) - 5;
  67. unreadMsgElement.setAttribute(
  68. 'style',
  69. `top:${topIndent}; left:${leftIndent};`);
  70. } else {
  71. unreadMsgSelector.html('');
  72. }
  73. if (unreadMsgElement) {
  74. unreadMsgSelector.parent()[unreadMessages > 0 ? 'show' : 'hide']();
  75. }
  76. }
  77. /**
  78. * Returns the current time in the format it is shown to the user
  79. * @returns {string}
  80. */
  81. function getCurrentTime(stamp) {
  82. const now = stamp ? new Date(stamp) : new Date();
  83. let hour = now.getHours();
  84. let minute = now.getMinutes();
  85. let second = now.getSeconds();
  86. if (hour.toString().length === 1) {
  87. hour = `0${hour}`;
  88. }
  89. if (minute.toString().length === 1) {
  90. minute = `0${minute}`;
  91. }
  92. if (second.toString().length === 1) {
  93. second = `0${second}`;
  94. }
  95. return `${hour}:${minute}:${second}`;
  96. }
  97. /**
  98. *
  99. */
  100. function toggleSmileys() {
  101. const smileys = $('#smileysContainer'); // eslint-disable-line no-shadow
  102. smileys.slideToggle();
  103. $('#usermsg').focus();
  104. }
  105. /**
  106. *
  107. */
  108. function addClickFunction(smiley, number) {
  109. smiley.onclick = function addSmileyToMessage() {
  110. const usermsg = $('#usermsg');
  111. let message = usermsg.val();
  112. message += smileys[`smiley${number}`];
  113. usermsg.val(message);
  114. usermsg.get(0).setSelectionRange(message.length, message.length);
  115. toggleSmileys();
  116. usermsg.focus();
  117. };
  118. }
  119. /**
  120. * Adds the smileys container to the chat
  121. */
  122. function addSmileys() {
  123. const smileysContainer = document.createElement('div');
  124. smileysContainer.id = 'smileysContainer';
  125. for (let i = 1; i <= 21; i++) {
  126. const smileyContainer = document.createElement('div');
  127. smileyContainer.id = `smiley${i}`;
  128. smileyContainer.className = 'smileyContainer';
  129. const smiley = document.createElement('img');
  130. smiley.src = `images/smileys/smiley${i}.svg`;
  131. smiley.className = 'smiley';
  132. addClickFunction(smiley, i);
  133. smileyContainer.appendChild(smiley);
  134. smileysContainer.appendChild(smileyContainer);
  135. }
  136. $('#chat_container').append(smileysContainer);
  137. }
  138. /**
  139. * Resizes the chat conversation.
  140. */
  141. function resizeChatConversation() {
  142. // FIXME: this function can all be done with CSS. If Chat is ever rewritten,
  143. // do not copy over this logic.
  144. const msgareaHeight = $('#usermsg').outerHeight();
  145. const chatspace = $(`#${CHAT_CONTAINER_ID}`);
  146. const width = chatspace.width();
  147. const chat = $('#chatconversation');
  148. const smileys = $('#smileysarea'); // eslint-disable-line no-shadow
  149. smileys.height(msgareaHeight);
  150. $('#smileys').css('bottom', (msgareaHeight - 26) / 2);
  151. $('#smileysContainer').css('bottom', msgareaHeight);
  152. chat.width(width - 10);
  153. const maybeAMagicNumberForPaddingAndMargin = 100;
  154. const offset = maybeAMagicNumberForPaddingAndMargin
  155. + msgareaHeight + getToolboxHeight();
  156. chat.height(window.innerHeight - offset);
  157. }
  158. /**
  159. * Focus input after 400 ms
  160. * Found input by id
  161. *
  162. * @param id {string} input id
  163. */
  164. function deferredFocus(id) {
  165. setTimeout(() => $(`#${id}`).focus(), 400);
  166. }
  167. /**
  168. * Chat related user interface.
  169. */
  170. const Chat = {
  171. /**
  172. * Initializes chat related interface.
  173. */
  174. init(eventEmitter) {
  175. initHTML();
  176. if (APP.conference.getLocalDisplayName()) {
  177. Chat.setChatConversationMode(true);
  178. }
  179. $('#smileys').click(() => {
  180. Chat.toggleSmileys();
  181. });
  182. $('#nickinput').keydown(function(event) {
  183. if (event.keyCode === 13) {
  184. event.preventDefault();
  185. const val = this.value; // eslint-disable-line no-invalid-this
  186. this.value = '';// eslint-disable-line no-invalid-this
  187. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, val);
  188. deferredFocus('usermsg');
  189. }
  190. });
  191. const usermsg = $('#usermsg');
  192. usermsg.keydown(function(event) {
  193. if (event.keyCode === 13) {
  194. event.preventDefault();
  195. const value = this.value; // eslint-disable-line no-invalid-this
  196. usermsg.val('').trigger('autosize.resize');
  197. this.focus();// eslint-disable-line no-invalid-this
  198. const command = new CommandsProcessor(value, eventEmitter);
  199. if (command.isCommand()) {
  200. command.processCommand();
  201. } else {
  202. const message = UIUtil.escapeHtml(value);
  203. eventEmitter.emit(UIEvents.MESSAGE_CREATED, message);
  204. }
  205. }
  206. });
  207. const onTextAreaResize = function() {
  208. resizeChatConversation();
  209. Chat.scrollChatToBottom();
  210. };
  211. usermsg.autosize({ callback: onTextAreaResize });
  212. eventEmitter.on(UIEvents.SIDE_TOOLBAR_CONTAINER_TOGGLED,
  213. (containerId, isVisible) => {
  214. if (containerId !== CHAT_CONTAINER_ID || !isVisible) {
  215. return;
  216. }
  217. unreadMessages = 0;
  218. APP.store.dispatch(markAllRead());
  219. updateVisualNotification();
  220. // Undock the toolbar when the chat is shown and if we're in a
  221. // video mode.
  222. if (VideoLayout.isLargeVideoVisible()) {
  223. APP.store.dispatch(dockToolbox(false));
  224. }
  225. // if we are in conversation mode focus on the text input
  226. // if we are not, focus on the display name input
  227. deferredFocus(
  228. APP.conference.getLocalDisplayName()
  229. ? 'usermsg'
  230. : 'nickinput');
  231. });
  232. addSmileys();
  233. updateVisualNotification();
  234. },
  235. /**
  236. * Appends the given message to the chat conversation.
  237. */
  238. // eslint-disable-next-line max-params
  239. updateChatConversation(id, displayName, message, stamp) {
  240. const isFromLocalParticipant = APP.conference.isLocalId(id);
  241. let divClassName = '';
  242. if (isFromLocalParticipant) {
  243. divClassName = 'localuser';
  244. } else {
  245. divClassName = 'remoteuser';
  246. if (!Chat.isVisible()) {
  247. unreadMessages++;
  248. updateVisualNotification();
  249. }
  250. }
  251. // replace links and smileys
  252. // Strophe already escapes special symbols on sending,
  253. // so we escape here only tags to avoid double &amp;
  254. const escMessage = message.replace(/</g, '&lt;')
  255. .replace(/>/g, '&gt;')
  256. .replace(/\n/g, '<br/>');
  257. const escDisplayName = UIUtil.escapeHtml(displayName);
  258. const timestamp = getCurrentTime(stamp);
  259. // eslint-disable-next-line no-param-reassign
  260. message = processReplacements(escMessage);
  261. const messageContainer
  262. = `${'<div class="chatmessage">'
  263. + '<img src="images/chatArrow.svg" class="chatArrow">'
  264. + '<div class="username '}${divClassName}">${escDisplayName
  265. }</div><div class="timestamp">${timestamp
  266. }</div><div class="usermessage">${message}</div>`
  267. + '</div>';
  268. $('#chatconversation').append(messageContainer);
  269. $('#chatconversation').animate(
  270. { scrollTop: $('#chatconversation')[0].scrollHeight }, 1000);
  271. const markAsRead = Chat.isVisible() || isFromLocalParticipant;
  272. APP.store.dispatch(addMessage(
  273. escDisplayName, message, timestamp, markAsRead));
  274. },
  275. /**
  276. * Appends error message to the conversation
  277. * @param errorMessage the received error message.
  278. * @param originalText the original message.
  279. */
  280. chatAddError(errorMessage, originalText) {
  281. // eslint-disable-next-line no-param-reassign
  282. errorMessage = UIUtil.escapeHtml(errorMessage);
  283. // eslint-disable-next-line no-param-reassign
  284. originalText = UIUtil.escapeHtml(originalText);
  285. $('#chatconversation').append(
  286. `${'<div class="errorMessage"><b>Error: </b>Your message'}${
  287. originalText ? ` "${originalText}"` : ''
  288. } was not sent.${
  289. errorMessage ? ` Reason: ${errorMessage}` : ''}</div>`);
  290. $('#chatconversation').animate(
  291. { scrollTop: $('#chatconversation')[0].scrollHeight }, 1000);
  292. },
  293. /**
  294. * Sets the subject to the UI
  295. * @param subject the subject
  296. */
  297. setSubject(subject) {
  298. if (subject) {
  299. // eslint-disable-next-line no-param-reassign
  300. subject = subject.trim();
  301. }
  302. const html = linkify(UIUtil.escapeHtml(subject));
  303. APP.store.dispatch(setSubject(html));
  304. },
  305. /**
  306. * Sets the chat conversation mode.
  307. * Conversation mode is the normal chat mode, non conversation mode is
  308. * where we ask user to input its display name.
  309. * @param {boolean} isConversationMode if chat should be in
  310. * conversation mode or not.
  311. */
  312. setChatConversationMode(isConversationMode) {
  313. $(`#${CHAT_CONTAINER_ID}`)
  314. .toggleClass('is-conversation-mode', isConversationMode);
  315. },
  316. /**
  317. * Resizes the chat area.
  318. */
  319. resizeChat(width, height) {
  320. $(`#${CHAT_CONTAINER_ID}`).width(width)
  321. .height(height);
  322. resizeChatConversation();
  323. },
  324. /**
  325. * Indicates if the chat is currently visible.
  326. */
  327. isVisible() {
  328. return UIUtil.isVisible(
  329. document.getElementById(CHAT_CONTAINER_ID));
  330. },
  331. /**
  332. * Shows and hides the window with the smileys
  333. */
  334. toggleSmileys,
  335. /**
  336. * Scrolls chat to the bottom.
  337. */
  338. scrollChatToBottom() {
  339. setTimeout(
  340. () => {
  341. const chatconversation = $('#chatconversation');
  342. // XXX Prevent TypeError: undefined is not an object when the
  343. // Web browser does not support WebRTC (yet).
  344. chatconversation.length > 0
  345. && chatconversation.scrollTop(
  346. chatconversation[0].scrollHeight);
  347. },
  348. 5);
  349. }
  350. };
  351. export default Chat;