Skip to content

Commit

Permalink
Bare-basics typescript support
Browse files Browse the repository at this point in the history
  • Loading branch information
goto-bus-stop committed Jan 6, 2025
1 parent 7dbde73 commit f5ebba9
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
27 changes: 22 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
* (c) Call-Em-All
*/

import ts from '@babel/plugin-syntax-typescript'
import { parse } from 'react-docgen'
import { parse as parseDoctrine } from 'doctrine'

Expand All @@ -27,7 +28,16 @@ function generatePropType (type) {
}
}

function generateDescription (required, description, type) {
function generateTsPropType (type) {
switch (type.name) {
case 'union':
return type.raw
default:
return type.name
}
}

function generateDescription (required, description, type, tsType) {
const parsed = parseDoctrine(description)

// two new lines result in a newline in the table. all other new lines
Expand All @@ -39,7 +49,7 @@ function generateDescription (required, description, type) {
}
let signature = ''

if (type.name === 'func' && parsed.tags.length > 0) {
if (type != null && type.name === 'func' && parsed.tags.length > 0) {
// Remove new lines from tag descriptions to avoid markdown errors.
parsed.tags.forEach((tag) => {
if (tag.description) {
Expand Down Expand Up @@ -80,12 +90,18 @@ function render (code) {
let text = '| Name | Type | Default | Description |\n' +
'|:-----|:-----|:-----|:-----|\n'

const [componentInfo] = parse(code)
const [componentInfo] = parse(code, {
babelOptions: {
plugins: [
[ts, { isTSX: true }]
]
}
})

Object.keys(componentInfo.props).forEach((key) => {
const prop = componentInfo.props[key]

const description = generateDescription(prop.required, prop.description, prop.type)
const description = generateDescription(prop.required, prop.description, prop.type, prop.tsType)

if (description === null) return

Expand All @@ -99,7 +115,8 @@ function render (code) {
key = `<span style="color: #31a148">${key} *</span>` // eslint-disable-line no-param-reassign
}

text += `| ${key} | ${generatePropType(prop.type)} | ${defaultValue} | ${description} |\n`
const ty = prop.tsType ? generateTsPropType(prop.tsType) : generatePropType(prop.type)
text += `| ${key} | ${ty} | ${defaultValue} | ${description} |\n`
})

return text
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"url": "https://github.com/goto-bus-stop/prop-types-table/issues"
},
"dependencies": {
"@babel/plugin-syntax-typescript": "^7.25.9",
"doctrine": "^3.0.0",
"react-docgen": "^7.1.0"
},
Expand Down

0 comments on commit f5ebba9

Please sign in to comment.