logo

pleroma-fe

My custom branche(s) on git.pleroma.social/pleroma/pleroma-fe git clone https://hacktivis.me/git/pleroma-fe.git

utility.service.js (2575B)


  1. /**
  2. * Extract tag name from tag opener/closer.
  3. *
  4. * @param {String} tag - tag string, i.e. '<a href="...">'
  5. * @return {String} - tagname, i.e. "div"
  6. */
  7. export const getTagName = (tag) => {
  8. const result = /(?:<\/(\w+)>|<(\w+)\s?.*?\/?>)/gis.exec(tag)
  9. return result && (result[1] || result[2])
  10. }
  11. /**
  12. * Extract attributes from tag opener.
  13. *
  14. * @param {String} tag - tag string, i.e. '<a href="...">'
  15. * @return {Object} - map of attributes key = attribute name, value = attribute value
  16. * attributes without values represented as boolean true
  17. */
  18. export const getAttrs = (tag, filter) => {
  19. const innertag = tag
  20. .substring(1, tag.length - 1)
  21. .replace(new RegExp('^' + getTagName(tag)), '')
  22. .replace(/\/?$/, '')
  23. .trim()
  24. const attrs = Array.from(innertag.matchAll(/([a-z]+[a-z0-9-]*)(?:=("[^"]+?"|'[^']+?'))?/gi))
  25. .map(([trash, key, value]) => [key, value])
  26. .map(([k, v]) => {
  27. if (!v) return [k, true]
  28. return [k, v.substring(1, v.length - 1)]
  29. })
  30. const defaultFilter = ([k, v]) => {
  31. const attrKey = k.toLowerCase()
  32. if (attrKey === 'style') return false
  33. if (attrKey === 'class') {
  34. return v === 'greentext' || v === 'cyantext'
  35. }
  36. return true
  37. }
  38. return Object.fromEntries(attrs.filter(filter || defaultFilter))
  39. }
  40. /**
  41. * Finds shortcodes in text
  42. *
  43. * @param {String} text - original text to find emojis in
  44. * @param {{ url: String, shortcode: Sring }[]} emoji - list of shortcodes to find
  45. * @param {Function} processor - function to call on each encountered emoji,
  46. * function is passed single object containing matching emoji ({ url, shortcode })
  47. * return value will be inserted into resulting array instead of :shortcode:
  48. * @return {Array} resulting array with non-emoji parts of text and whatever {processor}
  49. * returned for emoji
  50. */
  51. export const processTextForEmoji = (text, emojis, processor) => {
  52. const buffer = []
  53. let textBuffer = ''
  54. for (let i = 0; i < text.length; i++) {
  55. const char = text[i]
  56. if (char === ':') {
  57. const next = text.slice(i + 1)
  58. let found = false
  59. for (const emoji of emojis) {
  60. if (next.slice(0, emoji.shortcode.length + 1) === (emoji.shortcode + ':')) {
  61. found = emoji
  62. break
  63. }
  64. }
  65. if (found) {
  66. buffer.push(textBuffer)
  67. textBuffer = ''
  68. buffer.push(processor(found))
  69. i += found.shortcode.length + 1
  70. } else {
  71. textBuffer += char
  72. }
  73. } else {
  74. textBuffer += char
  75. }
  76. }
  77. if (textBuffer) buffer.push(textBuffer)
  78. return buffer
  79. }