Skip to content

Commit

Permalink
better getDisplayName
Browse files Browse the repository at this point in the history
  • Loading branch information
eps1lon authored and oliviertassinari committed Aug 31, 2020
1 parent 13ff52d commit 1fb6ae1
Showing 1 changed file with 10 additions and 17 deletions.
27 changes: 10 additions & 17 deletions packages/material-ui-utils/src/getDisplayName.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,16 @@ import { ForwardRef, Memo } from 'react-is';
// Simplified polyfill for IE 11 support
// https://github.com/JamesMGreene/Function.name/blob/58b314d4a983110c3682f1228f845d39ccca1817/Function.name.js#L3
const fnNameMatchRegex = /^\s*function(?:\s|\s*\/\*.*\*\/\s*)+([^(\s/]*)\s*/;
export function getFunctionName(fn: any) {
export function getFunctionName(fn: Function): string {
const match = `${fn}`.match(fnNameMatchRegex);
const name = match && match[1];
return name || '';
}

/**
* @param {function} Component
* @param {string} fallback
* @returns {string | undefined}
*/
function getFunctionComponentName(Component: any, fallback = '') {
function getFunctionComponentName(
Component: React.FunctionComponent | React.ComponentClass,
fallback = '',
) {
return Component.displayName || Component.name || getFunctionName(Component) || fallback;
}

Expand All @@ -30,11 +28,8 @@ function getWrappedName(outerType: any, innerType: any, wrapperName: string) {
* cherry-pick from
* https://github.com/facebook/react/blob/769b1f270e1251d9dbdce0fcbd9e92e502d059b8/packages/shared/getComponentName.js
* originally forked from recompose/getDisplayName with added IE 11 support
*
* @param {React.ElementType} Component
* @returns {string | undefined}
*/
export default function getDisplayName(Component: React.ElementType) {
export default function getDisplayName(Component: React.ElementType): string | undefined {
if (Component == null) {
return undefined;
}
Expand All @@ -47,15 +42,13 @@ export default function getDisplayName(Component: React.ElementType) {
return getFunctionComponentName(Component, 'Component');
}

// TypeScript can't have components as objects but they exist in the form of `memo` or `Suspense`
if (typeof Component === 'object') {
// @ts-ignore
switch (Component.$$typeof) {
switch ((Component as any).$$typeof) {
case ForwardRef:
// @ts-ignore
return getWrappedName(Component, Component.render, 'ForwardRef');
return getWrappedName(Component, (Component as any).render, 'ForwardRef');
case Memo:
// @ts-ignore
return getWrappedName(Component, Component.type, 'memo');
return getWrappedName(Component, (Component as any).type, 'memo');
default:
return undefined;
}
Expand Down

0 comments on commit 1fb6ae1

Please sign in to comment.