All files / hooks useWebGLContextLossHandler.ts

85.86% Statements 79/92
65.78% Branches 25/38
82.35% Functions 14/17
87.5% Lines 77/88

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 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292                                            7x 7x 7x         7x         7x                                                                                                                 7x                   103x   103x             103x 103x 103x 103x     103x 103x 103x       103x 72x 72x 72x       103x   3x 3x 3x 3x   3x             3x 2x     3x 3x             3x         103x 1x 1x   1x 1x           1x     103x 72x         72x 6x 6x           6x 6x           6x 6x 6x               72x 9x   9x 9x 6x 6x 3x 2x 2x     1x               1x               72x     72x 72x 72x 72x                     103x           7x 2x 2x   2x 2x   2x       2x                 7x 2x 2x 2x 2x   2x       2x          
/**
 * useWebGLContextLossHandler - React hook for handling WebGL context loss
 *
 * This hook sets up event listeners for WebGL context loss and restoration,
 * which can occur due to GPU issues, memory pressure, or browser tab switching.
 *
 * @example
 * ```tsx
 * const Canvas = () => {
 *   useWebGLContextLossHandler();
 *   return <Canvas>...</Canvas>;
 * };
 * ```
 */
 
import type React from "react";
import { useCallback, useEffect, useRef, useState } from "react";
 
/**
 * Global WebGL context state tracking
 * Helps coordinate context recovery across multiple Canvas components
 */
let globalContextLossCount = 0;
let globalIsContextLost = false;
let lastContextLossTime = 0;
 
/**
 * Minimum delay between context loss events to prevent thrashing
 */
export const MIN_CONTEXT_RECOVERY_DELAY = 100; // ms
 
/**
 * Get global WebGL context state
 */
export const getWebGLContextState = (): {
  isLost: boolean;
  lossCount: number;
  timeSinceLastLoss: number;
} => ({
  isLost: globalIsContextLost,
  lossCount: globalContextLossCount,
  timeSinceLastLoss: Date.now() - lastContextLossTime,
});
 
export interface WebGLContextLossOptions {
  /**
   * Callback when context is lost
   */
  readonly onContextLost?: () => void;
 
  /**
   * Callback when context is restored
   */
  readonly onContextRestored?: () => void;
 
  /**
   * Whether to attempt automatic restoration (default: true)
   */
  readonly autoRestore?: boolean;
 
  /**
   * Optional canvas ref to attach to a specific canvas element
   * If not provided, will query for the first canvas in the document
   */
  readonly canvasRef?: React.RefObject<HTMLCanvasElement>;
 
  /**
   * Delay in ms before attempting to query for canvas (default: 50)
   * Helps avoid race conditions during screen transitions
   */
  readonly mountDelay?: number;
 
  /**
   * Maximum attempts to find canvas element (default: 5)
   */
  readonly maxRetries?: number;
}
 
export interface WebGLContextState {
  /** Whether context is currently lost */
  readonly isContextLost: boolean;
  /** Number of times context has been lost */
  readonly lossCount: number;
  /** Whether the canvas element has been found */
  readonly isCanvasMounted: boolean;
}
 
/**
 * Hook to handle WebGL context loss and restoration
 * Returns state information about the WebGL context
 */
