55 type ParameterDeclaration ,
66 Project ,
77 type SourceFile ,
8- SyntaxKind ,
9- Type ,
8+ type TextRange ,
9+ VariableDeclaration ,
10+ VariableStatement ,
1011 ts ,
1112} from "ts-morph" ;
1213import { parseProps } from "./props" ;
@@ -15,6 +16,7 @@ import type { Documentation } from "./types";
1516type Component = {
1617 getName : ( ) => string ;
1718 getParameters : ( ) => ParameterDeclaration [ ] ;
19+ getDescription : ( ) => string | undefined ;
1820} ;
1921
2022function getProject ( ) {
@@ -40,37 +42,59 @@ export function parse(code: string): Documentation[] {
4042 const project = getProject ( ) ;
4143 const sourceFile = project . createSourceFile ( "input.tsx" , code ) ;
4244
43- return getExportedComponents ( sourceFile ) . map ( ( f ) => {
45+ return getExportedComponents ( sourceFile ) . map ( ( c ) => {
4446 return {
45- displayName : f . getName ( ) ,
46- props : parseProps ( project , f . getParameters ( ) ) ,
47+ displayName : c . getName ( ) ,
48+ props : parseProps ( project , c . getParameters ( ) ) ,
49+ description : c . getDescription ( ) ,
4750 } ;
4851 } ) ;
4952}
5053
5154function getExportedComponents ( sourceFile : SourceFile ) : Component [ ] {
52- const exportedFunctions = sourceFile
53- . getFunctions ( )
54- . filter ( ( f ) => f . isExported ( ) )
55- . map ( ( f ) => wrapWithName ( f , f . getName ( ) ?? "" ) ) ;
55+ const components : Component [ ] = [ ] ;
5656
57- const exportedVariables = sourceFile
58- . getVariableDeclarations ( )
59- . filter ( ( v ) => v . isExported ( ) && Node . isArrowFunction ( v . getInitializer ( ) ) )
60- . map ( ( v ) =>
61- wrapWithName ( v . getInitializer ( ) as ArrowFunction , v . getName ( ) ! ) ,
62- ) ;
57+ for ( const [ name , value ] of sourceFile . getExportedDeclarations ( ) . entries ( ) ) {
58+ if ( Node . isFunctionDeclaration ( value [ 0 ] ) ) {
59+ components . push (
60+ toComponent (
61+ value [ 0 ] ,
62+ name ,
63+ value [ 0 ] . getJsDocs ( ) [ 0 ] ?. getDescription ( ) . trim ( ) ,
64+ ) ,
65+ ) ;
66+ }
6367
64- return [ ...exportedFunctions , ...exportedVariables ] ;
68+ if ( Node . isVariableDeclaration ( value [ 0 ] ) ) {
69+ const initializer = value [ 0 ] . getInitializer ( ) ;
70+ if ( Node . isArrowFunction ( initializer ) ) {
71+ components . push (
72+ toComponent (
73+ initializer ,
74+ name ,
75+ value [ 0 ]
76+ . getVariableStatement ( )
77+ ?. getJsDocs ( ) [ 0 ]
78+ ?. getDescription ( )
79+ . trim ( ) ,
80+ ) ,
81+ ) ;
82+ }
83+ }
84+ }
85+
86+ return components ;
6587}
6688
67- function wrapWithName (
89+ function toComponent (
6890 f : ArrowFunction | FunctionDeclaration ,
6991 name : string ,
92+ description ?: string ,
7093) : Component {
71- const wrapped = f as Component ;
94+ const wrapped = f as unknown as Component ;
7295
7396 wrapped . getName = ( ) => name ;
97+ wrapped . getDescription = ( ) => description ;
7498
7599 return wrapped ;
76100}
0 commit comments