-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[core] Generate propTypes #2395
Merged
Merged
Changes from 8 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
f6ac768
[core] Generate propTypes
m4theushw b2f6b4c
ignore prettier files
m4theushw d6c27d0
add propTypes on all components
m4theushw 1a44dd2
add propTypes only on exported components
m4theushw 33b0803
fix using wrong @material-ui/utils
m4theushw d885d63
add propTypes to more components
m4theushw e88ba3b
Merge branch 'next' into proptypes
m4theushw 614cfaf
yarn proptypes
m4theushw e548aaa
TODO
m4theushw 6163d24
fix warning
m4theushw 6c6a7ef
Merge branch 'next' into proptypes
m4theushw d406f1a
use same version of @material-ui/utils
m4theushw e3027f1
skip a few big object-type props
m4theushw ab215e5
Merge branch 'next' into proptypes
m4theushw File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,133 @@ | ||
import * as yargs from 'yargs'; | ||
import * as path from 'path'; | ||
import * as fse from 'fs-extra'; | ||
import * as prettier from 'prettier'; | ||
import * as ttp from '@material-ui/monorepo/packages/typescript-to-proptypes/src'; | ||
import { fixBabelGeneratorIssues, fixLineEndings } from 'docs/scripts/helpers'; | ||
|
||
const tsconfig = ttp.loadConfig(path.resolve(__dirname, '../../tsconfig.json')); | ||
|
||
const prettierConfig = prettier.resolveConfig.sync(process.cwd(), { | ||
config: path.join(__dirname, '../../prettier.config.js'), | ||
}); | ||
|
||
async function generateProptypes(program: ttp.ts.Program, sourceFile: string) { | ||
const proptypes = ttp.parseFromProgram(sourceFile, program, { checkDeclarations: true }); | ||
|
||
if (proptypes.body.length === 0) { | ||
return; | ||
} | ||
|
||
const sourceContent = await fse.readFile(sourceFile, 'utf8'); | ||
|
||
const result = ttp.inject(proptypes, sourceContent, { | ||
disablePropTypesTypeChecking: true, | ||
comment: [ | ||
'----------------------------- Warning --------------------------------', | ||
'| These PropTypes are generated from the TypeScript type definitions |', | ||
'| To update them edit the TypeScript types and run "yarn proptypes" |', | ||
'----------------------------------------------------------------------', | ||
].join('\n'), | ||
reconcilePropTypes: (prop, previous, generated) => { | ||
const usedCustomValidator = previous !== undefined && !previous.startsWith('PropTypes'); | ||
const ignoreGenerated = | ||
previous !== undefined && | ||
previous.startsWith('PropTypes /* @typescript-to-proptypes-ignore */'); | ||
return usedCustomValidator || ignoreGenerated ? previous! : generated; | ||
}, | ||
shouldInclude: ({ component, prop }) => { | ||
if (['children', 'state'].includes(prop.name) && component.name.startsWith('DataGrid')) { | ||
return false; | ||
} | ||
let shouldDocument = true; | ||
prop.filenames.forEach((filename) => { | ||
// Don't include props from external dependencies | ||
if (/node_modules/.test(filename)) { | ||
shouldDocument = false; | ||
} | ||
}); | ||
return shouldDocument; | ||
}, | ||
}); | ||
|
||
if (!result) { | ||
throw new Error('Unable to produce inject propTypes into code.'); | ||
} | ||
|
||
const prettified = prettier.format(result, { ...prettierConfig, filepath: sourceFile }); | ||
const formatted = fixBabelGeneratorIssues(prettified); | ||
const correctedLineEndings = fixLineEndings(sourceContent, formatted); | ||
|
||
await fse.writeFile(sourceFile, correctedLineEndings); | ||
} | ||
|
||
function findComponents(folderPath) { | ||
const files = fse.readdirSync(folderPath, { withFileTypes: true }); | ||
return files.reduce((acc, file) => { | ||
if (file.isDirectory()) { | ||
const filesInFolder = findComponents(path.join(folderPath, file.name)); | ||
return [...acc, ...filesInFolder]; | ||
} | ||
if (/[A-Z]+.*\.tsx/.test(file.name)) { | ||
return [...acc, path.join(folderPath, file.name)]; | ||
} | ||
return acc; | ||
}, []); | ||
} | ||
|
||
async function run() { | ||
const componentsToAddPropTypes = [ | ||
path.resolve(__dirname, '../../packages/grid/data-grid/src/DataGrid.tsx'), | ||
path.resolve(__dirname, '../../packages/grid/x-grid/src/DataGridPro.tsx'), | ||
m4theushw marked this conversation as resolved.
Show resolved
Hide resolved
|
||
]; | ||
|
||
const indexPath = path.resolve(__dirname, '../../packages/grid/_modules_/index.ts'); | ||
const program = ttp.createTSProgram([...componentsToAddPropTypes, indexPath], tsconfig); | ||
const checker = program.getTypeChecker(); | ||
const indexFile = program.getSourceFile(indexPath)!; | ||
const symbol = checker.getSymbolAtLocation(indexFile); | ||
const exports = checker.getExportsOfModule(symbol!); | ||
|
||
const componentsFolder = path.resolve(__dirname, '../../packages/grid/_modules_/grid/components'); | ||
const components = findComponents(componentsFolder); | ||
components.forEach((component) => { | ||
const componentName = path.basename(component).replace('.tsx', ''); | ||
const isExported = exports.find((e) => e.name === componentName); | ||
if (isExported) { | ||
componentsToAddPropTypes.push(component); | ||
} | ||
}); | ||
|
||
const promises = componentsToAddPropTypes.map<Promise<void>>(async (file) => { | ||
try { | ||
await generateProptypes(program, file); | ||
} catch (error) { | ||
error.message = `${file}: ${error.message}`; | ||
throw error; | ||
} | ||
}); | ||
|
||
const results = await Promise.allSettled(promises); | ||
|
||
const fails = results.filter((result): result is PromiseRejectedResult => { | ||
return result.status === 'rejected'; | ||
}); | ||
|
||
fails.forEach((result) => { | ||
console.error(result.reason); | ||
}); | ||
if (fails.length > 0) { | ||
process.exit(1); | ||
} | ||
} | ||
|
||
yargs | ||
.command({ | ||
command: '$0', | ||
describe: 'Generates Component.propTypes from TypeScript declarations', | ||
handler: run, | ||
}) | ||
.help() | ||
.strict(true) | ||
.version(false) | ||
.parse(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -19,6 +19,7 @@ | |
"stylelint": "stylelint '**/*.js' '**/*.ts' '**/*.tsx'", | ||
"prettier": "node ./scripts/prettier.js --branch master", | ||
"prettier:all": "node ./scripts/prettier.js write", | ||
"proptypes": "cross-env BABEL_ENV=development babel-node -i \"/node_modules/(?!@material-ui)/\" -x .ts,.tsx,.js ./docs/scripts/generateProptypes.ts", | ||
"size:snapshot": "node --max-old-space-size=2048 ./scripts/sizeSnapshot/create", | ||
"size:why": "yarn size:snapshot --analyze --accurateBundles", | ||
"test": "lerna run test --parallel", | ||
|
@@ -61,6 +62,7 @@ | |
"@material-ui/core": "^4.9.12", | ||
"@material-ui/icons": "^4.11.2", | ||
"@material-ui/lab": "^4.0.0-alpha.54", | ||
"@material-ui/utils": "^5.0.0-beta.4", | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I don't know why but without adding it here, the build fails. The dependency is already added to the DataGrid's package.json. |
||
"@material-ui/monorepo": "/~https://github.com/mui-org/material-ui.git#next", | ||
"@material-ui/unstyled": "next", | ||
"@rollup/plugin-node-resolve": "^13.0.4", | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It seems to work without, is it still needed?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Here it crashes if I remove.