2020-11-02 05:46:49 -08:00
|
|
|
import { find } from 'lodash'
|
|
|
|
|
|
|
|
const createFaviconService = () => {
|
|
|
|
let favimg, favcanvas, favcontext, favicon
|
2020-11-03 01:55:29 -08:00
|
|
|
const faviconWidth = 128
|
|
|
|
const faviconHeight = 128
|
|
|
|
const badgeRadius = 32
|
2020-11-02 05:46:49 -08:00
|
|
|
|
|
|
|
const initFaviconService = () => {
|
|
|
|
const nodes = document.getElementsByTagName('link')
|
|
|
|
favicon = find(nodes, node => node.rel === 'icon')
|
|
|
|
if (favicon) {
|
|
|
|
favcanvas = document.createElement('canvas')
|
|
|
|
favcanvas.width = faviconWidth
|
|
|
|
favcanvas.height = faviconHeight
|
|
|
|
favimg = new Image()
|
2021-06-02 02:15:31 -07:00
|
|
|
favimg.crossOrigin = 'anonymous'
|
2020-11-02 05:46:49 -08:00
|
|
|
favimg.src = favicon.href
|
|
|
|
favcontext = favcanvas.getContext('2d')
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-03 01:55:29 -08:00
|
|
|
const isImageLoaded = (img) => img.complete && img.naturalHeight !== 0
|
|
|
|
|
2020-11-02 05:46:49 -08:00
|
|
|
const clearFaviconBadge = () => {
|
|
|
|
if (!favimg || !favcontext || !favicon) return
|
|
|
|
|
|
|
|
favcontext.clearRect(0, 0, faviconWidth, faviconHeight)
|
2020-11-03 01:55:29 -08:00
|
|
|
if (isImageLoaded(favimg)) {
|
|
|
|
favcontext.drawImage(favimg, 0, 0, favimg.width, favimg.height, 0, 0, faviconWidth, faviconHeight)
|
|
|
|
}
|
2020-11-02 05:46:49 -08:00
|
|
|
favicon.href = favcanvas.toDataURL('image/png')
|
|
|
|
}
|
|
|
|
|
|
|
|
const drawFaviconBadge = () => {
|
|
|
|
if (!favimg || !favcontext || !favcontext) return
|
|
|
|
|
|
|
|
clearFaviconBadge()
|
|
|
|
|
2020-11-02 06:45:15 -08:00
|
|
|
const style = getComputedStyle(document.body)
|
|
|
|
const badgeColor = `${style.getPropertyValue('--badgeNotification') || 'rgb(240, 100, 100)'}`
|
|
|
|
|
2020-11-03 01:55:29 -08:00
|
|
|
if (isImageLoaded(favimg)) {
|
|
|
|
favcontext.drawImage(favimg, 0, 0, favimg.width, favimg.height, 0, 0, faviconWidth, faviconHeight)
|
|
|
|
}
|
2020-11-02 06:45:15 -08:00
|
|
|
favcontext.fillStyle = badgeColor
|
2020-11-02 05:46:49 -08:00
|
|
|
favcontext.beginPath()
|
2020-11-02 06:45:15 -08:00
|
|
|
favcontext.arc(faviconWidth - badgeRadius, badgeRadius, badgeRadius, 0, 2 * Math.PI, false)
|
2020-11-02 05:46:49 -08:00
|
|
|
favcontext.fill()
|
|
|
|
favicon.href = favcanvas.toDataURL('image/png')
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
initFaviconService,
|
|
|
|
clearFaviconBadge,
|
|
|
|
drawFaviconBadge
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const FaviconService = createFaviconService()
|
|
|
|
|
|
|
|
export default FaviconService
|