chat.js 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. import {
  2. CHAT_INITIAL_PLACEHOLDER_TEXT,
  3. CHAT_PLACEHOLDER_TEXT,
  4. CHAT_PLACEHOLDER_OFFLINE,
  5. } from './constants.js';
  6. // Taken from https://stackoverflow.com/a/46902361
  7. export function getCaretPosition(node) {
  8. const selection = window.getSelection();
  9. if (selection.rangeCount === 0) {
  10. return 0;
  11. }
  12. const range = selection.getRangeAt(0);
  13. const preCaretRange = range.cloneRange();
  14. const tempElement = document.createElement('div');
  15. preCaretRange.selectNodeContents(node);
  16. preCaretRange.setEnd(range.endContainer, range.endOffset);
  17. tempElement.appendChild(preCaretRange.cloneContents());
  18. return tempElement.innerHTML.length;
  19. }
  20. // Might not need this anymore
  21. // Pieced together from parts of https://stackoverflow.com/questions/6249095/how-to-set-caretcursor-position-in-contenteditable-element-div
  22. export function setCaretPosition(editableDiv, position) {
  23. var range = document.createRange();
  24. var sel = window.getSelection();
  25. range.selectNode(editableDiv);
  26. range.setStart(editableDiv.childNodes[0], position);
  27. range.collapse(true);
  28. sel.removeAllRanges();
  29. sel.addRange(range);
  30. }
  31. export function generatePlaceholderText(isEnabled, hasSentFirstChatMessage) {
  32. if (isEnabled) {
  33. return hasSentFirstChatMessage
  34. ? CHAT_PLACEHOLDER_TEXT
  35. : CHAT_INITIAL_PLACEHOLDER_TEXT;
  36. }
  37. return CHAT_PLACEHOLDER_OFFLINE;
  38. }
  39. export function extraUserNamesFromMessageHistory(messages) {
  40. const list = [];
  41. if (messages) {
  42. messages
  43. .filter((m) => m.user && m.user.displayName)
  44. .forEach(function (message) {
  45. if (!list.includes(message.user.displayName)) {
  46. list.push(message.user.displayName);
  47. }
  48. });
  49. }
  50. return list;
  51. }
  52. // utils from https://gist.github.com/nathansmith/86b5d4b23ed968a92fd4
  53. /*
  54. You would call this after getting an element's
  55. `.innerHTML` value, while the user is typing.
  56. */
  57. export function convertToText(str = '') {
  58. // Ensure string.
  59. let value = String(str);
  60. // Convert encoding.
  61. value = value.replace(/ /gi, ' ');
  62. value = value.replace(/&/gi, '&');
  63. // Replace `<br>`.
  64. value = value.replace(/<br>/gi, '\n');
  65. // Replace `<div>` (from Chrome).
  66. value = value.replace(/<div>/gi, '\n');
  67. // Replace `<p>` (from IE).
  68. value = value.replace(/<p>/gi, '\n');
  69. // Cleanup the emoji titles.
  70. value = value.replace(/\u200C{2}/gi, '');
  71. // Trim each line.
  72. value = value
  73. .split('\n')
  74. .map((line = '') => {
  75. return line.trim();
  76. })
  77. .join('\n');
  78. // No more than 2x newline, per "paragraph".
  79. value = value.replace(/\n\n+/g, '\n\n');
  80. // Clean up spaces.
  81. value = value.replace(/[ ]+/g, ' ');
  82. value = value.trim();
  83. // Expose string.
  84. return value;
  85. }
  86. /*
  87. You would call this when a user pastes from
  88. the clipboard into a `contenteditable` area.
  89. */
  90. export function convertOnPaste(event = { preventDefault() {} }, emojiList) {
  91. // Prevent paste.
  92. event.preventDefault();
  93. // Set later.
  94. let value = '';
  95. // Does method exist?
  96. const hasEventClipboard = !!(
  97. event.clipboardData &&
  98. typeof event.clipboardData === 'object' &&
  99. typeof event.clipboardData.getData === 'function'
  100. );
  101. // Get clipboard data?
  102. if (hasEventClipboard) {
  103. value = event.clipboardData.getData('text/plain');
  104. }
  105. // Insert into temp `<textarea>`, read back out.
  106. const textarea = document.createElement('textarea');
  107. textarea.innerHTML = value;
  108. value = textarea.innerText;
  109. // Clean up text.
  110. value = convertToText(value);
  111. const HTML = emojify(value, emojiList);
  112. // Insert text.
  113. if (typeof document.execCommand === 'function') {
  114. document.execCommand('insertHTML', false, HTML);
  115. }
  116. }
  117. export function createEmojiMarkup(data, isCustom) {
  118. const emojiUrl = isCustom ? data.emoji : data.url;
  119. const emojiName = (
  120. isCustom
  121. ? data.name
  122. : data.url.split('\\').pop().split('/').pop().split('.').shift()
  123. ).toLowerCase();
  124. return (
  125. '<img class="emoji" alt=":‌‌' +
  126. emojiName +
  127. '‌‌:" title=":‌‌' +
  128. emojiName +
  129. '‌‌:" src="' +
  130. emojiUrl +
  131. '"/>'
  132. );
  133. }
  134. // trim html white space characters from ends of messages for more accurate counting
  135. export function trimNbsp(html) {
  136. return html.replace(/^(?:&nbsp;|\s)+|(?:&nbsp;|\s)+$/gi, '');
  137. }
  138. export function emojify(HTML, emojiList) {
  139. const textValue = convertToText(HTML);
  140. for (var lastPos = textValue.length; lastPos >= 0; lastPos--) {
  141. const endPos = textValue.lastIndexOf(':', lastPos);
  142. if (endPos <= 0) {
  143. break;
  144. }
  145. const startPos = textValue.lastIndexOf(':', endPos - 1);
  146. if (startPos === -1) {
  147. break;
  148. }
  149. const typedEmoji = textValue.substring(startPos + 1, endPos).trim();
  150. const emojiIndex = emojiList.findIndex(function (emojiItem) {
  151. return emojiItem.name.toLowerCase() === typedEmoji.toLowerCase();
  152. });
  153. if (emojiIndex != -1) {
  154. const emojiImgElement = createEmojiMarkup(emojiList[emojiIndex], true);
  155. HTML = HTML.replace(':' + typedEmoji + ':', emojiImgElement);
  156. }
  157. }
  158. return HTML;
  159. }
  160. // MODERATOR UTILS
  161. export function checkIsModerator(message) {
  162. const { user } = message;
  163. const { scopes } = user;
  164. if (!scopes || scopes.length === 0) {
  165. return false;
  166. }
  167. return scopes.includes('MODERATOR');
  168. }