Skip to content
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

Add support for React components #5

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,33 @@ This functionality is available in various file types commonly used in React dev

- #### This also works with async snippets.

## Component Generation

You can easily generate a React Component snippet by typing `fc.ComponentName` for functional components
OR `cc.ComponentName` for class components and pressing Enter. The extension automatically expands this into a properly formatted React Component.

For example, typing `fc.ComponentName` and pressing Enter will generate:

```javascript
const ComponentName = () => {
return (
<div></div>
);
};
```

## Component props support

- For example: `fc.ComponentName[firstName, lastName]` will create:

```javascript
const ComponentName = ({firstName, lastName}) => {
return (
<div></div>
);
};
```

### Planned Features

In future updates, we plan to extend support to other React hooks, such as `useContext`, and more, following the same intuitive Emmet-like pattern for quick and efficient coding.
Expand Down
9 changes: 9 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,22 @@
{
"command": "extension.generateReactHookSnippet",
"title": "Generate React Hook"
},
{
"command": "extension.generateReactComponentSnippet",
"title": "Generate React Component"
}
],
"keybindings": [
{
"command": "extension.generateReactHookSnippet",
"key": "enter",
"when": "editorTextFocus && !editorReadonly && editorLangId =~ /javascript|typescript|javascriptreact|typescriptreact/ && isReactHookPattern"
},
{
"command": "extension.generateReactComponentSnippet",
"key": "enter",
"when": "editorTextFocus && !editorReadonly && editorLangId =~ /javascript|typescript|javascriptreact|typescriptreact/ && isReactComponentPattern"
}
]
},
Expand Down
68 changes: 65 additions & 3 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,19 @@ export function activate(context: vscode.ExtensionContext) {
if (editor) {
const position = editor.selection.active;
const line = editor.document.lineAt(position.line).text;
const isPatternPresent = /use(state|effect)\.\w+.*$/i.test(line);
const isReactHookPatternPresent = /use(state|effect)\.\w+.*$/i.test(line);

vscode.commands.executeCommand(
"setContext",
"isReactHookPattern",
isPatternPresent
isReactHookPatternPresent
);

const isComponentPatternPresent = /(fc|cc)\.\w+.*$/i.test(line);
vscode.commands.executeCommand(
"setContext",
"isReactComponentPattern",
isComponentPatternPresent
);
}
});
Expand Down Expand Up @@ -61,7 +68,50 @@ export function activate(context: vscode.ExtensionContext) {
}
);

context.subscriptions.push(disposable);
let disposable2 = vscode.commands.registerCommand(
"extension.generateReactComponentSnippet",
() => {
const editor = vscode.window.activeTextEditor;
if (!editor) {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd encourage using early returns instead of nesting your code, like you did in the extension.generateReactHookSnippet command.

This leads to much simpler code in my eyes and also decreases the cyclomatic complexity
CodeAesthetics made a video about it if you're curious: https://www.youtube.com/watch?v=CFRhGnuXG-4

return;
}

const position = editor.selection.active;
const line = editor.document.lineAt(position.line).text;

const componentRegex = /(fc|cc)\.(\w+)(\[(.*)\])?$/i;
const match = line.match(componentRegex);

if (!match) {
return;
}

const componentType = match[1].toLowerCase();
const componentName = match[2];
const componentProps = match[4];

let snippet = "";

if (componentType === "fc") {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could be rewritten to use a switch/case instead or even better to use an appropriate data structure so you eliminate any branching code in the first place. But I leave that refactoring to another PR / to you :)

snippet = generateFunctionalComponentSnippet(
componentName,
componentProps
);
} else if (componentType === "cc") {
snippet = generateClassComponentSnippet(componentName);
}

// Replace the line with the generated snippet
editor.edit((editBuilder) => {
const range = new vscode.Range(
new vscode.Position(position.line, 0),
new vscode.Position(position.line, line.length)
);
editBuilder.replace(range, snippet);
});
}
);
context.subscriptions.push(disposable2);

// Helper functions
function capitalizeFirstLetter(string: string): string {
Expand All @@ -83,4 +133,16 @@ export function activate(context: vscode.ExtensionContext) {
const functionCall = isAsync ? `${functionName}();` : `${functionName}();`;
return `useEffect(() => {\n ${asyncSnippet}function ${functionName}() {\n // Your code here\n }\n ${functionCall}\n}, ${dependencies});`;
}

function generateFunctionalComponentSnippet(
componentName: string,
componentProps?: string
): string {
const props = componentProps ? `{${componentProps}}` : "";
return `const ${componentName} = (${props}) => {\n return (\n <div></div>\n );\n};`;
}

function generateClassComponentSnippet(componentName: string): string {
return `class ${componentName} extends React.Component {\n render() {\n return (\n <div></div>\n );\n }\n}`;
}
}