Skip to content

Commit

Permalink
Add window availability check (software-mansion#4976)
Browse files Browse the repository at this point in the history
## Summary

When SSG is used to generate a website the `window` object can't be
accessed (in the server portion of the build). This PR adds an
availability check for when `window` is used.

## Test plan

<!-- Provide a minimal but complete code snippet that can be used to
test out this change along with instructions how to run it and a
description of the expected behavior. -->
  • Loading branch information
bartlomiejbloniarz authored Aug 25, 2023
1 parent 9b453a1 commit a1f04b2
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
11 changes: 10 additions & 1 deletion src/reanimated2/PlatformChecker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,17 @@ export function nativeShouldBeMock() {
return isJest() || isChromeDebugger() || isWindows();
}

export function isWindowAvailable() {
// the window object is unavailable when building the server portion of a site that uses SSG
// this function shouldn't be used to conditionally render components
// https://www.joshwcomeau.com/react/the-perils-of-rehydration/
return typeof window !== 'undefined';
}

export function isReducedMotion() {
return isWeb()
? !window.matchMedia('(prefers-reduced-motion: no-preference)').matches
? isWindowAvailable()
? !window.matchMedia('(prefers-reduced-motion: no-preference)').matches
: false
: global._REANIMATED_IS_REDUCED_MOTION ?? false;
}
13 changes: 12 additions & 1 deletion src/reanimated2/js-reanimated/JSReanimated.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import { isChromeDebugger, isJest, isWeb } from '../PlatformChecker';
import {
isChromeDebugger,
isJest,
isWeb,
isWindowAvailable,
} from '../PlatformChecker';
import type {
ShareableRef,
ShareableSyncDataHolderRef,
Expand Down Expand Up @@ -78,6 +83,12 @@ export default class JSReanimated {
_iosReferenceFrame: number,
eventHandler: ShareableRef<(data: Value3D | ValueRotation) => void>
): number {
if (!isWindowAvailable()) {
// the window object is unavailable when building the server portion of a site that uses SSG
// this check is here to ensure that the server build won't fail
return -1;
}

if (this.platform === undefined) {
this.detectPlatform();
}
Expand Down

0 comments on commit a1f04b2

Please sign in to comment.