Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/mixin-class-props.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'react-docgen': patch
---

Find TypeScript props of class components extending a mixin call such as
`class X extends withFoo(React.Component<Props>)`.
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,18 @@ exports[`getTypeFromReactComponent > Flow > stateless > finds param type annotat
]
`;

exports[`getTypeFromReactComponent > TypeScript > classes > finds props type in mixin base class params 1`] = `
[
Node {
"type": "TSTypeReference",
"typeName": Node {
"name": "Props",
"type": "Identifier",
},
},
]
`;

exports[`getTypeFromReactComponent > TypeScript > classes > finds props type in params 1`] = `
[
Node {
Expand All @@ -107,6 +119,18 @@ exports[`getTypeFromReactComponent > TypeScript > classes > finds props type in
]
`;

exports[`getTypeFromReactComponent > TypeScript > classes > finds props type in properties when extending a mixin without params 1`] = `
[
Node {
"type": "TSTypeReference",
"typeName": Node {
"name": "Props",
"type": "Identifier",
},
},
]
`;

exports[`getTypeFromReactComponent > TypeScript > stateless > does not find generic forwardRef type annotation on typo 1`] = `[]`;

exports[`getTypeFromReactComponent > TypeScript > stateless > finds generic forwardRef type annotation 1`] = `
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type {
} from '@babel/types';
import { parse, parseTypescript } from '../../../tests/utils';
import getTypeFromReactComponent from '../getTypeFromReactComponent.js';
import { parse as parseComponent } from '../../main.js';
import { describe, expect, test } from 'vitest';
import type { NodePath } from '@babel/traverse';

Expand Down Expand Up @@ -154,6 +155,125 @@ describe('getTypeFromReactComponent', () => {

expect(getTypeFromReactComponent(path)).toMatchSnapshot();
});

test('finds props type in mixin base class params', () => {
const path = parseTypescript.statementLast<ClassDeclaration>(
`import React from 'react';
class X extends withFoo(React.Component<Props, State>) {
render() {}
}`,
);

expect(getTypeFromReactComponent(path)).toMatchSnapshot();
});

test('finds mixin props using Babel 8 type argument fields', () => {
const path = parseTypescript.statementLast<ClassDeclaration>(
`import React from 'react';
class X extends withFoo(React.Component<Props>) {
render() {}
}`,
);
const superClass = path.get('superClass');

if (!superClass.isCallExpression()) {
throw new Error('Expected a mixin call');
}
const [baseClass] = superClass.get('arguments');

if (!baseClass?.isTSInstantiationExpression()) {
throw new Error('Expected an instantiated base class');
}

// Exercise Babel 8's AST shape even when running with Babel 7.
if (!('typeArguments' in baseClass.node)) {
Object.assign(baseClass.node, {
typeArguments: baseClass.node.typeParameters,
});
Reflect.deleteProperty(baseClass.node, 'typeParameters');
}

expect(getTypeFromReactComponent(path)[0]?.node).toMatchObject({
type: 'TSTypeReference',
typeName: { type: 'Identifier', name: 'Props' },
});
});

test.each(['configure<Options>', 'Other.Component<Options>'])(
'preserves declared props when the mixin argument is %s',
(argument) => {
const result = parseComponent(
`import Other from 'other';
interface Props { value: string }
interface Options { unrelated: number }
function configure<T>() {}
export class Button extends makeComponent(${argument}) {
props: Props;
render() { return <button />; }
}`,
{ filename: 'component.tsx' },
);

expect(result[0]?.props).toEqual({
value: {
required: true,
tsType: { name: 'string' },
description: '',
},
});
},
);

test.each(['Component', 'PureComponent'])(
'finds mixin props from an aliased React %s import',
(component) => {
const result = parseComponent(
`import { ${component} as Base } from 'react';
interface Props { value: string }
export class Button extends withFoo(Base<Props>) {
render() { return <button />; }
}`,
{ filename: 'component.tsx' },
);

expect(result[0]?.props?.value?.tsType).toEqual({ name: 'string' });
},
);

