History

Set favicon to the icon of the currently shown docs

Jasper van Merle committed 7 years ago

Commit c36478c1 parent d640a8e5 files · +58 −25Browse files

Showing the changes to assets/javascripts/lib (1 of 5 files). Show all

Unified · Split

assets/javascripts/lib/favicon.coffee+53−0
@@ -0,0 +1,53 @@
1defaultUrl = null
2currentSlug = null
3
4imageCache = {}
5urlCache = {}
6
7withImage = (url, action) ->
8 if imageCache[url]
9 action(imageCache[url])
10 else
11 img = new Image()
12 img.src = url
13 img.onload = () =>
14 imageCache[url] = img
15 action(img)
16
17@setFaviconForDoc = (doc) ->
18 return if currentSlug == doc.slug
19
20 favicon = $('link[rel="icon"]')
21
22 if urlCache[doc.slug]
23 favicon.href = urlCache[doc.slug]
24 currentSlug = doc.slug
25 return
26
27 styles = window.getComputedStyle($("._icon-#{doc.slug}"), ':before')
28
29 bgUrl = styles['background-image'].slice(5, -2)
30 bgSize = if bgUrl.includes('@2x') then 32 else 16
31 bgX = parseInt(styles['background-position-x'].slice(0, -2))
32 bgY = parseInt(styles['background-position-y'].slice(0, -2))
33
34 withImage(bgUrl, (img) ->
35 canvas = document.createElement('canvas')
36
37 canvas.width = bgSize
38 canvas.height = bgSize
39 canvas.getContext('2d').drawImage(img, bgX, bgY)
40
41 if defaultUrl == null
42 defaultUrl = favicon.href
43
44 urlCache[doc.slug] = canvas.toDataURL()
45 favicon.href = urlCache[doc.slug]
46
47 currentSlug = doc.slug
48 )
49
50@resetFavicon = () ->
51 if defaultUrl != null and currentSlug != null
52 $('link[rel="icon"]').href = defaultUrl
53 currentSlug = null