All files / src/react-parallax-tilt ReactParallaxTilt.tsx

99.35% Statements 153/154
93.47% Branches 43/46
100% Functions 24/24
100% Lines 153/153

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 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389                          14x 23x                                 23x 23x     23x 23x 23x 23x 23x 23x 23x 23x 23x       23x 23x   23x       1x 1x 1x       23x   23x   23x 1x 1x 1x 1x 1x 1x                                                                 23x   23x   23x 1x 1x 1x 1x 1x 1x                       23x 43x 43x 18x         43x 43x 43x 43x 43x       23x   23x 14x     9x 9x     23x 47x 24x   47x 47x 47x     23x 20x         20x     20x 20x   20x 2x       23x 23x 23x       47x 47x 3x   44x 44x 44x 18x 18x     44x                     23x 3x 3x   3x 2x     3x 2x 2x       23x 47x   47x   17x 17x 17x 17x   4x 4x 4x 4x                 25x 25x 25x 25x 25x 25x 25x                                               23x 47x   47x 47x 47x 47x 47x 21x     47x 43x     47x   47x   47x 18x       23x 21x       21x 2x   2x 2x         19x   19x 19x     21x 21x     23x 47x   47x 2x 2x   47x 2x       23x 9x   9x 9x 9x 9x 2x         9x       9x   9x       9x   9x       23x 23x   23x 9x         24x 24x     48x                                
import { PureComponent } from 'react';
 
import { Glare } from '@/features/glare/Glare';
import { Tilt } from '@/features/tilt/Tilt';
import { setTransition, constrainToRange } from '@/utils/helperFns';
 
import { defaultProps } from './defaultProps';
import type { SupportedEvent, EventType, CustomEventType, WrapperElement, DeviceOrientationEventiOS } from './types';
import type { OnEnterParams, OnLeaveParams, ReactParallaxTiltProps } from './types.public';
 
// All props are initialized by default with non-null values
/* eslint-disable @typescript-eslint/no-non-null-assertion */
export class ReactParallaxTilt extends PureComponent<ReactParallaxTiltProps> {
  public static defaultProps = defaultProps;
  private wrapperEl: WrapperElement = {
    node: null,
    size: {
      width: 0,
      height: 0,
      left: 0,
      top: 0,
    },
    clientPosition: {
      x: null,
      y: null,
      xPercentage: 0,
      yPercentage: 0,
    },
    updateAnimationId: null,
    scale: 1,
  };
  private tilt: Tilt | null = null;
  private glare: Glare | null = null;
 
  public componentDidMount() {
    this.tilt = new Tilt();
    this.initGlare();
    this.setSize();
    this.addEventListeners();
    Iif (typeof CustomEvent === 'undefined') return;
    const autoreset = new CustomEvent<CustomEventType>('autoreset');
    this.mainLoop(autoreset);
    const initialEvent = new CustomEvent<CustomEventType>('initial');
    this.emitOnMove(initialEvent);
  }
 
  public componentWillUnmount() {
    Eif (this.wrapperEl.updateAnimationId !== null) {
      cancelAnimationFrame(this.wrapperEl.updateAnimationId);
    }
    this.removeEventListeners();
  }
 
  public componentDidUpdate() {
    const eventType = new CustomEvent<CustomEventType>('propChange');
    this.mainLoop(eventType);
    this.emitOnMove(eventType);
  }
 
  private addEventListeners() {
    const { trackOnWindow, gyroscope } = this.props;
 
    window.addEventListener('resize', this.setSize);
 
    if (trackOnWindow) {
      window.addEventListener('mouseenter', this.onEnter);
      window.addEventListener('mousemove', this.onMove);
      window.addEventListener('mouseout', this.onLeave);
      window.addEventListener('touchstart', this.onEnter);
      window.addEventListener('touchmove', this.onMove);
      window.addEventListener('touchend', this.onLeave);
    }
 
    /* v8 ignore start */
    if (gyroscope) {
      void this.addDeviceOrientationEventListener();
    }
    /* v8 ignore stop */
  }
 
  /* v8 ignore start */
  private addDeviceOrientationEventListener = async () => {
    // Browser doesn't support Device Orientation.
    // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
    if (!window.DeviceOrientationEvent) {
      return;
    }
 
    const requestPermission = (DeviceOrientationEvent as unknown as DeviceOrientationEventiOS).requestPermission;
    const iOS = typeof requestPermission === 'function';
    if (iOS) {
      const response = await requestPermission();
      if (response === 'granted') {
        window.addEventListener('deviceorientation', this.onMove);
      }
      return;
    }
 
    window.addEventListener('deviceorientation', this.onMove);
  };
  /* v8 ignore stop */
 
