2019-08-17 17:54:45 +00:00
|
|
|
import BlurhashWorker from 'worker-loader!../_workers/blurhash' // eslint-disable-line
|
2019-08-17 21:36:13 +00:00
|
|
|
import PromiseWorker from 'promise-worker'
|
|
|
|
import { BLURHASH_RESOLUTION as RESOLUTION } from '../_static/blurhash'
|
|
|
|
import QuickLRU from 'quick-lru'
|
|
|
|
|
|
|
|
const CACHE = new QuickLRU({ maxSize: 100 })
|
2019-08-17 17:54:45 +00:00
|
|
|
|
|
|
|
let worker
|
|
|
|
let canvas
|
|
|
|
let canvasContext2D
|
|
|
|
|
|
|
|
export function init () {
|
2019-08-17 21:36:13 +00:00
|
|
|
worker = worker || new PromiseWorker(new BlurhashWorker())
|
2019-08-17 17:54:45 +00:00
|
|
|
}
|
|
|
|
|
2019-08-17 21:36:13 +00:00
|
|
|
function initCanvas () {
|
|
|
|
if (!canvas) {
|
|
|
|
canvas = document.createElement('canvas')
|
|
|
|
canvas.height = RESOLUTION
|
|
|
|
canvas.width = RESOLUTION
|
|
|
|
canvasContext2D = canvas.getContext('2d')
|
|
|
|
}
|
|
|
|
}
|
2019-08-17 17:54:45 +00:00
|
|
|
|
2019-08-17 21:36:13 +00:00
|
|
|
// canvas is the backup if we can't use OffscreenCanvas
|
|
|
|
async function decodeUsingCanvas (imageData) {
|
|
|
|
initCanvas()
|
|
|
|
canvasContext2D.putImageData(imageData, 0, 0)
|
|
|
|
const blob = await new Promise(resolve => canvas.toBlob(resolve))
|
|
|
|
return URL.createObjectURL(blob)
|
|
|
|
}
|
2019-08-17 17:54:45 +00:00
|
|
|
|
2019-08-17 21:36:13 +00:00
|
|
|
async function decodeWithoutCache (blurhash) {
|
|
|
|
init()
|
|
|
|
const { decoded, imageData } = await worker.postMessage(blurhash)
|
|
|
|
if (decoded) {
|
|
|
|
return decoded
|
|
|
|
}
|
|
|
|
return decodeUsingCanvas(imageData)
|
|
|
|
}
|
2019-08-17 17:54:45 +00:00
|
|
|
|
2019-08-17 21:36:13 +00:00
|
|
|
export async function decode (blurhash) {
|
|
|
|
let result = CACHE.get(blurhash)
|
|
|
|
if (!result) {
|
|
|
|
result = await decodeWithoutCache(blurhash)
|
|
|
|
CACHE.set(blurhash, result)
|
|
|
|
}
|
|
|
|
return result
|
2019-08-17 17:54:45 +00:00
|
|
|
}
|