This file contains 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
import React from 'react'; | |
// @ts-ignore | |
globalThis.whenCalledBy = function whenCalledBy(fnName: string, depth = Infinity) { | |
const [, , , ...stackTraceLines] = (new Error().stack ?? '') | |
.split('\n') | |
.map((line) => { | |
const matches = /^at (?<name>(?:\w+|<anonymous>)) ?/.exec(line.trim()); | |
return matches ? matches.groups?.name : undefined; | |
}) | |
.filter((stackLine): stackLine is string => stackLine !== undefined); | |
return (depth !== Infinity ? stackTraceLines.slice(0, depth) : stackTraceLines).some((fn) => fn === fnName); | |
}; | |
// @ts-ignore | |
globalThis.whenRenderedWithin = function whenRenderedWithin(componentName: string, depth = Infinity) { | |
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment | |
const currentStack: string = | |
// @ts-ignore | |
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call | |
React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactDebugCurrentFrame.getCurrentStack() ?? ''; | |
const [, ...componentStack] = currentStack | |
.split('\n') | |
.map((line) => { | |
const matches = /^at (?<name>\w+) ?/.exec(line.trim()); | |
return matches ? matches.groups?.name : undefined; | |
}) | |
.filter((stackLine): stackLine is string => stackLine !== undefined); | |
return (depth !== Infinity ? componentStack.slice(0, depth) : componentStack).some((cn) => cn === componentName); | |
}; |
(Another idea that might be interesting is a set of assertions which both operate as TypeScript checks but also in development mode can call debugger
.)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
We should probably be using this API in order to do things correctly. Potentially need to find out where the renderers come from?
It seems that we can get the ones which were setup in React Devtools using this line:
The
renderers
seem to be setup deep within this function.Edit: Unfortunately
react-devtools-shared
isn't published therefore doing things this way seems impractical. Also, the implementation is more complicated and therefore more fragile to API changes (even more so than using the secret API!).