  private removeEventListeners() {
    const { trackOnWindow, gyroscope } = this.props;
 
    window.removeEventListener('resize', this.setSize);
 
    if (trackOnWindow) {
      window.removeEventListener('mouseenter', this.onEnter);
      window.removeEventListener('mousemove', this.onMove);
      window.removeEventListener('mouseout', this.onLeave);
      window.removeEventListener('touchstart', this.onEnter);
      window.removeEventListener('touchmove', this.onMove);
      window.removeEventListener('touchend', this.onLeave);
    }
 
    // Instance of DeviceOrientationEvent not possible.
    /* v8 ignore start */
    // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
    if (gyroscope && window.DeviceOrientationEvent) {
      window.removeEventListener('deviceorientation', this.onMove);
    }
    /* v8 ignore stop */
  }
 
  public setSize = () => {
    this.setWrapperElSize();
    if (this.glare) {
      this.glare.setSize(this.wrapperEl.size);
    }
  };
 
  private setWrapperElSize() {
    const rect = this.wrapperEl.node!.getBoundingClientRect();
    this.wrapperEl.size.width = this.wrapperEl.node!.offsetWidth;
    this.wrapperEl.size.height = this.wrapperEl.node!.offsetHeight;
    this.wrapperEl.size.left = rect.left + window.scrollX;
    this.wrapperEl.size.top = rect.top + window.scrollY;
  }
 
  private initGlare() {
    const { glareEnable, glareBorderRadius } = this.props;
 
    if (!glareEnable) {
      return;
    }
 
    this.glare = new Glare(this.wrapperEl.size, glareBorderRadius!);
    this.wrapperEl.node!.appendChild(this.glare.glareWrapperEl);
  }
 
  public mainLoop = (event: SupportedEvent) => {
    if (this.wrapperEl.updateAnimationId !== null) {
      cancelAnimationFrame(this.wrapperEl.updateAnimationId);
    }
    this.processInput(event);
    this.update(event.type);
    this.wrapperEl.updateAnimationId = requestAnimationFrame(this.renderFrame);
  };
 
  private onEnter = (event: OnEnterParams['event']) => {
    const { onEnter } = this.props;
 
    // Update wrapped tilt component params in case
    // - it's being manipulated (position, size, etc.) in consumed application
    // - initial (delayed) images/children load
    this.setSize();
 
    // increase performance by notifying browser 'transform' property is just about to get changed
    this.wrapperEl.node!.style.willChange = 'transform';
    this.setTransitions();
 
    if (onEnter) {
      onEnter({ event });
    }
  };
 
  private onMove = (event: SupportedEvent): void => {
    this.mainLoop(event);
    this.emitOnMove(event);
  };
 
  private emitOnMove(event: SupportedEvent) {
    const { onMove } = this.props;
    if (!onMove) {
      return;
    }
    let glareAngle = 0;
    let glareOpacity = 0;
    if (this.glare) {
      glareAngle = this.glare.glareAngle;
      glareOpacity = this.glare.glareOpacity;
    }
 
    onMove({
      tiltAngleX: this.tilt!.tiltAngleX,
      tiltAngleY: this.tilt!.tiltAngleY,
      tiltAngleXPercentage: this.tilt!.tiltAngleXPercentage,
      tiltAngleYPercentage: this.tilt!.tiltAngleYPercentage,
      glareAngle,
      glareOpacity,
      event,
    });
  }
 
  private onLeave = (event: OnLeaveParams['event']) => {
    const { onLeave } = this.props;
    this.setTransitions();
 
    if (onLeave) {
      onLeave({ event });
    }
 
    if (this.props.reset) {
      const autoResetEvent = new CustomEvent<CustomEventType>('autoreset');
      this.onMove(autoResetEvent);
    }
  };
 
  private processInput = (event: SupportedEvent): void => {
    const { scale } = this.props;
 
    switch (event.type as EventType) {
      case 'mousemove':
        this.wrapperEl.clientPosition.x = (event as MouseEvent).pageX;
        this.wrapperEl.clientPosition.y = (event as MouseEvent).pageY;
        this.wrapperEl.scale = scale!;
        break;
      case 'touchmove':
        this.wrapperEl.clientPosition.x = (event as TouchEvent).touches[0].pageX;
        this.wrapperEl.clientPosition.y = (event as TouchEvent).touches[0].pageY;
        this.wrapperEl.scale = scale!;
        break;
      // Instance of DeviceOrientationEvent not possible.
      /* v8 ignore start */
      case 'deviceorientation':
        this.processInputDeviceOrientation(event as DeviceOrientationEvent);
        this.wrapperEl.scale = scale!;
        break;
      /* v8 ignore stop */
      case 'autoreset': {
        const { tiltAngleXInitial, tiltAngleYInitial, tiltMaxAngleX, tiltMaxAngleY } = this.props;
        const xPercentage = (tiltAngleXInitial! / tiltMaxAngleX!) * 100;
        const yPercentage = (tiltAngleYInitial! / tiltMaxAngleY!) * 100;
        this.wrapperEl.clientPosition.xPercentage = constrainToRange(xPercentage, -100, 100);
        this.wrapperEl.clientPosition.yPercentage = constrainToRange(yPercentage, -100, 100);
        this.wrapperEl.scale = 1;
        break;
      }
    }
  };
 
