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

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