Skip to content

Commit

Permalink
fix(statless-to-stateful): typescript annotation of props will be mai…
Browse files Browse the repository at this point in the history
…ntained when refactoring
  • Loading branch information
Boris Litvinsky committed Oct 30, 2018
1 parent b71ff34 commit a6ac8a9
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/modules/statless-to-stateful.ts
Expand Up @@ -27,6 +27,10 @@ function getRenderFunctionBody(statelessComponentBody) {
}
}

const getParamTypeAnnotation = (param) => {
return param && param.typeAnnotation? t.tsTypeParameterInstantiation([param.typeAnnotation.typeAnnotation]): null;
}

export function statelessToStateful(component) {
const visitor = {
Function(path) {
Expand All @@ -50,7 +54,6 @@ export function statelessToStateful(component) {

}


}

let name;
Expand All @@ -68,7 +71,8 @@ export function statelessToStateful(component) {
const render = t.classMethod('method', t.identifier('render'), [], getRenderFunctionBody(path.node.body));
const superCall = t.expressionStatement(t.callExpression((<any>t).super(), [t.identifier('props')]))
const ctor = t.classMethod('constructor', t.identifier('constructor'), [t.identifier('props')], t.blockStatement([superCall]));
const classDefinition = t.classDeclaration(name, t.identifier('Component'), t.classBody([ctor, render]))
const classDefinition = t.classDeclaration(name, t.identifier('Component'), t.classBody([ctor, render]));
classDefinition.superTypeParameters = getParamTypeAnnotation(path.node.params[0]);
replacementPath.replaceWith(classDefinition)
replacementPath.skip()

Expand Down
11 changes: 11 additions & 0 deletions src/test/jsx.test.ts
Expand Up @@ -173,6 +173,17 @@ describe('jsx module', function () {
expect(fileSystem.replaceTextInFile).to.have.been.calledWith('class Foo extends Component {\n constructor(props) {\n super(props);\n }\n\n render() {\n return (<div></div>);\n }\n\n}', selectedTextStart, selectedTextEnd, '/source.js');
});



it.only('maintains prop type annotation', async () => {
sandbox.stub(editor, 'selectedText').returns(`
const Foo = (props: Props) => (<div></div>)
`);

await statelessToStatefulComponent();

expect(fileSystem.replaceTextInFile).to.have.been.calledWith('class Foo extends Component<Props> {\n constructor(props) {\n super(props);\n }\n\n render() {\n return (<div></div>);\n }\n\n}', selectedTextStart, selectedTextEnd, '/source.js');
});

it('should not convert functions and function calls in the body', async () => {
sandbox.stub(editor, 'selectedText').returns(`
Expand Down

0 comments on commit a6ac8a9

Please sign in to comment.