Skip to content

Commit

Permalink
Fix document polyfill executed too late
Browse files Browse the repository at this point in the history
The polyfill MUST be run before react initializes to be effective.
  • Loading branch information
marvinhagemeister committed Sep 14, 2022
1 parent dee3089 commit 71de8e2
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 18 deletions.
24 changes: 24 additions & 0 deletions packages/react/src/error-polyfill.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Make the react build believe that it is running in a page context,
// otherwise react rendering errors won't be logged. This code MUST
// be in the global scope, to ensure that it is run before react
// initializes. This is especially important when bundlers are used
// which will re-order modules by execution priority.
//
// React logic we're working around:
// https://github.com/facebook/react/blob/4e6eec69be632c0c0177c5b1c8a70397d92ee181/packages/shared/invokeGuardedCallbackImpl.js#L53-L237
if (!('window' in globalThis) && !('document' in globalThis)) {
class FakeDocument {
createEvent(type: string) {
return new Event(type);
}

createElement() {
return new EventTarget();
}
}

globalThis.window = globalThis as any;
globalThis.document = new FakeDocument() as any;
}

export {};
19 changes: 1 addition & 18 deletions packages/react/src/render.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import './error-polyfill';
import type {ReactElement} from 'react';
import type {RemoteRoot} from '@remote-ui/core';
import type {RootTag} from 'react-reconciler';
Expand All @@ -15,24 +16,6 @@ const cache = new WeakMap<
}
>();

// Make the react build believe that it is running in a page context,
// otherwise react rendering errors won't be logged. See:
// https://github.com/facebook/react/blob/4e6eec69be632c0c0177c5b1c8a70397d92ee181/packages/shared/invokeGuardedCallbackImpl.js#L53-L237
if (!('window' in globalThis) && !('document' in globalThis)) {
class FakeDocument {
createEvent(type: string) {
return new Event(type);
}

createElement() {
return new EventTarget();
}
}

globalThis.window = globalThis as any;
globalThis.document = new FakeDocument() as any;
}

// @see https://github.com/facebook/react/blob/993ca533b42756811731f6b7791ae06a35ee6b4d/packages/react-reconciler/src/ReactRootTags.js
// I think we are a legacy root?
const LEGACY_ROOT: RootTag = 0;
Expand Down

0 comments on commit 71de8e2

Please sign in to comment.