2019-08-17 20:54:45 +03:00
|
|
|
import { decode as decodeBlurHash } from 'blurhash'
|
2019-08-17 14:36:13 -07:00
|
|
|
import registerPromiseWorker from 'promise-worker/register'
|
|
|
|
import { BLURHASH_RESOLUTION as RESOLUTION } from '../_static/blurhash'
|
2019-10-24 19:03:10 -07:00
|
|
|
import { isChrome } from '../_utils/userAgent'
|
2019-08-18 14:14:11 +02:00
|
|
|
|
|
|
|
// Disabled in Chrome because convertToBlob() is slow
|
|
|
|
// https://github.com/nolanlawson/pinafore/issues/1396
|
2019-10-24 19:03:10 -07:00
|
|
|
const OFFSCREEN_CANVAS = !isChrome() && typeof OffscreenCanvas === 'function'
|
2019-08-17 20:54:45 +03:00
|
|
|
? new OffscreenCanvas(RESOLUTION, RESOLUTION) : null
|
|
|
|
const OFFSCREEN_CANVAS_CONTEXT_2D = OFFSCREEN_CANVAS
|
|
|
|
? OFFSCREEN_CANVAS.getContext('2d') : null
|
|
|
|
|
2019-08-17 14:36:13 -07:00
|
|
|
registerPromiseWorker(async (encoded) => {
|
|
|
|
const pixels = decodeBlurHash(encoded, RESOLUTION, RESOLUTION)
|
2019-08-17 20:54:45 +03:00
|
|
|
|
2019-08-17 14:36:13 -07:00
|
|
|
if (!pixels) {
|
|
|
|
throw new Error('decode did not return any pixels')
|
|
|
|
}
|
|
|
|
const imageData = new ImageData(pixels, RESOLUTION, RESOLUTION)
|
2019-08-17 20:54:45 +03:00
|
|
|
|
2019-08-17 14:36:13 -07:00
|
|
|
if (OFFSCREEN_CANVAS) {
|
|
|
|
OFFSCREEN_CANVAS_CONTEXT_2D.putImageData(imageData, 0, 0)
|
|
|
|
const blob = await OFFSCREEN_CANVAS.convertToBlob()
|
|
|
|
const decoded = URL.createObjectURL(blob)
|
|
|
|
return { decoded, imageData: null }
|
|
|
|
} else {
|
|
|
|
return { imageData, decoded: null }
|
2019-08-17 20:54:45 +03:00
|
|
|
}
|
|
|
|
})
|