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.

replacement.js 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { regexes } from './smileys';
  2. /* eslint-disable no-useless-escape, max-len */
  3. const replacePatterns = {
  4. // URLs starting with http://, https://, or ftp://
  5. '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>':
  6. /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim,
  7. // URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  8. '$1<a href="https://$2" target="_blank" rel="noopener noreferrer">$2</a>':
  9. /(^|[^\/])(www\.[\S]+(\b|$))/gim,
  10. // Change email addresses to mailto: links.
  11. '<a href="mailto:$1">$1</a>':
  12. /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim
  13. };
  14. /* eslint-enable no-useless-escape, max-len */
  15. /**
  16. * Processes links and smileys in "body".
  17. *
  18. * @param {string} body - The message body.
  19. * @returns {string} Message body with image tags and href tags.
  20. */
  21. export function processReplacements(body) {
  22. // make links clickable + add smileys
  23. // non of the patterns we search contains a space, that's why we tokenize it
  24. // and after processing each token we join it again with the results
  25. // making sure we do only one replacement for a token
  26. const tokens = body.split(' ');
  27. const resultText = [];
  28. for (const token of tokens) {
  29. let replacedText;
  30. const tokenLength = token.length;
  31. for (const newString in replacePatterns) { // eslint-disable-line guard-for-in, max-len
  32. const replacePattern = replacePatterns[newString];
  33. replacedText = token.replace(replacePattern, newString);
  34. // replacement was done, stop doing any other replacements
  35. if (replacedText.length > tokenLength) {
  36. break;
  37. }
  38. replacedText = null;
  39. }
  40. // no replacement was done, then just check for smiley
  41. if (!replacedText) {
  42. replacedText = smilify(token);
  43. }
  44. resultText.push(replacedText);
  45. }
  46. return resultText.join(' ');
  47. }
  48. /**
  49. * Replaces common smiley strings with images.
  50. *
  51. * @param {string} body - The message body.
  52. * @returns {string} Body returned with smiley replaced.
  53. */
  54. function smilify(body) {
  55. if (!body) {
  56. return body;
  57. }
  58. let formattedBody = body;
  59. for (const smiley in regexes) {
  60. if (regexes.hasOwnProperty(smiley)) {
  61. formattedBody = formattedBody.replace(regexes[smiley],
  62. `<img class="smiley" src="images/smileys/${smiley}.svg">`);
  63. }
  64. }
  65. return formattedBody;
  66. }