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