~cytrogen/masto-fe

ref: 20a89f1c8eefa0f766a4650be4d2e5f1fa92ee71 masto-fe/app/javascript/flavours/glitch/components/blurhash.tsx -rw-r--r-- 1.3 KiB
20a89f1c — Cytrogen [feature] Bookmark folders UI 8 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { useRef, useEffect } from "react";
import * as React from "react";

import { decode } from "blurhash";

interface Props extends React.HTMLAttributes<HTMLCanvasElement> {
  hash: string,
  width?: number,
  height?: number,
  dummy?: boolean, // Whether dummy mode is enabled. If enabled, nothing is rendered and canvas left untouched
  children?: never,
}
const Blurhash: React.FC<Props> = ({
  hash,
  width = 32,
  height = width,
  dummy = false,
  ...canvasProps
}) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);

  useEffect(() => {
    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
    const canvas = canvasRef.current!;

    // 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} />
  );
};

const MemoizedBlurhash = React.memo(Blurhash);

export { MemoizedBlurhash as Blurhash };