index.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. import { v4 as uuidv4 } from 'uuid';
  2. import sha256 from 'js-sha256';
  3. //////////////////////////
  4. // Helper functions
  5. //////////////////////////
  6. export const splitStream = (splitOn) => {
  7. let buffer = '';
  8. return new TransformStream({
  9. transform(chunk, controller) {
  10. buffer += chunk;
  11. const parts = buffer.split(splitOn);
  12. parts.slice(0, -1).forEach((part) => controller.enqueue(part));
  13. buffer = parts[parts.length - 1];
  14. },
  15. flush(controller) {
  16. if (buffer) controller.enqueue(buffer);
  17. }
  18. });
  19. };
  20. export const convertMessagesToHistory = (messages) => {
  21. let history = {
  22. messages: {},
  23. currentId: null
  24. };
  25. let parentMessageId = null;
  26. let messageId = null;
  27. for (const message of messages) {
  28. messageId = uuidv4();
  29. if (parentMessageId !== null) {
  30. history.messages[parentMessageId].childrenIds = [
  31. ...history.messages[parentMessageId].childrenIds,
  32. messageId
  33. ];
  34. }
  35. history.messages[messageId] = {
  36. ...message,
  37. id: messageId,
  38. parentId: parentMessageId,
  39. childrenIds: []
  40. };
  41. parentMessageId = messageId;
  42. }
  43. history.currentId = messageId;
  44. return history;
  45. };
  46. export const getGravatarURL = (email) => {
  47. // Trim leading and trailing whitespace from
  48. // an email address and force all characters
  49. // to lower case
  50. const address = String(email).trim().toLowerCase();
  51. // Create a SHA256 hash of the final string
  52. const hash = sha256(address);
  53. // Grab the actual image URL
  54. return `https://www.gravatar.com/avatar/${hash}`;
  55. };
  56. const copyToClipboard = (text) => {
  57. if (!navigator.clipboard) {
  58. var textArea = document.createElement('textarea');
  59. textArea.value = text;
  60. // Avoid scrolling to bottom
  61. textArea.style.top = '0';
  62. textArea.style.left = '0';
  63. textArea.style.position = 'fixed';
  64. document.body.appendChild(textArea);
  65. textArea.focus();
  66. textArea.select();
  67. try {
  68. var successful = document.execCommand('copy');
  69. var msg = successful ? 'successful' : 'unsuccessful';
  70. console.log('Fallback: Copying text command was ' + msg);
  71. } catch (err) {
  72. console.error('Fallback: Oops, unable to copy', err);
  73. }
  74. document.body.removeChild(textArea);
  75. return;
  76. }
  77. navigator.clipboard.writeText(text).then(
  78. function () {
  79. console.log('Async: Copying to clipboard was successful!');
  80. },
  81. function (err) {
  82. console.error('Async: Could not copy text: ', err);
  83. }
  84. );
  85. };