Skip to content

Instantly share code, notes, and snippets.

@eramdam
Last active May 1, 2020 01:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eramdam/c0ffb9d598509907f47f7c0e75f58dc0 to your computer and use it in GitHub Desktop.
Save eramdam/c0ffb9d598509907f47f7c0e75f58dc0 to your computer and use it in GitHub Desktop.
instance-of-window-aware
module.exports = {
overrides: [
{
include: [/react-pose/, /stylefire/],
plugins: ['./plugin-transform.js']
}
]
}
function getWindow(object) {
if (!object || !('ownerDocument' in object))
return undefined;
// This is null on a Node if it is the document itself, but it shouldn't be null on an Element.
const element = object;
const {ownerDocument} = element;
if (!ownerDocument)
return undefined;
// This is null if the document does not have a "browsing context", a situation we don't care about.
const {defaultView} = ownerDocument;
if (!defaultView)
return undefined;
return defaultView;
}
module.exports = function instanceOf(object, constructor) {
// We get the name of the constructor we're looking at.
const constructorName = constructor.name;
if (!constructorName)
return false;
// Get the window of the object.
const defaultView = getWindow(object);
if (!defaultView)
return false;
// Check a constructor with that name exists in that window, which is the global scope in a browsing context.
const elementScope = defaultView;
if (!(constructorName in elementScope))
return false;
const actualConstructor = elementScope[constructorName];
return object instanceof actualConstructor;
};
const {addDefault} = require('@babel/helper-module-imports');
const path = require('path');
module.exports = function convert(babel, opts, dirname) {
const {types: t} = babel;
return {
name: 'instanceof-window-aware',
visitor: {
BinaryExpression(bPath) {
const {node} = bPath;
if (node.operator === 'instanceof')
bPath.replaceWith(
t.callExpression(
addDefault(bPath, path.resolve(dirname, './custom-instanceof.js')),
[node.left, node.right]
)
);
}
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment