Skip to content

Commit

Permalink
Apply React polyfill directly to globalThis
Browse files Browse the repository at this point in the history
  • Loading branch information
lemonmade committed Nov 19, 2024
1 parent 4a2242e commit deb42fa
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 23 deletions.
5 changes: 5 additions & 0 deletions .changeset/sharp-frogs-bathe.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@remote-dom/react': patch
---

Apply React polyfill directly to `globalThis`
50 changes: 27 additions & 23 deletions packages/react/source/polyfill.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,25 @@
import {window} from '@remote-dom/core/polyfill';

class HTMLIFrameElement extends HTMLElement {}

// React checks whether elements are Iframes on initialization.
defineGlobalProperty('HTMLIFrameElement', {
value: HTMLIFrameElement,
configurable: true,
});

// React ues the `location` and `navigator` properties when printing help text in
// development, and the `Window` polyfill from Remote DOM doesn’t define these properties.
// We copy their implementation from the existing global scope when it exists, and
// provide a minimal working implementation otherwise.
defineGlobalProperty('location', {
value: globalThis.location ?? {protocol: 'https:'},
configurable: true,
});

defineGlobalProperty('navigator', {
value: globalThis.navigator ?? {userAgent: ''},
configurable: true,
});

class CSSStyleDeclaration {
getPropertyValue(_key: string): string | null | undefined {
return undefined;
Expand All @@ -24,27 +42,6 @@ class CSSStyleDeclaration {
}
}

// React ues the `location` property when printing help text in development.
if (!window.location) {
Object.defineProperty(window, 'location', {
value: globalThis.location ?? {protocol: 'https:'},
configurable: true,
});
}

if (!window.navigator) {
Object.defineProperty(window, 'navigator', {
value: globalThis.navigator ?? {userAgent: ''},
configurable: true,
});
}

// React checks whether elements are Iframes on initialization.
Object.defineProperty(window, 'HTMLIFrameElement', {
value: HTMLIFrameElement,
configurable: true,
});

// React checks for a few properties in `document.createElement('div').style`
const STYLE = Symbol('style');
Object.defineProperty(Element.prototype, 'style', {
Expand All @@ -61,3 +58,10 @@ Object.defineProperty(Element.prototype, 'style', {
this.style.cssText = String(cssText);
},
});

function defineGlobalProperty(name: string, descriptor: PropertyDescriptor) {
Object.defineProperty(window, name, descriptor);
Object.defineProperty(globalThis, name, descriptor);
}

export {};

0 comments on commit deb42fa

Please sign in to comment.