您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

Chat.js 12KB

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