All files / src/components/VirtualWalkthrough useRestartOnVr.ts

100% Statements 15/15
100% Branches 8/8
100% Functions 4/4
100% Lines 15/15

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                                1x 6x   6x 6x 6x 1x     5x 4x 4x 2x   2x 2x     5x   5x 5x            
import { RefObject, useEffect } from 'react';
 
import { useApp } from '@playcanvas/react/hooks';
import { Script, XRTYPE_VR } from 'playcanvas';
 
/**
 * Replays a one-shot script effect at the start of every VR session.
 *
 * `GSplatShaderEffect` zeroes its timeline on the script's `enable` event and switches itself off
 * once the animation has played out, so re-enabling a finished effect runs it again. The `enabled`
 * setter only fires the event on a change of state, which is why an effect still mid-play is taken
 * back through disabled first.
 *
 * @param scriptRef - The script instance to replay, as handed back by `Script`'s ref.
 * @param enabled - Whether the effect is in use at all. No session is watched while false.
 */
export const useRestartOnVr = (scriptRef: RefObject<Script | null>, enabled: boolean) => {
  const app = useApp();
 
  useEffect(() => {
    const xr = app?.xr;
    if (!xr || !enabled) {
      return;
    }
 
    const restart = () => {
      const script = scriptRef.current;
      if (!script || xr.type !== XRTYPE_VR) {
        return;
      }
      script.enabled = false;
      script.enabled = true;
    };
 
    xr.on('start', restart);
 
    return () => {
      xr.off('start', restart);
    };
  }, [app, enabled, scriptRef]);
};
 
export default useRestartOnVr;