export const useWebGLContextLossHandler = (
  options: WebGLContextLossOptions = {}
): WebGLContextState => {
  const {
    onContextLost,
    onContextRestored,
    autoRestore = true,
    canvasRef,
    mountDelay = 50,
    maxRetries = 5,
  } = options;
 
  const [contextState, setContextState] = useState<WebGLContextState>({
    isContextLost: globalIsContextLost,
    lossCount: globalContextLossCount,
    isCanvasMounted: false,
  });
 
  // Use refs to store the latest callbacks to avoid re-registering event listeners
  const onContextLostRef = useRef(onContextLost);
  const onContextRestoredRef = useRef(onContextRestored);
  const retryCountRef = useRef(0);
  const mountedRef = useRef(true);
 
  // Update refs when callbacks change
  useEffect(() => {
    onContextLostRef.current = onContextLost;
    onContextRestoredRef.current = onContextRestored;
  });
 
  // Track component mount state
  useEffect(() => {
    mountedRef.current = true;
    return () => {
      mountedRef.current = false;
    };
  }, []);
 
  const handleContextLost = useCallback(
    (event: Event) => {
      const now = Date.now();
      globalIsContextLost = true;
      globalContextLossCount++;
      lastContextLossTime = now;
 
      console.warn(
        `⚠️ WebGL context lost (count: ${globalContextLossCount}, time since mount: ${
          now - lastContextLossTime
        }ms)`
      );
 
      // Prevent default behavior to allow restoration
      if (autoRestore) {
        event.preventDefault();
      }
 
      Eif (mountedRef.current) {
        setContextState({
          isContextLost: true,
          lossCount: globalContextLossCount,
          isCanvasMounted: true,
        });
      }
 
      onContextLostRef.current?.();
    },
    [autoRestore]
  );
 
  const handleContextRestored = useCallback(() => {
    globalIsContextLost = false;
    console.log("✅ WebGL context restored successfully");
 
    Eif (mountedRef.current) {
      setContextState((prev) => ({
        ...prev,
        isContextLost: false,
      }));
    }
 
    onContextRestoredRef.current?.();
  }, []);
 
  useEffect(() => {
    let canvas = canvasRef?.current ?? document.querySelector("canvas");
    let cleanupFn: (() => void) | undefined;
    let retryTimeout: ReturnType<typeof setTimeout> | undefined;
    let observer: MutationObserver | undefined;
 
    const attachListeners = (canvasEl: HTMLCanvasElement) => {
      canvasEl.addEventListener("webglcontextlost", handleContextLost, false);
      canvasEl.addEventListener(
        "webglcontextrestored",
        handleContextRestored,
        false
      );
 
      Eif (mountedRef.current) {
        setContextState((prev) => ({
          ...prev,
          isCanvasMounted: true,
        }));
      }
 
      return () => {
        canvasEl.removeEventListener("webglcontextlost", handleContextLost);
        canvasEl.removeEventListener(
          "webglcontextrestored",
          handleContextRestored
        );
      };
    };
 
    // Retry finding canvas with delay to handle screen transitions
    const tryFindCanvas = () => {
      Iif (!mountedRef.current) return;
 
      canvas = canvasRef?.current ?? document.querySelector("canvas");
      if (canvas) {
        cleanupFn = attachListeners(canvas);
        retryCountRef.current = 0;
      } else if (retryCountRef.current < maxRetries) {
        retryCountRef.current++;
        retryTimeout = setTimeout(tryFindCanvas, mountDelay);
      } else {
        // Fall back to MutationObserver
        observer = new MutationObserver(() => {
          canvas = document.querySelector("canvas");
          if (canvas && mountedRef.current) {
            observer?.disconnect();
            cleanupFn = attachListeners(canvas);
          }
        });
 
        observer.observe(document.body, {
          childList: true,
          subtree: true,
        });
      }
    };
 
    // Start with initial delay to let Canvas mount
    retryTimeout = setTimeout(tryFindCanvas, mountDelay);
 
    // Cleanup
    return () => {
      Eif (retryTimeout) clearTimeout(retryTimeout);
      observer?.disconnect();
      cleanupFn?.();
    };
  }, [
    autoRestore,
    canvasRef,
    handleContextLost,
    handleContextRestored,
    maxRetries,
    mountDelay,
  ]);
 
  return contextState;
};
 
/**
 * Check if WebGL is available in the current browser
 */
export const isWebGLAvailable = (): boolean => {
  try {
    const canvas = document.createElement("canvas");
    const gl =
      canvas.getContext("webgl") ?? canvas.getContext("experimental-webgl");
    const available = gl !== null;
    // Help GC by cleaning up WebGL context
    Iif (gl && "getExtension" in gl) {
      const loseContext = gl.getExtension("WEBGL_lose_context");
      loseContext?.loseContext();
    }
    return available;
  } catch {
    return false;
  }
};
 
/**
 * Check if WebGL2 is available in the current browser
 */
export const isWebGL2Available = (): boolean => {
  try {
    const canvas = document.createElement("canvas");
    const gl = canvas.getContext("webgl2");
    const available = gl !== null;
    // Help GC by cleaning up WebGL context
    Iif (gl && "getExtension" in gl) {
      const loseContext = gl.getExtension("WEBGL_lose_context");
      loseContext?.loseContext();
    }
    return available;
  } catch {
    return false;
  }
};