All files / js/visualization canvas.tsx

83.33% Statements 15/18
50% Branches 3/6
100% Functions 5/5
83.33% Lines 15/18

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 52 53 54 55 56 57 58 59 60                                  236x   236x   236x 14x   14x       14x     236x 236x   236x       236x   236x       236x     236x             12x 16x        
import React, {useEffect, useRef} from "react";
 
type Props = {
    width: number,
    height: number,
    draw: (ctx: CanvasRenderingContext2D) => void,
    focused: (b: Boolean) => void,
    // style from MUI
    sx?: any,
    tabIndex?: number,
    onKeyDown?: (e: KeyboardEvent) => void,
    onTouchStart?: (e: TouchEvent) => void,
    onTouchMove?: (e: TouchEvent) => void
};
 
// https://medium.com/@pdx.lucasm/canvas-with-react-js-32e133c05258
export default function Canvas(props: Props) {
    const canvasRef = useRef<HTMLCanvasElement|null>(null);
 
    const {draw, focused, ...passthrough} = props;
 
    useEffect(() => {
        const canvas = canvasRef.current;
 
        Iif(canvas === null) {
            throw "Canvas failed to construct";
        }
 
        canvas.focus();
    }, []);
 
    useEffect(() => {
        const canvas = canvasRef.current;
 
        Iif(canvas === null) {
            throw "Canvas failed to construct";
        }
 
        const context = canvas.getContext('2d');
 
        Iif(context === null) {
            throw "Failed to get the Context of the constructed canvas";
        }
 
        draw(context);
    });
 
    return (
        // @ts-ignore
        <canvas
            ref={canvasRef}
            {...passthrough}
            id={"snakeCanvas"}
            tabIndex={-1}
            onBlur={_ => focused(false)}
            onFocus={_ => focused(true)}
        />
    )
}