All files / repo/src/hooks useThrottledDraw.ts

100% Statements 37/37
100% Branches 12/12
100% Functions 3/3
100% Lines 37/37

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  1x   1x   1x 4x 4x 4x 4x 4x 4x 4x 4x 4x   4x 11x 6x 6x 6x 11x   4x 6x 4x 4x 4x 3x 3x   2x   2x 2x 4x 6x   4x 6x 4x   4x 4x 4x 4x  
import type { Tile } from '@/components/GameCanvas/GameCanvas.types';
import { drawBoard } from '@/shared/utils/canvasRenderer';
import type { Ref } from 'vue';
import { ref, watchEffect } from 'vue';
 
export function useThrottledDraw(
  canvasRef: Ref<HTMLCanvasElement | null>,
  tiles: Ref<Tile[]>,
  mouseX: Ref<number>,
  mouseY: Ref<number>,
  hoveredTileId: Ref<number | null>,
  tileSize: Ref<number>
) {
  const needsRedraw = ref(false);
  let animationFrameId: number | null = null;
 
  function triggerDraw() {
    if (!needsRedraw.value) {
      needsRedraw.value = true;
      scheduleDraw();
    }
  }
 
  function scheduleDraw() {
    if (animationFrameId !== null) return;
    animationFrameId = requestAnimationFrame(() => {
      const canvas = canvasRef.value;
      if (!canvas) return;
      const ctx = canvas.getContext('2d');
      if (!ctx) return;
 
      drawBoard(ctx, canvas, tiles.value, { x: mouseX.value, y: mouseY.value }, hoveredTileId.value, tileSize.value);
 
      needsRedraw.value = false;
      animationFrameId = null;
    });
  }
 
  watchEffect(() => {
    triggerDraw();
  });
 
  return {
    triggerDraw,
  };
}