2023-05-28 12:18:23 +00:00
|
|
|
import { useRef, useEffect } from 'react';
|
|
|
|
import * as React from 'react';
|
2023-05-02 10:54:00 +00:00
|
|
|
|
2023-05-10 10:59:29 +00:00
|
|
|
import { decode } from 'blurhash';
|
|
|
|
|
|
|
|
interface Props extends React.HTMLAttributes<HTMLCanvasElement> {
|
2023-05-02 10:54:00 +00:00
|
|
|
hash: string;
|
|
|
|
width?: number;
|
|
|
|
height?: number;
|
|
|
|
dummy?: boolean; // Whether dummy mode is enabled. If enabled, nothing is rendered and canvas left untouched
|
|
|
|
children?: never;
|
2023-05-10 10:59:29 +00:00
|
|
|
}
|
2023-05-09 01:11:56 +00:00
|
|
|
const Blurhash: React.FC<Props> = ({
|
2023-05-02 10:54:00 +00:00
|
|
|
hash,
|
|
|
|
width = 32,
|
|
|
|
height = width,
|
|
|
|
dummy = false,
|
|
|
|
...canvasProps
|
2023-05-09 01:11:56 +00:00
|
|
|
}) => {
|
2023-05-02 10:54:00 +00:00
|
|
|
const canvasRef = useRef<HTMLCanvasElement>(null);
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
|
|
const canvas = canvasRef.current!;
|
2023-05-10 10:59:29 +00:00
|
|
|
|
2023-05-02 10:54:00 +00:00
|
|
|
// eslint-disable-next-line no-self-assign
|
|
|
|
canvas.width = canvas.width; // resets canvas
|
|
|
|
|
|
|
|
if (dummy || !hash) return;
|
|
|
|
|
|
|
|
try {
|
|
|
|
const pixels = decode(hash, width, height);
|
|
|
|
const ctx = canvas.getContext('2d');
|
|
|
|
const imageData = new ImageData(pixels, width, height);
|
|
|
|
|
|
|
|
ctx?.putImageData(imageData, 0, 0);
|
|
|
|
} catch (err) {
|
|
|
|
console.error('Blurhash decoding failure', { err, hash });
|
|
|
|
}
|
|
|
|
}, [dummy, hash, width, height]);
|
|
|
|
|
|
|
|
return (
|
|
|
|
<canvas {...canvasProps} ref={canvasRef} width={width} height={height} />
|
|
|
|
);
|
2023-05-09 01:11:56 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
const MemoizedBlurhash = React.memo(Blurhash);
|
2023-05-02 10:54:00 +00:00
|
|
|
|
2023-05-09 01:11:56 +00:00
|
|
|
export { MemoizedBlurhash as Blurhash };
|