diff --git a/CHANGELOG.md b/CHANGELOG.md index 7f98588..e2f2a31 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,26 @@ Check [Keep a Changelog](http://keepachangelog.com/) for recommendations on how --- +## [2.4.0] - (10-5-2020) + + +### Modified +- FAST Template Render HTML preview + - now respects tab settings like other windows + - Re-renders appropriately when sending new content (like changing template params) + - this required a complete rework of the class object + - Re-scoped fast templates to yaml files only (it's really just the best way to go) + - added right click options in explorer view to render template html preview + - added right click option in editor view to render template html preview + - added right click option in Fast view for connected device + - added `Submit` button to bottom of html preview which produces a rendered template output in new json editor + +- onConnect/onDisconnect terminal settings + - updated to only execute if settings are actaully present to be executed + - added logic to track created terminals, use existing terminals (created by extension), and dispose terminals onDisconnect + +--- + ## [2.3.0] - (9-8-2020) ### Added diff --git a/package.json b/package.json index a08b7dd..29fc8cf 100644 --- a/package.json +++ b/package.json @@ -3,7 +3,7 @@ "displayName": "F5 Networks FAST", "description": "(F)5 Networks (A)pplication (S)ervices (T)emplate engine extension", "publisher": "DumpySquare", - "version": "2.3.0", + "version": "2.4.0", "keywords": [ "f5", "f5networks", @@ -49,6 +49,12 @@ "path": "./snippets.json" } ], + "yamlValidation": [ + { + "fileMatch": "*.fast.yml", + "url": "https://github.com/f5devcentral/f5-fast-core/blob/master/schema/template.json" + } + ], "jsonValidation": [ { "fileMatch": "*.as3.json", @@ -416,14 +422,9 @@ "category": "F5-Fast", "enablement": "f5.fastInstalled" }, - { - "command": "f5-fast.renderYmlTemplate", - "title": "Render YAML Template", - "category": "F5-Fast" - }, { "command": "f5-fast.renderHtmlPreview", - "title": "Render HTML Preview", + "title": "Render Fast Template HTML Preview", "category": "F5-Fast" }, { @@ -563,6 +564,10 @@ "command": "f5-fast.deployApp", "group": "F5" }, + { + "command": "f5-fast.renderHtmlPreview", + "group": "F5" + }, { "when": "editorHasSelection", "command": "f5-as3.postDec", @@ -641,6 +646,11 @@ "when": "f5.fastInstalled && resourceExtname =~ /\\.(mst|ya?ml|fast)/", "command": "f5-fast.postTemplate", "group": "F5-Fast" + }, + { + "when": "resourceExtname =~ /\\.(ya?ml)/", + "command": "f5-fast.renderHtmlPreview", + "group": "F5-Fast" } ], "view/title": [ @@ -910,6 +920,10 @@ "command": "f5-fast.deleteFastTempSet", "when": "view == fastView && viewItem == fastTemplateSet" }, + { + "command": "f5-fast.renderHtmlPreview", + "when": "view == fastView && viewItem == fastTemplate" + }, { "command": "f5-as3.fullTenant", "when": "view == as3Tenants && viewItem == as3Tenant" diff --git a/src/editorViews/editorView.ts b/src/editorViews/editorView.ts index 8068b7d..9f0098f 100644 --- a/src/editorViews/editorView.ts +++ b/src/editorViews/editorView.ts @@ -75,10 +75,10 @@ export class TextDocumentView { const newEditorColumn = ext.settings.previewColumn; - /** - * bool, default = false - */ - const enableWebViews = ext.settings.enableWebViews; + // /** + // * bool, default = false + // */ + // const enableWebViews = ext.settings.enableWebViews; /** * Should the new/updated editor take focus? diff --git a/src/editorViews/fastWebView.ts b/src/editorViews/fastWebView.ts new file mode 100644 index 0000000..f785bfe --- /dev/null +++ b/src/editorViews/fastWebView.ts @@ -0,0 +1,161 @@ + +import { WebviewPanel, window, commands, ViewColumn, EventEmitter, Event, Uri } from 'vscode'; + +import { ext } from '../extensionVariables'; +import logger from '../utils/logger'; + +const fast = require('@f5devcentral/f5-fast-core'); + +type HttpResponse = ''; + +export class FastWebView { + + protected _onDidCloseAllWebviewPanels = new EventEmitter(); + protected readonly panels: WebviewPanel[] = []; + private showResponseInDifferentTab = false; + protected activePanel: WebviewPanel | undefined; + protected fastTemplateYml: string | undefined; + protected fastEngine: any | undefined; + + private readonly panelResponses: Map; + + public constructor() { + this.panelResponses = new Map(); + } + + public get onDidCloseAllWebviewPanels(): Event { + + return this._onDidCloseAllWebviewPanels.event; + } + + protected get previewActiveContextKey(): string { + return 'httpResponsePreviewFocus'; + } + + protected setPreviewActiveContext(value: boolean) { + commands.executeCommand('setContext', this.previewActiveContextKey, value); + } + + protected displayRenderedTemplate (tempParams: string) { + /** + * take params from panel submit button + * process through fast with template + * then display in new editor to the right... + */ + + // const final = this.fastEngine.template.render(tempParams); + + // ext.panel.render('text'); + } + + protected async renderHTML(fastYml: string) { + + /** + * add checking for YAML format since we only want to support yaml + * + */ + try { + this.fastEngine = await fast.Template.loadYaml(fastYml); + } catch (e) { + logger.error(e); + window.showErrorMessage(e.message); + } + const schema = this.fastEngine.getParametersSchema(); + const defaultParams = this.fastEngine.getCombinedParameters(); + const htmlData = fast.guiUtils.generateHtmlPreview(schema, defaultParams); + return htmlData; + } + + public async render(fastYml: string) { + + // put the incoming fast template somewhere + this.fastTemplateYml = fastYml; + // create + let html = await this.renderHTML(fastYml); + + let title = 'test-title'; + + const newEditorColumn = ext.settings.previewColumn; + const preserveEditorFocus = ext.settings.preserveEditorFocus; + const newEditorTabForAll = ext.settings.newEditorTabForAll; + let viewColumn: ViewColumn | undefined; + + viewColumn = viewColumn ? viewColumn : newEditorColumn; + + let panel: WebviewPanel; + if (this.showResponseInDifferentTab || this.panels.length === 0) { + panel = window.createWebviewPanel( + 'fast webView', + title, + { viewColumn: viewColumn, preserveFocus: !preserveEditorFocus }, + { + enableFindWidget: true, + enableScripts: true, + retainContextWhenHidden: true + }); + + panel.onDidDispose(() => { + if (panel === this.activePanel) { + this.setPreviewActiveContext(false); + this.activePanel = undefined; + } + + const index = this.panels.findIndex(v => v === panel); + if (index !== -1) { + this.panels.splice(index, 1); + this.panelResponses.delete(panel); + } + if (this.panels.length === 0) { + this._onDidCloseAllWebviewPanels.fire(); + } + }); + + panel.onDidChangeViewState(({ webviewPanel }) => { + const active = this.panels.some(p => p.active); + this.setPreviewActiveContext(active); + this.activePanel = webviewPanel.active ? webviewPanel : undefined; + }); + + panel.webview.onDidReceiveMessage( async message => { + // console.log( message ); + + try { + const final = await this.fastEngine.render(message); + ext.panel.render(final); + } catch (e) { + logger.error(e); + // window.showErrorMessage(e.message); + } + + }); + + this.panels.push(panel); + } else { + panel = this.panels[this.panels.length - 1]; + panel.title = title; + } + + + /** + * Appends the necessary stuff for submit button and getting template params + * move the following to it's own function + */ + const htmlSubmitBtn = ` + + +

+ `; + + html += htmlSubmitBtn; + + panel.webview.html = html; + panel.reveal(viewColumn, !preserveEditorFocus); + this.activePanel = panel; + } + +} \ No newline at end of file diff --git a/src/extension.ts b/src/extension.ts index 541fb91..82ce7a9 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -15,7 +15,7 @@ import * as f5Api from './utils/f5Api'; import * as extAPI from './utils/externalAPIs'; import * as utils from './utils/utils'; import { ext, git, loadConfig } from './extensionVariables'; -import { FastWebViewPanel } from './utils/fastHtmlPreveiwWebview'; +import { FastWebView } from './editorViews/fastWebView'; import * as f5FastApi from './utils/f5FastApi'; import * as f5FastUtils from './utils/f5FastUtils'; import * as rpmMgmt from './utils/rpmMgmt'; @@ -26,7 +26,7 @@ import logger from './utils/logger'; import { TextDocumentView } from './editorViews/editorView'; -const fast = require('@f5devcentral/f5-fast-core'); +// const fast = require('@f5devcentral/f5-fast-core'); export function activate(context: vscode.ExtensionContext) { @@ -59,7 +59,7 @@ export function activate(context: vscode.ExtensionContext) { ext.connectBar.show(); // const webview = new HttpResponseWebview(context); - const panel = new TextDocumentView(); + ext.panel = new TextDocumentView(); // ext.logger = new Logger('f5-fast'); @@ -160,7 +160,7 @@ export function activate(context: vscode.ExtensionContext) { context.subscriptions.push(vscode.commands.registerCommand('f5.getProvider', async () => { const resp: any = await ext.mgmtClient?.makeRequest('/mgmt/tm/auth/source'); - panel.render(resp); + ext.panel.render(resp); })); @@ -176,7 +176,7 @@ export function activate(context: vscode.ExtensionContext) { } const resp: any = await ext.mgmtClient?.makeRequest('/mgmt/shared/identified-devices/config/device-info'); - panel.render(resp); + ext.panel.render(resp); })); context.subscriptions.push(vscode.commands.registerCommand('f5.disconnect', () => { @@ -399,13 +399,13 @@ export function activate(context: vscode.ExtensionContext) { // --- IAPP COMMANDS --- context.subscriptions.push(vscode.commands.registerCommand('f5-tcl.getApp', async (item) => { logger.debug('f5-tcl.getApp command: ', item); - return panel.render(item); + return ext.panel.render(item); })); context.subscriptions.push(vscode.commands.registerCommand('f5-tcl.getTemplate', async (item) => { // returns json view of iApp Template - return panel.render(item); + return ext.panel.render(item); })); @@ -469,7 +469,7 @@ export function activate(context: vscode.ExtensionContext) { context.subscriptions.push(vscode.commands.registerCommand('f5-fast.getInfo', async () => { const resp: any = await ext.mgmtClient?.makeRequest(`/mgmt/shared/fast/info`); - panel.render(resp); + ext.panel.render(resp); })); context.subscriptions.push(vscode.commands.registerCommand('f5-fast.deployApp', async () => { @@ -499,7 +499,7 @@ export function activate(context: vscode.ExtensionContext) { const resp = await f5FastApi.deployFastApp(jsonText); - panel.render(resp); + ext.panel.render(resp); // give a little time to finish before refreshing trees await new Promise(resolve => { setTimeout(resolve, 3000); }); @@ -511,27 +511,27 @@ export function activate(context: vscode.ExtensionContext) { context.subscriptions.push(vscode.commands.registerCommand('f5-fast.getApp', async (tenApp) => { const resp: any = await ext.mgmtClient?.makeRequest(`/mgmt/shared/fast/applications/${tenApp}`); - panel.render(resp); + ext.panel.render(resp); })); context.subscriptions.push(vscode.commands.registerCommand('f5-fast.getTask', async (taskId) => { const resp: any = await ext.mgmtClient?.makeRequest(`/mgmt/shared/fast/tasks/${taskId}`); - panel.render(resp); + ext.panel.render(resp); })); context.subscriptions.push(vscode.commands.registerCommand('f5-fast.getTemplate', async (template) => { const resp: any = await ext.mgmtClient?.makeRequest(`/mgmt/shared/fast/templates/${template}`); - panel.render(resp); + ext.panel.render(resp); })); context.subscriptions.push(vscode.commands.registerCommand('f5-fast.getTemplateSets', async (set) => { const resp: any = await ext.mgmtClient?.makeRequest(`/mgmt/shared/fast/templatesets/${set}`); - panel.render(resp); + ext.panel.render(resp); })); @@ -676,7 +676,7 @@ export function activate(context: vscode.ExtensionContext) { // var device: string | undefined = ext.hostStatusBar.text; // const password = await utils.getPassword(device); const resp = await f5FastApi.delTenApp(tenApp.label); - panel.render(resp); + ext.panel.render(resp); // give a little time to finish await new Promise(resolve => { setTimeout(resolve, 2000); }); @@ -697,67 +697,55 @@ export function activate(context: vscode.ExtensionContext) { })); - context.subscriptions.push(vscode.commands.registerCommand('f5-fast.renderYmlTemplate', async () => { - /** - * this is working through the f5 fast template creating process - * https://clouddocs.f5.com/products/extensions/f5-appsvcs-templates/latest/userguide/template-authoring.html - * - * I think I was trying to take in a params.yml file to feed into an .mst file to test the output before - * being able to upload to fast as a template - */ - - var editor = vscode.window.activeTextEditor; - if (!editor) { return; // No open text editor - } - - let text: string; - if (editor.selection.isEmpty) { - text = editor.document.getText(); // entire editor/doc window - } else { - text = editor.document.getText(editor.selection); // highlighted text - } + const fastPanel = new FastWebView(); + context.subscriptions.push(vscode.commands.registerCommand('f5-fast.renderHtmlPreview', async (item) => { - // const templateEngine = await fast.Template.loadYaml(text); + let text: string = 'empty'; + let title: string = 'Fast Template'; - // const schema = templateEngine.getParametersSchema(); - // // const view = {}; - // const htmlData = fast.guiUtils.generateHtmlPreview(schema, {}); - // displayWebView(htmlData); - // f5FastUtils.templateFromYaml(text); - - })); + if(item?.hasOwnProperty('scheme') && item?.scheme === 'file') { + // right click from explorer view initiation, so load file contents + const fileContents = fs.readFileSync(item.fsPath); + // convert from buffer to string + text = fileContents.toString('utf8'); + // set webPanel name to filename + title = path.parse(item.fsPath).name; + } else if (item?.hasOwnProperty('label')) { + // right click on template from fast view when connected to device + // - ex. label: 'goodFastTemplates/app4' - context.subscriptions.push(vscode.commands.registerCommand('f5-fast.renderHtmlPreview', async () => { + const resp: any = await ext.mgmtClient?.makeRequest(`/mgmt/shared/fast/templates/${item.label}`); - /** - * this view is requested by zinke as part of the template authoring process - * The view should consume/watch the yml file that defines the user inputs for the template - * Every time a save occurs, it should refresh with the changes to streamline the authoring process - */ + if (resp?.data?.sourceText) { + text = resp?.data?.sourceText; + } else { + // alert that we didn't get the response we were looking for + logger.error('f5-fast.renderHtmlPreview command tried to get template details from connected device, but did not get the source text we were looking for'); + } - var editor = vscode.window.activeTextEditor; - if (!editor) { return; // No open text editor - } - let text: string; - if (editor.selection.isEmpty) { - text = editor.document.getText(); // entire editor/doc window } else { - text = editor.document.getText(editor.selection); // highlighted text - } - - const templateEngine = await fast.Template.loadYaml(text); - - const schema = templateEngine.getParametersSchema(); + // right-click or commandpalette initiation, so get editor text + var editor = vscode.window.activeTextEditor; + if (editor) { + if (editor?.selection?.isEmpty) { + text = editor.document.getText(); // entire editor/doc window + } else { + text = editor.document.getText(editor.selection); // highlighted text + } + } + } - const htmlData = fast.guiUtils.generateHtmlPreview(schema, {}); - FastWebViewPanel.render(context.extensionPath, htmlData); - // f5FastUtils.renderHtmlPreview(text); + // const templateEngine = await fast.Template.loadYaml(text); + // const schema = templateEngine.getParametersSchema(); + // const htmlData = fast.guiUtils.generateHtmlPreview(schema, {}); + // fastPanel.render(htmlData, title, ); + fastPanel.render(text); })); - + @@ -789,7 +777,7 @@ export function activate(context: vscode.ExtensionContext) { tenant = tenant ? tenant : ''; const resp: any = await ext.mgmtClient?.makeRequest(`/mgmt/shared/appsvcs/declare/${tenant}`); - panel.render(resp); + ext.panel.render(resp); })); @@ -828,7 +816,7 @@ export function activate(context: vscode.ExtensionContext) { }, async () => { const resp: any = await ext.mgmtClient?.makeRequest(`/mgmt/shared/appsvcs/task/${id}`); - panel.render(resp); + ext.panel.render(resp); }); })); @@ -861,7 +849,7 @@ export function activate(context: vscode.ExtensionContext) { } const resp = await f5Api.postAS3Dec(postParam, JSON.parse(text)); - panel.render(resp); + ext.panel.render(resp); as3Tree.refresh(); })); @@ -995,7 +983,7 @@ export function activate(context: vscode.ExtensionContext) { context.subscriptions.push(vscode.commands.registerCommand('f5-ts.info', async () => { const resp: any = await ext.mgmtClient?.makeRequest('/mgmt/shared/telemetry/info'); - panel.render(resp); + ext.panel.render(resp); })); @@ -1005,7 +993,7 @@ export function activate(context: vscode.ExtensionContext) { title: `Getting TS Dec` }, async () => { const resp: any = await ext.mgmtClient?.makeRequest(`/mgmt/shared/telemetry/declare`); - panel.render(resp); + ext.panel.render(resp); }); })); @@ -1034,14 +1022,14 @@ export function activate(context: vscode.ExtensionContext) { method: 'POST', body: JSON.parse(text) }); - panel.render(resp); + ext.panel.render(resp); }); })); context.subscriptions.push(vscode.commands.registerCommand('f5.getGitHubExample', async (decUrl) => { const resp = await extAPI.makeRequest({ url: decUrl }); - return panel.render(resp); + return ext.panel.render(resp); })); @@ -1068,7 +1056,7 @@ export function activate(context: vscode.ExtensionContext) { title: `Getting DO Dec` }, async () => { const resp: any = await ext.mgmtClient?.makeRequest(`/mgmt/shared/declarative-onboarding/`); - panel.render(resp); + ext.panel.render(resp); }); @@ -1093,7 +1081,7 @@ export function activate(context: vscode.ExtensionContext) { } const resp = await f5Api.postDoDec(JSON.parse(text)); - panel.render(resp); + ext.panel.render(resp); })); @@ -1104,7 +1092,7 @@ export function activate(context: vscode.ExtensionContext) { title: `Getting DO Inspect` }, async () => { const resp: any = await ext.mgmtClient?.makeRequest(`/mgmt/shared/declarative-onboarding/inspect`); - panel.render(resp); + ext.panel.render(resp); }); })); @@ -1118,7 +1106,7 @@ export function activate(context: vscode.ExtensionContext) { title: `Getting DO Tasks` }, async () => { const resp: any = await ext.mgmtClient?.makeRequest(`/mgmt/shared/declarative-onboarding/task`); - panel.render(resp); + ext.panel.render(resp); }); })); @@ -1303,7 +1291,7 @@ export function activate(context: vscode.ExtensionContext) { } if(resp) { - panel.render(resp); + ext.panel.render(resp); } } @@ -1327,7 +1315,7 @@ export function activate(context: vscode.ExtensionContext) { } }); - panel.render(resp.data.commandResult); + ext.panel.render(resp.data.commandResult); })); diff --git a/src/extensionVariables.ts b/src/extensionVariables.ts index 53597b9..d5dea73 100644 --- a/src/extensionVariables.ts +++ b/src/extensionVariables.ts @@ -3,10 +3,11 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { ExtensionContext, StatusBarItem, workspace, ViewColumn, commands } from "vscode"; +import { ExtensionContext, StatusBarItem, workspace, ViewColumn, commands, TextDocument } from "vscode"; import * as keyTarType from "keytar"; import { MgmtClient } from './utils/f5DeviceClient'; import logger from "./utils/logger"; +import { TextDocumentView } from './editorViews/editorView'; type KeyTar = typeof keyTarType; @@ -27,7 +28,7 @@ export namespace ext { export let connectBar: StatusBarItem; export let iRulesAble: boolean = false; export let as3AsyncPost: boolean | undefined; - export let carTreeData: object | undefined; + export let panel: TextDocumentView; export let tsExampleView: object | undefined; export namespace settings { diff --git a/src/utils/f5DeviceClient.ts b/src/utils/f5DeviceClient.ts index 4c76f1f..29355f5 100644 --- a/src/utils/f5DeviceClient.ts +++ b/src/utils/f5DeviceClient.ts @@ -39,7 +39,7 @@ export class MgmtClient { protected _tokenTimeout: number = 0; private _onConnect: string[] = []; private _onDisconnect: string[] = []; - private terminal: Terminal; + private terminal: Terminal | undefined; /** * @param options function options @@ -60,8 +60,6 @@ export class MgmtClient { this._user = options['user']; this._password = options['password']; this.getConfig(); - this.terminal = window.createTerminal('f5-fast-cmd'); - this.terminal.show(true); } /** @@ -348,27 +346,57 @@ export class MgmtClient { * issues terminal commands defined for "onConnect" */ private termConnect() { - // if _onConnect has a value, loop through each as terminal commands - this._onConnect?.forEach((el: string) => { - // swap out variable as needed - el = el.replace(/\${this.device}/, `${this.device}`); - setTimeout( () => { - // console.log(el); - this.terminal.sendText(el); - }, 500); - }); + + // if we have configuration in the onConnect + if (this._onConnect) { + + // if we don't already have a terminal, create one + if (!this.terminal) { + this.terminal = window.createTerminal('f5-fast-cmd'); + this.terminal.show(true); + } + + // loop through onConnect commands and issue them + this._onConnect?.forEach((el: string) => { + + // swap out variable as needed + el = el.replace(/\${this.device}/, `${this.device}`); + setTimeout( () => { + this.terminal?.sendText(el); + }, 500); + }); + }; + } /** * issue terminal commands defined for "onDisonnect" */ private termDisConnect() { - // if _onDisconnect has a value, loop through each as terminal commands - this._onDisconnect?.forEach((el: string) => { + + // if we have onDisconnect commands + if (this._onDisconnect) { + + // if we don't already have a terminal, create one (very corner cases) + if (!this.terminal) { + this.terminal = window.createTerminal('f5-fast-cmd'); + this.terminal.show(true); + } + + // if _onDisconnect has a value, loop through each as terminal commands + this._onDisconnect?.forEach((el: string) => { + setTimeout( () => { + this.terminal?.sendText(el); + }, 500); + }); + } + + // if we have a terminal, and we are disconnecting, delete terminal when done + if (this.terminal) { setTimeout( () => { - this.terminal.sendText(el); - }, 500); - }); + this.terminal?.dispose(); + }, 1000); + } } } diff --git a/src/utils/f5FastUtils.ts b/src/utils/f5FastUtils.ts index e343374..6ea3f3a 100644 --- a/src/utils/f5FastUtils.ts +++ b/src/utils/f5FastUtils.ts @@ -249,6 +249,9 @@ async function packageTemplateSet2(tsPath: string, dst: string) { logger.debug(error); }); // return fastPackage; + }) + .catch( e => { + logger.error(e); }); return tempVal; } diff --git a/src/utils/fastHtmlPreveiwWebview.ts b/src/utils/fastHtmlPreveiwWebview.ts deleted file mode 100644 index df8abb4..0000000 --- a/src/utils/fastHtmlPreveiwWebview.ts +++ /dev/null @@ -1,293 +0,0 @@ -import * as vscode from 'vscode'; -import { ext } from '../extensionVariables'; -// import * as path from 'path'; -// import * as fs from 'fs'; - -// import hljs = require('highlight.js'); -// hljs.registerLanguage('json', require('highlight.js/lib/languages/json')); - -// import codeHighlightLinenums = require('code-highlight-linenums'); - -// const tHtml = require('./testHttp.html'); - -/** - * Manages cat coding webview panels - * working this catCodeing webView example - * https://code.visualstudio.com/api/extension-guides/webview - */ -export class FastWebViewPanel { - /** - * Track the currently panel. Only allow a single panel to exist at a time. - */ - - public static currentPanel: FastWebViewPanel | undefined; - - public static readonly viewType = 'catCoding'; - - private readonly _panel: vscode.WebviewPanel; - private readonly _extensionPath: string; - private _disposables: vscode.Disposable[] = []; - - public static render(extensionPath: string, data: string) { - const column = vscode.window.activeTextEditor - ? vscode.window.activeTextEditor.viewColumn - : undefined; - - // If we already have a panel, show it. - if (FastWebViewPanel.currentPanel) { - FastWebViewPanel.currentPanel._panel.reveal(column); - FastWebViewPanel.currentPanel.update(data); - return; - } - - // Otherwise, create a new panel. - const panel = vscode.window.createWebviewPanel( - FastWebViewPanel.viewType, - 'Rendered HTML', - column || vscode.ViewColumn.One, - { - enableScripts: true, - enableFindWidget: true, - retainContextWhenHidden: true - } - ); - - FastWebViewPanel.currentPanel = new FastWebViewPanel(panel, extensionPath, data); - } - - public static revive(panel: vscode.WebviewPanel, extensionPath: string, data: string) { - FastWebViewPanel.currentPanel = new FastWebViewPanel(panel, extensionPath, data); - } - - private constructor(panel: vscode.WebviewPanel, extensionPath: string, data: string) { - this._panel = panel; - this._extensionPath = extensionPath; - - // Set the webview's initial html content - this.update(data); - - // Listen for when the panel is disposed - // This happens when the user closes the panel or when the panel is closed programatically - this._panel.onDidDispose(() => this.dispose(), null, this._disposables); - - // Update the content based on view changes - this._panel.onDidChangeViewState( - e => { - if (this._panel.visible) { - this.update(data); - } - }, - null, - this._disposables - ); - - // Handle messages from the webview - this._panel.webview.onDidReceiveMessage( - message => { - switch (message.command) { - case 'alert': - vscode.window.showErrorMessage(message.text); - return; - } - }, - null, - this._disposables - ); - } - - public doRefactor() { - // Send a message to the webview webview. - // You can send any JSON serializable data. - this._panel.webview.postMessage({ command: 'refactor' }); - } - - public dispose() { - FastWebViewPanel.currentPanel = undefined; - - // Clean up our resources - this._panel.dispose(); - - while (this._disposables.length) { - const x = this._disposables.pop(); - if (x) { - x.dispose(); - } - } - } - - public update(data: string) { - const webview = this._panel.webview; - this._panel.title = 'Response'; - // this._panel.webview.html = getWebviewContent(JSON.stringify(data, null, 4)); - this._panel.webview.html = data; - // this._panel.webview.html = this._getHtmlForWebview(webview, JSON.stringify(data, null, 4)); - // return; - - // // Vary the webview's content based on where it is located in the editor. - // switch (this._panel.viewColumn) { - // case vscode.ViewColumn.Two: - // this._updateForCat(webview, 'Compiling Cat'); - // return; - - // case vscode.ViewColumn.Three: - // this._updateForCat(webview, 'Testing Cat'); - // return; - - // case vscode.ViewColumn.One: - // default: - // this._updateForCat(webview, 'Coding Cat'); - // return; - // } - } - - // private _updateForCat(webview: vscode.Webview, catName: keyof typeof cats) { - // this._panel.title = catName; - // this._panel.webview.html = this._getHtmlForWebview(webview, cats[catName]); - // } - - // private _getHtmlForWebview(webview: vscode.Webview, stuff: string) { - // // Local path to main script run in the webview - // const scriptPathOnDisk = vscode.Uri.file( - // path.join(this._extensionPath, 'media', 'main.js') - // ); - - // const styleFilePath = vscode.Uri.file(path.join( - // ext.context.extensionPath, - // 'styles', - // 'webView.css' - // )) - // .with({ scheme: 'vscode-resource' }); - - // // And the uri we use to load this script in the webview - // const scriptUri = webview.asWebviewUri(scriptPathOnDisk); - - // // // Use a nonce to whitelist which scripts can be run - // // const nonce = getNonce(); - - // return ` - // - // - // - // - // - // - // - //
- //

-    //     ${codeHighlightLinenums(stuff, { hljs, lang: 'json', start: 1 })}
-    //     
- //
- // - // `; - // } -} - -// function getNonce() { -// let text = ''; -// const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; -// for (let i = 0; i < 32; i++) { -// text += possible.charAt(Math.floor(Math.random() * possible.length)); -// } -// return text; -// } - - - - - - - - - - - - - - -// export async function displayWebView(info: string) { - -// // Track currently webview panel -// let currentPanel: vscode.WebviewPanel | undefined; - -// const columnToShowIn = vscode.window.activeTextEditor -// ? vscode.window.activeTextEditor.viewColumn -// : undefined; - -// if (currentPanel) { -// // If we already have a panel, show it in the target column -// currentPanel.reveal(columnToShowIn); -// } else { -// // Otherwise, create a new panel -// currentPanel = vscode.window.createWebviewPanel( -// 'atcResponse', -// 'ATC Response', -// vscode.ViewColumn.Two, -// { -// enableScripts: true, -// retainContextWhenHidden: true -// } -// ); -// // currentPanel.webview.html = getWebviewContent(JSON.stringify(info, null, 4)); -// currentPanel.webview.html = info; - -// currentPanel.onDidDispose( -// () => { -// currentPanel = undefined; -// }, -// null, -// ext.context.subscriptions -// ); -// } -// } - -// function getWebviewContent(stuff : string) { -// const highlightedCode = hljs.highlightAuto(stuff).value; -// const styleFilePath = vscode.Uri.file(path.join( -// ext.context.extensionPath, -// 'styles', -// 'webView.css' -// )) -// .with({ scheme: 'vscode-resource' }); - -// return ` -// -// -// -// -// -// -// -//
${highlightedCode}
-// -// `; -// } - -/* -* Other way that include line numbers. -* couldn't find a types file for "code-highlight-linenums" -*/ -// function getWebviewContent(stuff : string) { -// // const highlightedCode = hljs.highlightAuto('json', stuff).value; -// const styleFilePath = vscode.Uri.file(path.join( -// ext.context.extensionPath, -// 'styles', -// 'webView.css' -// )) -// .with({ scheme: 'vscode-resource' }); - -// return ` -// -// -// -// -// -// -// -//
-//
${codeHighlightLinenums(stuff, { hljs, lang: 'json', start: 1 })}
-//
-// -// `; -// } - -