  /* v8 ignore start */
  private processInputDeviceOrientation = (event: DeviceOrientationEvent): void => {
    if (!event.gamma || !event.beta || !this.props.gyroscope) {
      return;
    }
 
    const { tiltMaxAngleX, tiltMaxAngleY } = this.props;
 
    const angleX = event.beta; // motion of the device around the x axis in degree in the range:[-180,180]
    const angleY = event.gamma; // motion of the device around the y axis in degree in the range:[-90,90]
 
    this.wrapperEl.clientPosition.xPercentage = (angleX / tiltMaxAngleX!) * 100;
    this.wrapperEl.clientPosition.yPercentage = (angleY / tiltMaxAngleY!) * 100;
 
    this.wrapperEl.clientPosition.xPercentage = constrainToRange(this.wrapperEl.clientPosition.xPercentage, -100, 100);
    this.wrapperEl.clientPosition.yPercentage = constrainToRange(this.wrapperEl.clientPosition.yPercentage, -100, 100);
  };
  /* v8 ignore stop */
 
  private update = (eventType: string): void => {
    const { tiltEnable, flipVertically, flipHorizontally } = this.props;
 
    const isAngleSetToDefaultAlready = eventType !== ('autoreset' satisfies EventType);
    const isAngleRetrievedFromGyroscope = eventType !== ('deviceorientation' satisfies EventType);
    const isPropChanged = eventType !== ('propChange' satisfies EventType);
    const isUpdateCalculationNeeded = isAngleSetToDefaultAlready && isAngleRetrievedFromGyroscope && isPropChanged;
    if (isUpdateCalculationNeeded) {
      this.updateClientInput();
    }
 
    if (tiltEnable) {
      this.tilt!.update(this.wrapperEl.clientPosition, this.props);
    }
 
    this.updateFlip();
 
    this.tilt!.updateTiltAnglesPercentage(this.props);
 
    if (this.glare) {
      this.glare.update(this.wrapperEl.clientPosition, this.props, flipVertically!, flipHorizontally!);
    }
  };
 
  private updateClientInput = (): void => {
    const { trackOnWindow } = this.props;
 
    let xTemp;
    let yTemp;
    if (trackOnWindow) {
      const { x, y } = this.wrapperEl.clientPosition;
 
      xTemp = (y! / window.innerHeight) * 200 - 100;
      yTemp = (x! / window.innerWidth) * 200 - 100;
    } else {
      const {
        size: { width, height, left, top },
        clientPosition: { x, y },
      } = this.wrapperEl;
 
      xTemp = ((y! - top!) / height!) * 200 - 100;
      yTemp = ((x! - left!) / width!) * 200 - 100;
    }
 
    this.wrapperEl.clientPosition.xPercentage = constrainToRange(xTemp, -100, 100);
    this.wrapperEl.clientPosition.yPercentage = constrainToRange(yTemp, -100, 100);
  };
 
  private updateFlip = (): void => {
    const { flipVertically, flipHorizontally } = this.props;
 
    if (flipVertically) {
      this.tilt!.tiltAngleX += 180;
      this.tilt!.tiltAngleY *= -1;
    }
    if (flipHorizontally) {
      this.tilt!.tiltAngleY += 180;
    }
  };
 
  public renderFrame = (): void => {
    this.resetWrapperElTransform();
 
    this.renderPerspective();
    this.tilt!.render(this.wrapperEl.node!);
    this.renderScale();
    if (this.glare) {
      this.glare.render(this.props);
    }
  };
 
  private resetWrapperElTransform(): void {
    this.wrapperEl.node!.style.transform = '';
  }
 
  private renderPerspective(): void {
    const { perspective } = this.props;
 
    this.wrapperEl.node!.style.transform += `perspective(${perspective!}px) `;
  }
 
  private renderScale(): void {
    const { scale } = this.wrapperEl;
 
    this.wrapperEl.node!.style.transform += `scale3d(${scale},${scale},${scale})`;
  }
 
  private setTransitions() {
    const { transitionSpeed, transitionEasing } = this.props;
    setTransition(this.wrapperEl.node!, 'all', transitionSpeed!, transitionEasing!);
 
    if (this.glare) {
      setTransition(this.glare.glareEl, 'opacity', transitionSpeed!, transitionEasing!);
    }
  }
 
  public render() {
    const { children, className, style } = this.props;
    return (
      <div
        ref={(el) => {
          this.wrapperEl.node = el;
        }}
        onMouseEnter={this.onEnter}
        onMouseMove={this.onMove}
        onMouseLeave={this.onLeave}
        onTouchStart={this.onEnter}
        onTouchMove={this.onMove}
        onTouchEnd={this.onLeave}
        className={className}
        style={style}
      >
        {children}
      </div>
    );
  }
}