Skip to content

Commit 492e4ae

Browse files
authored
fix: add support to activate the extension on json files (#127)
1 parent b199ab2 commit 492e4ae

File tree

2 files changed

+20
-6
lines changed

2 files changed

+20
-6
lines changed

package.json

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,12 +50,12 @@
5050
"menus": {
5151
"editor/title": [
5252
{
53-
"when": "resourceLangId == yaml && asyncapi.isAsyncAPI",
53+
"when": "resourceLangId == json || resourceLangId == yaml && asyncapi.isAsyncAPI",
5454
"command": "asyncapi.preview",
5555
"group": "navigation"
5656
},
5757
{
58-
"when": "resourceLangId == yaml && asyncapi.isAsyncAPI",
58+
"when": "resourceLangId == json || resourceLangId == yaml && asyncapi.isAsyncAPI",
5959
"command": "asyncapi.preview"
6060
}
6161
],

src/extension.ts

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ export function activate(context: vscode.ExtensionContext) {
88

99
// sets context to show "AsyncAPI Preview" button on Editor Title Bar
1010
function setAsyncAPIPreviewContext(document: vscode.TextDocument) {
11-
const isAsyncAPI = (document.languageId === 'yml' || document.languageId === 'yaml') && isAsyncAPIFile(document.getText());
11+
const isAsyncAPI = isAsyncAPIFile(document);
1212
console.log('Setting context for asyncapi.isAsyncAPI', isAsyncAPI, document.uri.fsPath);
1313
vscode.commands.executeCommand('setContext', 'asyncapi.isAsyncAPI', isAsyncAPI);
1414
}
@@ -41,8 +41,22 @@ export function activate(context: vscode.ExtensionContext) {
4141
context.subscriptions.push(disposable);
4242
}
4343

44-
function isAsyncAPIFile(text: string) {
45-
return text.includes('asyncapi:');
44+
function isAsyncAPIFile(document?: vscode.TextDocument) {
45+
if (!document) {
46+
return false;
47+
}
48+
if (document.languageId === 'json') {
49+
try {
50+
const json = JSON.parse(document.getText());
51+
return json.asyncapi;
52+
} catch (e) {
53+
return false;
54+
}
55+
}
56+
if(document.languageId === 'yml' || document.languageId === 'yaml') {
57+
return document.getText().match('^asyncapi:') !== null;
58+
}
59+
return false;
4660
}
4761

4862
function openAsyncAPI(context: vscode.ExtensionContext, uri: vscode.Uri) {
@@ -73,7 +87,7 @@ function openAsyncAPI(context: vscode.ExtensionContext, uri: vscode.Uri) {
7387
}
7488

7589
async function promptForAsyncapiFile() {
76-
if (isAsyncAPIFile(vscode.window.activeTextEditor?.document.getText() || '')) {
90+
if (isAsyncAPIFile(vscode.window.activeTextEditor?.document)) {
7791
return vscode.window.activeTextEditor?.document.uri;
7892
}
7993
return await vscode.window.showOpenDialog({

0 commit comments

Comments
 (0)