favicon.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. defaultUrl = null
  2. currentSlug = null
  3. imageCache = {}
  4. urlCache = {}
  5. withImage = (url, action) ->
  6. if imageCache[url]
  7. action(imageCache[url])
  8. else
  9. img = new Image()
  10. img.crossOrigin = 'anonymous'
  11. img.src = url
  12. img.onload = () =>
  13. imageCache[url] = img
  14. action(img)
  15. @setFaviconForDoc = (doc) ->
  16. return if currentSlug == doc.slug
  17. favicon = $('link[rel="icon"]')
  18. if defaultUrl == null
  19. defaultUrl = favicon.href
  20. if urlCache[doc.slug]
  21. favicon.href = urlCache[doc.slug]
  22. currentSlug = doc.slug
  23. return
  24. iconEl = $("._icon-#{doc.slug.split('~')[0]}")
  25. return if iconEl == null
  26. styles = window.getComputedStyle(iconEl, ':before')
  27. backgroundPositionX = styles['background-position-x']
  28. backgroundPositionY = styles['background-position-y']
  29. return if backgroundPositionX == undefined || backgroundPositionY == undefined
  30. bgUrl = app.config.favicon_spritesheet
  31. sourceSize = 16
  32. sourceX = Math.abs(parseInt(backgroundPositionX.slice(0, -2)))
  33. sourceY = Math.abs(parseInt(backgroundPositionY.slice(0, -2)))
  34. withImage(bgUrl, (docImg) ->
  35. withImage(defaultUrl, (defaultImg) ->
  36. size = defaultImg.width
  37. canvas = document.createElement('canvas')
  38. ctx = canvas.getContext('2d')
  39. canvas.width = size
  40. canvas.height = size
  41. ctx.drawImage(defaultImg, 0, 0)
  42. docIconPercentage = 65
  43. destinationCoords = size / 100 * (100 - docIconPercentage)
  44. destinationSize = size / 100 * docIconPercentage
  45. ctx.drawImage(docImg, sourceX, sourceY, sourceSize, sourceSize, destinationCoords, destinationCoords, destinationSize, destinationSize)
  46. try
  47. urlCache[doc.slug] = canvas.toDataURL()
  48. favicon.href = urlCache[doc.slug]
  49. currentSlug = doc.slug
  50. catch error
  51. Raven.captureException error, { level: 'info' }
  52. @resetFavicon()
  53. )
  54. )
  55. @resetFavicon = () ->
  56. if defaultUrl != null and currentSlug != null
  57. $('link[rel="icon"]').href = defaultUrl
  58. currentSlug = null