test.each(['PropsWithChildren', 'PropsWithRef', 'PropsWithoutRef'])(
'unwraps %s in mixin base class props',
(wrapper) => {
const result = parseComponent(
`import React from 'react';
interface Props { value: string }
export class Button extends withFoo(React.Component<React.${wrapper}<Props>>) {
props: Props;
render() { return <button />; }
}`,
{ filename: 'component.tsx' },
);

expect(result[0]?.props).toEqual({
value: {
required: true,
tsType: { name: 'string' },
description: '',
},
});
},
);

test('finds props type in properties when extending a mixin without params', () => {
const path = parseTypescript.statementLast<ClassDeclaration>(
`import React from 'react';
class X extends withFoo(React.Component) {
props: Props;
render() {}
}`,
);

expect(getTypeFromReactComponent(path)).toMatchSnapshot();
});
});
});

Expand Down
56 changes: 49 additions & 7 deletions packages/react-docgen/src/utils/getTypeFromReactComponent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import type {
TSTypeParameterDeclaration,
TSTypeParameterInstantiation,
TypeParameterDeclaration,
ClassDeclaration,
ClassExpression,
TypeParameterInstantiation,
VariableDeclarator,
} from '@babel/types';
Expand Down Expand Up @@ -81,6 +83,37 @@ function findAssignedVariableType(
return null;
}

/**
* Finds the props type of a class extending a mixin call, e.g.
* `class X extends withFoo(React.Component<Props>) {}`.
*/
function getMixinSuperClassPropsPath(
classDefinition: NodePath<ClassDeclaration | ClassExpression>,
): NodePath | null {
const superClass = classDefinition.get('superClass');

if (!superClass.isCallExpression()) return null;

const [baseClass] = superClass.get('arguments');

if (!baseClass?.isTSInstantiationExpression()) return null;

const expression = baseClass.get('expression');

if (
!isReactBuiltinReference(expression, 'Component') &&
!isReactBuiltinReference(expression, 'PureComponent')
) {
return null;
}

const typeParameters = getTypeArguments(baseClass);

if (!typeParameters.hasNode()) return null;

return typeParameters.get('params')[0] ?? null;
}

/**
* Given an React component (stateless or class) tries to find
* flow or TS types for the props. It may find multiple types.
Expand Down Expand Up @@ -113,16 +146,25 @@ export default (componentDefinition: NodePath): NodePath[] => {
}
}
} else {
const propsMemberPath = getMemberValuePath(componentDefinition, 'props');
const mixinPropsPath = getMixinSuperClassPropsPath(componentDefinition);

if (!propsMemberPath) {
return [];
}
if (mixinPropsPath) {
typePaths.push(mixinPropsPath);
} else {
const propsMemberPath = getMemberValuePath(
componentDefinition,
'props',
);

const typeAnnotation = getTypeAnnotation(propsMemberPath.parentPath);
if (!propsMemberPath) {
return [];
}

if (typeAnnotation) {
typePaths.push(typeAnnotation);
const typeAnnotation = getTypeAnnotation(propsMemberPath.parentPath);

if (typeAnnotation) {
typePaths.push(typeAnnotation);
}
}
}
} else {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import React from 'react';

interface Props {
/**
* description of value
*/
value: string;
}

function withFoo<T extends new (...args: any[]) => React.Component<any>>(
Base: T,
) {
return class extends Base {};
}

export default class MyComponent extends withFoo(React.Component<Props>) {
render() {
return <div />;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2163,3 +2163,22 @@ exports[`integration > fixtures > processes component "test-all-imports.tsx" wit
},
]
`;

exports[`integration > fixtures > processes component "ts-extends-mixin.tsx" without errors 1`] = `
[
{
"description": "",
"displayName": "MyComponent",
"methods": [],
"props": {
"value": {
"description": "description of value",
"required": true,
"tsType": {
"name": "string",
},
},
},
},
]
`;
Loading