Skip to content

Commit

Permalink
feat: ✨ add Convert to TypeScript feature and update file handling logic
Browse files Browse the repository at this point in the history
  • Loading branch information
ManuelGil committed Feb 21, 2024
1 parent 00389c0 commit d9772b1
Show file tree
Hide file tree
Showing 6 changed files with 164 additions and 20 deletions.
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- Add `covertToTS` method to `example.controller.ts` file to convert a JSON Schema to TypeScript
- Add Convert to TypeScript command to convert a JSON Schema to TypeScript

### Changed

- Update `package.json` to include the Convert to TypeScript command in the contributes section

### Fixed

- Fix `getListFiles` method in `list-files.provider.ts` file to show a message when there are no files

## [1.4.0] - 2024-02-18

### Added
Expand Down
24 changes: 24 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,11 @@
"title": "Get Files in Folder",
"category": "MyExtension"
},
{
"command": "extension-starter-kit.convertToTS",
"title": "Convert JSON to TypeScript",
"category": "MyExtension"
},
{
"command": "extension-starter-kit.feedback.aboutUs",
"title": "About Us",
Expand Down Expand Up @@ -172,6 +177,10 @@
{
"id": "extension-starter-kit.explorer.submenu",
"label": "MyExtension"
},
{
"id": "extension-starter-kit.editor.submenu",
"label": "MyExtension"
}
],
"menus": {
Expand All @@ -195,12 +204,26 @@
"when": "explorerViewletFocus && explorerResourceIsFolder && !explorerResourceIsRoot"
}
],
"editor/context": [
{
"submenu": "extension-starter-kit.editor.submenu",
"group": "1_modification",
"when": "editorHasSelection"
}
],
"extension-starter-kit.explorer.submenu": [
{
"command": "extension-starter-kit.getFilesInFolder",
"alt": "Get Files in Folder",
"group": "extension-starter-kit@1"
}
],
"extension-starter-kit.editor.submenu": [
{
"command": "extension-starter-kit.convertToTS",
"alt": "Convert JSON to TypeScript",
"group": "extension-starter-kit@2"
}
]
},
"viewsWelcome": [
Expand Down Expand Up @@ -284,6 +307,7 @@
"vscode-test": "^1.5.0"
},
"dependencies": {
"json-to-ts": "^1.7.0",
"openai": "^4.26.1"
}
}
90 changes: 88 additions & 2 deletions src/app/controllers/example.controller.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Uri } from 'vscode';
import JsonToTS from 'json-to-ts';
import { Range, TextEditor, Uri, window, workspace } from 'vscode';

// Import the Config and helper functions
import { ExtensionConfig } from '../configs';
Expand All @@ -7,6 +8,7 @@ import {
getPath,
getRelativePath,
saveFile,
showError,
showMessage,
} from '../helpers';

Expand Down Expand Up @@ -100,7 +102,7 @@ export class ExampleController {
});

// If files are found, save them to a file
if (files.length > 0) {
if (files.length !== 0) {
// Write the content to a file
const result = await saveFile(
folder,
Expand All @@ -114,4 +116,88 @@ export class ExampleController {
}
}
}

/**
* The convertToTS method.
*
* @function convertToTS
* @public
* @async
* @memberof ConvertController
* @example
* await controller.convertToTS();
*
* @returns {Promise<TextEditor | void>} The result
*/
async convertToTS(): Promise<TextEditor | void> {
let editor;

if (workspace.workspaceFolders) {
editor = window.activeTextEditor;
} else {
showError('No text editor is active.');
return;
}

const selection = editor?.selection;

if (selection && !selection.isEmpty) {
const selectionRange = new Range(
selection.start.line,
selection.start.character,
selection.end.line,
selection.end.character,
);

const text = editor?.document.getText(selectionRange) || '';

const jsonSchema = this.tryParseJSONObject(text);

if (!jsonSchema) {
showError('Invalid JSON Schema!');
return;
}

const tsSchema = JsonToTS(jsonSchema)
.map((itf) => `export ${itf}\n`)
.join('\n');

const document = await workspace.openTextDocument({
language: 'typescript',
content: tsSchema,
});

return await window.showTextDocument(document);
}

showError('No text is selected!');
return;
}

// Private methods
/**
* The tryParseJSONObject method.
*
* @private
* @memberof ConvertController
* @param {string} str - The string to parse
* @returns {boolean | object} The result
* @example
* const object = controller.tryParseJSONObject(str);
*
* @returns {boolean | object} The result
*/
private tryParseJSONObject(str: string): boolean | object {
try {
var object = JSON.parse(str);

if (object && typeof object === 'object') {
return object;
}
} catch (e) {
return false;
}

return false;
}
}
2 changes: 1 addition & 1 deletion src/app/controllers/list-files.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export class ListFilesController {
maxResults,
});

