-
-
Notifications
You must be signed in to change notification settings - Fork 5
feat: Add code actions for React #112
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
Closed
Closed
Changes from 2 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
69655ed
feat: Add 6 code actions for React
AgentRBY 25096e0
Merge branch 'develop' of https://github.com/AgentRBY/typescript-vsco…
AgentRBY 9be27fb
Merge branch 'zardoy:develop' into develop
AgentRBY 97cf74f
Change kind to Surround
AgentRBY b5ada8f
Change name
AgentRBY 6e68621
Remove ganarateJSXMap
AgentRBY 4eacc06
Remove generateJSXMap again
AgentRBY 7090dec
Merge branch 'develop' into pr/AgentRBY/112-1
zardoy 5284a09
demo: reuse wrap memo from ts-react-hooks-tools
zardoy d5a09bf
Merge branch 'zardoy:develop' into develop
AgentRBY 7618aea
Migrate to Code Action snippets
AgentRBY d570e87
patch wrap use range to allow positions
zardoy 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 hidden or 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
37 changes: 37 additions & 0 deletions
37
typescript/src/codeActions/custom/React/conditionalRendering.ts
This file contains hidden or 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,37 @@ | ||
import { CodeAction } from '../../getCodeActions' | ||
|
||
/* | ||
Before: <div></div> | ||
After: { && (<div></div>)} | ||
*/ | ||
export default { | ||
id: 'conditionalRendering', | ||
name: 'Wrap into Condition', | ||
kind: 'refactor.rewrite.conditionalRendering', | ||
zardoy marked this conversation as resolved.
Show resolved
Hide resolved
|
||
tryToApply(sourceFile, position, _range, node, formatOptions) { | ||
if (!node || !position) return | ||
|
||
const isSelection = ts.isJsxOpeningElement(node); | ||
const isSelfClosingElement = node.parent && ts.isJsxSelfClosingElement(node.parent); | ||
|
||
if (!isSelection && !isSelfClosingElement && (!ts.isIdentifier(node) || (!ts.isJsxOpeningElement(node.parent) && !ts.isJsxClosingElement(node.parent)))) { | ||
return; | ||
} | ||
|
||
const wrapNode = isSelection || isSelfClosingElement ? node.parent : node.parent.parent; | ||
|
||
const isTopJsxElement = ts.isJsxElement(wrapNode.parent) | ||
|
||
if (!isTopJsxElement) { | ||
return [ | ||
{ start: wrapNode.getStart(), length: 0, newText: ` && (` }, | ||
{ start: wrapNode.getEnd(), length: 0, newText: `)` }, | ||
] | ||
} | ||
|
||
return [ | ||
{ start: wrapNode.getStart(), length: 0, newText: `{ && (` }, | ||
{ start: wrapNode.getEnd(), length: 0, newText: `)}` }, | ||
] | ||
}, | ||
} satisfies CodeAction |
37 changes: 37 additions & 0 deletions
37
typescript/src/codeActions/custom/React/conditionalRenderingTernary.ts
This file contains hidden or 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,37 @@ | ||
import { CodeAction } from '../../getCodeActions' | ||
|
||
/* | ||
Before: <div></div> | ||
After: { ? (<div></div>) : null} | ||
*/ | ||
export default { | ||
id: 'conditionalRenderingTernary', | ||
name: 'Wrap into Condition (ternary)', | ||
kind: 'refactor.rewrite.conditionalRenderingTernary', | ||
tryToApply(sourceFile, position, _range, node, formatOptions) { | ||
if (!node || !position) return | ||
|
||
const isSelection = ts.isJsxOpeningElement(node); | ||
const isSelfClosingElement = node.parent && ts.isJsxSelfClosingElement(node.parent); | ||
|
||
if (!isSelection && !isSelfClosingElement && (!ts.isIdentifier(node) || (!ts.isJsxOpeningElement(node.parent) && !ts.isJsxClosingElement(node.parent)))) { | ||
return; | ||
} | ||
|
||
const wrapNode = isSelection || isSelfClosingElement ? node.parent : node.parent.parent; | ||
|
||
const isTopJsxElement = ts.isJsxElement(wrapNode.parent) | ||
|
||
if (!isTopJsxElement) { | ||
return [ | ||
{ start: wrapNode.getStart(), length: 0, newText: ` ? (` }, | ||
{ start: wrapNode.getEnd(), length: 0, newText: `) : null` }, | ||
] | ||
} | ||
|
||
return [ | ||
{ start: wrapNode.getStart(), length: 0, newText: `{ ? (` }, | ||
{ start: wrapNode.getEnd(), length: 0, newText: `) : null}` }, | ||
] | ||
}, | ||
} satisfies CodeAction |
57 changes: 57 additions & 0 deletions
57
typescript/src/codeActions/custom/React/createPropsInterface.ts
This file contains hidden or 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,57 @@ | ||
import { autoImportPackage, getChangesTracker } from '../../../utils'; | ||
import { CodeAction } from '../../getCodeActions' | ||
|
||
/* | ||
Before: | ||
const Component = () => {...}; | ||
After: | ||
interface Props {} | ||
const Component: React.FC<Props> = () => {...} | ||
*/ | ||
export default { | ||
id: 'createPropsInterface', | ||
name: 'Create Props Interface', | ||
kind: 'refactor.rewrite.createPropsInterface', | ||
tryToApply(sourceFile, position, _range, node, formatOptions, languageService) { | ||
if (!node || !position) return | ||
|
||
const componentType = node.parent; | ||
|
||
const typeChecker = languageService.getProgram()!.getTypeChecker() | ||
const type = typeChecker.getTypeAtLocation(node) | ||
const typeName = typeChecker.typeToString(type) | ||
|
||
|
||
const isReactFCType = componentType?.parent && ts.isQualifiedName(componentType) && componentType.parent.getFullText().trim() === "React.FC"; | ||
|
||
const isComponentName = !isReactFCType && /(FC<{}>|\) => Element|ReactElement<)/.test(typeName) | ||
|
||
if (!isReactFCType && !isComponentName) { | ||
return undefined; | ||
} | ||
|
||
const reactComponent = isComponentName ? componentType.parent.parent : componentType.parent.parent.parent.parent; | ||
|
||
if (!reactComponent || !ts.isVariableStatement(reactComponent)) { | ||
return undefined; | ||
} | ||
|
||
const newInterface = ts.factory.createInterfaceDeclaration(undefined, 'Props', [], [], []) | ||
|
||
const changesTracker = autoImportPackage(sourceFile, 'react', 'React', true); | ||
|
||
changesTracker.insertNodeBefore(sourceFile, reactComponent, newInterface, true) | ||
|
||
if (isComponentName) { | ||
return [ | ||
{ start: node!.getEnd(), length: 0, newText: `: React.FC<Props>` }, | ||
...changesTracker.getChanges()[0]?.textChanges! | ||
].filter(Boolean) | ||
} | ||
|
||
return [ | ||
{ start: componentType!.getEnd(), length: 0, newText: `<Props>` }, | ||
...changesTracker.getChanges()[0]?.textChanges! | ||
].filter(Boolean) | ||
}, | ||
} satisfies CodeAction |
This file contains hidden or 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,60 @@ | ||
import pluralize from 'pluralize'; | ||
import { isIdentifier, SyntaxKind, TypeFlags } from 'typescript-full'; | ||
import { autoImportPackage, findChildContainingPosition, findParrentNode, getChangesTracker, getIndentFromPos } from '../../../utils'; | ||
import { CodeAction } from '../../getCodeActions' | ||
|
||
/* | ||
Before: {items} | ||
After: {items.map((item) => <div key={item.id}> </div>)} | ||
*/ | ||
export default { | ||
id: 'createJSXMap', | ||
name: 'Map this array to JSX', | ||
kind: 'refactor.rewrite.createJSXMap', | ||
tryToApply(sourceFile, position, _range, node, formatOptions, languageService) { | ||
if (!node || !node.parent || !position) return | ||
|
||
const prevNode = findChildContainingPosition(ts, sourceFile, position - 2); | ||
|
||
if (prevNode && ts.isIdentifier(prevNode)) { | ||
node = prevNode; | ||
} | ||
|
||
if (!ts.isIdentifier(node) || !findParrentNode(node, ts.SyntaxKind.JsxExpression)) { | ||
return undefined; | ||
} | ||
|
||
const typeChecker = languageService.getProgram()!.getTypeChecker() | ||
const type = typeChecker.getTypeAtLocation(node) | ||
|
||
|
||
const typeName = typeChecker.typeToString(type) | ||
const isArrayType = typeName.trim().endsWith('[]'); | ||
|
||
if (!isArrayType) { | ||
return undefined; | ||
} | ||
|
||
const arrayType = type.getNumberIndexType(); | ||
|
||
if (!arrayType) { | ||
return; | ||
} | ||
|
||
const isHasId = arrayType?.getProperties().some(key => key.name === 'id') | ||
|
||
const varName = node.getFullText().trim().replace(/^(?:all)?(.+?)(?:List)?$/, '$1') | ||
let inferredName = varName && pluralize.singular(varName) | ||
|
||
if (inferredName === varName) { | ||
inferredName = "item" | ||
} | ||
|
||
const indent = getIndentFromPos(ts, sourceFile, position) | ||
|
||
return [ | ||
{ start: node.getEnd(), length: 0, newText: `.map((${inferredName}) => (\n${indent} <div${isHasId ? ` key={${inferredName}.id}` : ''}>\n${indent} \n${indent} </div>\n${indent}))` }, | ||
] | ||
|
||
}, | ||
} satisfies CodeAction |
This file contains hidden or 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,66 @@ | ||
import { CodeAction } from '../../getCodeActions' | ||
import { findChildContainingKind, autoImportPackage, deepFindNode } from '../../../utils' | ||
|
||
/* | ||
Before: const Component = () => {...}; | ||
After: const Component = memo(() => {...}) | ||
*/ | ||
export default { | ||
id: 'wrapIntoMemo', | ||
name: 'Wrap into React Memo', | ||
kind: 'refactor.rewrite.wrapIntoMemo', | ||
tryToApply(sourceFile, position, _range, node, formatOptions, languageService) { | ||
if (!node || !node.kind || !position) return | ||
|
||
const typeChecker = languageService.getProgram()!.getTypeChecker() | ||
const type = typeChecker.getTypeAtLocation(node) | ||
const typeName = typeChecker.typeToString(type) | ||
|
||
if (!/(FC<{}>|\) => Element|ReactElement<)/.test(typeName)) { | ||
return undefined; | ||
} | ||
|
||
const reactComponent = findChildContainingKind(node!.parent, ts.SyntaxKind.Identifier); | ||
|
||
const fileExport = findChildContainingKind(sourceFile, ts.SyntaxKind.ExportAssignment); | ||
const isDefaultExport = fileExport?.getChildren().some((children) => children.kind === ts.SyntaxKind.DefaultKeyword); | ||
const exportIdentifier = deepFindNode(fileExport!, (node) => node?.getFullText()?.trim() === reactComponent?.getFullText().trim()); | ||
|
||
const isAlreadyMemo = deepFindNode(fileExport!, (node) => node?.getFullText()?.trim() === "memo") | ||
|
||
if (isAlreadyMemo) { | ||
return undefined; | ||
} | ||
|
||
const changesTracker = autoImportPackage(sourceFile, 'react', 'memo'); | ||
|
||
if (isDefaultExport && exportIdentifier) { | ||
|
||
return [ | ||
{ start: exportIdentifier!.getStart(), length: 0, newText: `memo(` }, | ||
{ start: exportIdentifier!.getEnd(), length: 0, newText: `)` }, | ||
changesTracker.getChanges()[0]?.textChanges[0]! | ||
].filter(Boolean) | ||
} | ||
|
||
const func = (c) => { | ||
if (c.getFullText().trim() === "memo") { | ||
return c | ||
} | ||
|
||
return ts.forEachChild(c, func) | ||
} | ||
|
||
const componentFunction = node?.parent.getChildren().find(ts.isArrowFunction) | ||
|
||
if (!componentFunction) { | ||
return undefined; | ||
} | ||
|
||
return [ | ||
{ start: componentFunction!.getStart(), length: 0, newText: `memo(` }, | ||
{ start: componentFunction!.getEnd(), length: 0, newText: `)` }, | ||
changesTracker.getChanges()[0]?.textChanges[0]! | ||
].filter(Boolean) | ||
}, | ||
} satisfies CodeAction |
49 changes: 49 additions & 0 deletions
49
typescript/src/codeActions/custom/React/wrapIntoUseCallback.ts
This file contains hidden or 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,49 @@ | ||
import { CodeAction } from '../../getCodeActions' | ||
import { autoImportPackage } from '../../../utils' | ||
|
||
/* | ||
Before: const func = () => value; | ||
After: const func = useCallback(() => value, []) | ||
*/ | ||
export default { | ||
id: 'wrapIntoUseCallback', | ||
name: 'Wrap into useCallback', | ||
kind: 'refactor.rewrite.wrapIntoUseCallback', | ||
tryToApply(sourceFile, position, _range, node, formatOptions, languageService) { | ||
if (!node || !position) return | ||
|
||
const [functionIdentifier, _, arrowFunction] = node.parent.getChildren() | ||
|
||
if (!functionIdentifier || !arrowFunction ) { | ||
return undefined; | ||
} | ||
|
||
if (!ts.isIdentifier(functionIdentifier) || !ts.isArrowFunction(arrowFunction)) { | ||
return undefined | ||
} | ||
|
||
// Check is react component | ||
const reactComponent = node?.parent?.parent?.parent?.parent?.parent?.parent | ||
|
||
if (!reactComponent) { | ||
return undefined; | ||
} | ||
|
||
const typeChecker = languageService.getProgram()!.getTypeChecker() | ||
const type = typeChecker.getTypeAtLocation(reactComponent) | ||
const typeName = typeChecker.typeToString(type) | ||
|
||
if (!['FC<', '() => Element', 'ReactElement<'].some((el) => typeName.startsWith(el))) { | ||
return undefined; | ||
} | ||
|
||
const changesTracker = autoImportPackage(sourceFile, 'react', 'useCallback'); | ||
|
||
return [ | ||
{ start: arrowFunction!.getStart(), length: 0, newText: `useCallback(` }, | ||
{ start: arrowFunction!.getEnd(), length: 0, newText: `, [])` }, | ||
changesTracker.getChanges()[0]?.textChanges[0]! | ||
].filter(Boolean); | ||
|
||
}, | ||
} satisfies CodeAction |
This file contains hidden or 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 hidden or 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.
Uh oh!
There was an error while loading. Please reload this page.