Created
June 20, 2022 11:03
-
-
Save sebinsua/862dacbfc7d89885d34d781b955d8b3d to your computer and use it in GitHub Desktop.
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); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
(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
.)