if (files.length > 0) {
if (files.length !== 0) {
let nodes: NodeModel[] = [];

files.sort((a, b) => a.path.localeCompare(b.path));
Expand Down
32 changes: 20 additions & 12 deletions src/app/providers/list-files.providers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,13 +149,13 @@ export class ListFilesProvider implements TreeDataProvider<NodeModel> {
* @example
* const files = provider.getListFiles();
*
* @returns {Promise<NodeModel[]>} - The list of files
* @returns {Promise<NodeModel[] | undefined>} - The list of files
*/
private async getListFiles(): Promise<NodeModel[]> {
private async getListFiles(): Promise<NodeModel[] | undefined> {
const files = await this.controller.getFiles();

if (!files) {
return [];
return;
}

const nodes: NodeModel[] = [];
Expand All @@ -166,15 +166,23 @@ export class ListFilesProvider implements TreeDataProvider<NodeModel> {
const children = files.filter((file) =>
file.label.toString().endsWith(`.${fileType}`),
);
const node = new NodeModel(
`${fileType}: ${children.length}`,
new ThemeIcon('folder-opened'),
undefined,
undefined,
fileType,
children,
);
nodes.push(node);

if (children.length !== 0) {
const node = new NodeModel(
`${fileType}: ${children.length}`,
new ThemeIcon('folder-opened'),
undefined,
undefined,
fileType,
children,
);

nodes.push(node);
}
}

if (nodes.length === 0) {
return;
}

return nodes;
Expand Down
23 changes: 18 additions & 5 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import * as vscode from 'vscode';

// Import the Configs, Controllers, and Providers
import { ExtensionConfig, EXTENSION_ID } from './app/configs';
import { EXTENSION_ID, ExtensionConfig } from './app/configs';
import {
ExampleController,
FeedbackController,
Expand All @@ -20,11 +20,15 @@ import { OpenAIService } from './app/services';
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {
// The code you place here will be executed every time your command is executed
let resource: vscode.Uri | null = null;
let resource:
| vscode.Uri
| vscode.TextDocument
| vscode.WorkspaceFolder
| undefined;

// Get the resource for the workspace
if (vscode.workspace.workspaceFolders) {
resource = vscode.workspace.workspaceFolders[0].uri;
resource = vscode.workspace.workspaceFolders[0];
}

// -----------------------------------------------------------------
Expand All @@ -33,7 +37,7 @@ export function activate(context: vscode.ExtensionContext) {

// Get the configuration for the extension
const config = new ExtensionConfig(
vscode.workspace.getConfiguration(EXTENSION_ID, resource ?? null),
vscode.workspace.getConfiguration(EXTENSION_ID, resource),
);

// -----------------------------------------------------------------
Expand Down Expand Up @@ -64,7 +68,16 @@ export function activate(context: vscode.ExtensionContext) {
(args) => exampleController.getFilesInFolder(args),
);

context.subscriptions.push(disposableHelloWorld, disposableGetFilesInFolder);
const disposableConvertToTS = vscode.commands.registerCommand(
`${EXTENSION_ID}.convertToTS`,
() => exampleController.convertToTS(),
);

context.subscriptions.push(
disposableHelloWorld,
disposableGetFilesInFolder,
disposableConvertToTS,
);

// -----------------------------------------------------------------
// Register ListFilesController
Expand Down

0 comments on commit d9772b1

Please sign in to comment.