logo

pleroma-fe

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

favicon_service.js (2257B)


  1. const createFaviconService = () => {
  2. const favicons = []
  3. const faviconWidth = 128
  4. const faviconHeight = 128
  5. const badgeRadius = 32
  6. const initFaviconService = () => {
  7. const nodes = document.querySelectorAll('link[rel="icon"]')
  8. nodes.forEach(favicon => {
  9. if (favicon) {
  10. const favcanvas = document.createElement('canvas')
  11. favcanvas.width = faviconWidth
  12. favcanvas.height = faviconHeight
  13. const favimg = new Image()
  14. favimg.crossOrigin = 'anonymous'
  15. favimg.src = favicon.href
  16. const favcontext = favcanvas.getContext('2d')
  17. favicons.push({ favcanvas, favimg, favcontext, favicon })
  18. }
  19. })
  20. }
  21. const isImageLoaded = (img) => img.complete && img.naturalHeight !== 0
  22. const clearFaviconBadge = () => {
  23. if (favicons.length === 0) return
  24. favicons.forEach(({ favimg, favcanvas, favcontext, favicon }) => {
  25. if (!favimg || !favcontext || !favicon) return
  26. favcontext.clearRect(0, 0, faviconWidth, faviconHeight)
  27. if (isImageLoaded(favimg)) {
  28. favcontext.drawImage(favimg, 0, 0, favimg.width, favimg.height, 0, 0, faviconWidth, faviconHeight)
  29. }
  30. favicon.href = favcanvas.toDataURL('image/png')
  31. })
  32. }
  33. const drawFaviconBadge = () => {
  34. if (favicons.length === 0) return
  35. clearFaviconBadge()
  36. favicons.forEach(({ favimg, favcanvas, favcontext, favicon }) => {
  37. if (!favimg || !favcontext || !favcontext) return
  38. const style = getComputedStyle(document.body)
  39. const badgeColor = `${style.getPropertyValue('--badgeNotification') || 'rgb(240, 100, 100)'}`
  40. if (isImageLoaded(favimg)) {
  41. favcontext.drawImage(favimg, 0, 0, favimg.width, favimg.height, 0, 0, faviconWidth, faviconHeight)
  42. }
  43. favcontext.fillStyle = badgeColor
  44. favcontext.beginPath()
  45. favcontext.arc(faviconWidth - badgeRadius, badgeRadius, badgeRadius, 0, 2 * Math.PI, false)
  46. favcontext.fill()
  47. favicon.href = favcanvas.toDataURL('image/png')
  48. })
  49. }
  50. const getOriginalFavicons = () => [...favicons]
  51. return {
  52. initFaviconService,
  53. clearFaviconBadge,
  54. drawFaviconBadge,
  55. getOriginalFavicons
  56. }
  57. }
  58. const FaviconService = createFaviconService()
  59. export default FaviconService