Last active
May 1, 2020 01:30
-
-
Save eramdam/c0ffb9d598509907f47f7c0e75f58dc0 to your computer and use it in GitHub Desktop.
instance-of-window-aware
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = { | |
overrides: [ | |
{ | |
include: [/react-pose/, /stylefire/], | |
plugins: ['./plugin-transform.js'] | |
} | |
] | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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