vscode#WebviewViewProvider TypeScript Examples
The following examples show how to use
vscode#WebviewViewProvider.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: trivy_helpview.ts From trivy-vscode-extension with Apache License 2.0 | 5 votes |
export class TrivyHelpProvider implements WebviewViewProvider {
private view: Webview | undefined;
resolveWebviewView(webviewView: WebviewView, _context: WebviewViewResolveContext<unknown>, _token: CancellationToken): void | Thenable<void> {
this.view = webviewView.webview;
this.update(null);
}
update(item: TrivyTreeItem | null) {
if (this.view === undefined) {
return;
}
if (item === null) {
return;
}
const codeData = item.check;
if (codeData === undefined) {
this.view.html = `
<h2>No check data available</h2>
`;
return;
}
var html: string = "";
switch (item.itemType) {
case TrivyTreeItemType.misconfigCode:
case TrivyTreeItemType.misconfigInstance:
html = getMisconfigurationHtml(item.check);
break;
case TrivyTreeItemType.vulnerabilityCode:
html = getVulnerabilityHtml(item.check);
break;
case TrivyTreeItemType.secretInstance:
html = getSecretHtml(item.check);
break;
default:
return "";
}
if (codeData.references) {
html += "<ul>";
for (let i = 0; i < codeData.references.length; i++) {
const reference = codeData.references[i];
html += `<li><a href="${reference}">${reference}</a></li>
`;
}
html += "</ul>";
}
this.view.html = html;
return;
}
}
Example #2
Source File: webview.ts From cloudmusic-vscode with MIT License | 4 votes |
export class AccountViewProvider implements WebviewViewProvider {
static context: ExtensionContext;
private static _view?: WebviewView;
static master(): void {
if (this._view) {
const msg: ProviderSMsg = { command: "master", is: State.master };
void this._view.webview.postMessage(msg);
}
}
static play(): void {
if (this._view) {
const msg: ProviderSMsg = { command: "state", state: "playing" };
void this._view.webview.postMessage(msg);
}
}
static pause(): void {
if (this._view) {
const msg: ProviderSMsg = { command: "state", state: "paused" };
void this._view.webview.postMessage(msg);
}
}
static stop(): void {
if (this._view) {
const msg: ProviderSMsg = { command: "state", state: "none" };
void this._view.webview.postMessage(msg);
}
}
static wasmLoad(path: string): void {
if (this._view) {
const url = this._view.webview.asWebviewUri(Uri.file(path)).toString();
const msg: ProviderSMsg = { command: "load", url };
void this._view.webview.postMessage(msg);
}
}
static wasmPause(): void {
if (this._view) {
const msg: ProviderSMsg = { command: "pause" };
void this._view.webview.postMessage(msg);
}
}
static wasmPlay(): void {
if (this._view) {
const msg: ProviderSMsg = { command: "play" };
void this._view.webview.postMessage(msg);
}
}
static wasmStop(): void {
if (this._view) {
const msg: ProviderSMsg = { command: "stop" };
void this._view.webview.postMessage(msg);
}
}
static wasmSpeed(speed: number): void {
if (this._view) {
const msg: ProviderSMsg = { command: "speed", speed };
void this._view.webview.postMessage(msg);
}
}
static wasmVolume(level: number): void {
if (this._view) {
const msg: ProviderSMsg = { command: "volume", level };
void this._view.webview.postMessage(msg);
}
}
static account(profiles: NeteaseTypings.Profile[]): void {
if (this._view) {
const msg: ProviderSMsg = { command: "account", profiles };
void this._view.webview.postMessage(msg);
}
}
static metadata(): void {
if (this._view) {
const item = State.playItem;
const msg: ProviderSMsg = item
? {
command: "metadata",
duration: item.item.dt / 1000,
title: item.label,
artist: item.description,
album: item.tooltip,
artwork: [{ src: item.item.al.picUrl }],
}
: { command: "metadata" };
void this._view.webview.postMessage(msg);
}
}
resolveWebviewView(
webview: WebviewView
// context: WebviewViewResolveContext
// token: CancellationToken
): void {
const extUri = AccountViewProvider.context.extensionUri;
AccountViewProvider._view = webview;
webview.title = i18n.word.account;
webview.webview.options = {
enableScripts: true,
localResourceRoots: [extUri, Uri.file(SETTING_DIR)],
};
webview.webview.onDidReceiveMessage((msg: ProviderCMsg) => {
switch (msg.command) {
case "pageLoaded":
AccountViewProvider.master();
AccountViewProvider.account([...AccountManager.accounts.values()]);
AccountViewProvider.metadata();
AccountViewProvider.wasmVolume(
AccountViewProvider.context.globalState.get(VOLUME_KEY, 85)
);
AccountViewProvider.wasmSpeed(
AccountViewProvider.context.globalState.get(SPEED_KEY, 1)
);
if (State.wasm) {
const audioUri = Uri.joinPath(extUri, "media", "audio");
workspace.fs.readDirectory(audioUri).then((items) => {
const files = items
.filter(([name]) => name.startsWith("silent"))
.map(([name]) =>
webview.webview
.asWebviewUri(Uri.joinPath(audioUri, name))
.toString()
);
const msg: ProviderSMsg = { command: "test", files };
void webview.webview.postMessage(msg);
}, console.error);
State.downInit(); // 3
}
break;
case "account":
AccountManager.accountQuickPick(msg.userId);
break;
case "end":
if (State.repeat) IPC.load();
else void commands.executeCommand("cloudmusic.next");
break;
case "load":
IPC.loaded();
break;
case "position":
IPC.position(msg.pos);
break;
case "playing":
IPC.playing(msg.playing);
break;
default:
void commands.executeCommand(`cloudmusic.${msg.command}`);
break;
}
});
const js = webview.webview
.asWebviewUri(Uri.joinPath(extUri, "dist", "provider.js"))
.toString();
const css = webview.webview
.asWebviewUri(Uri.joinPath(extUri, "dist", "style.css"))
.toString();
webview.webview.html = `
<!DOCTYPE html>
<html
lang="en"
${window.activeColorTheme.kind === ColorThemeKind.Light ? "" : 'class="dark"'}
>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>${i18n.word.account}</title>
<link rel="stylesheet" type="text/css" href=${css} />
</head>
<body>
<div id="root"></div>
</body>
<script>window.enablePlayer=${State.wasm ? "true" : "false"}</script>
<script type="module" src=${js} nonce=${getNonce()}></script>
</html>`;
}
}
Example #3
Source File: webviewView.ts From vscode-todo-md with MIT License | 4 votes |
export class TasksWebviewViewProvider implements WebviewViewProvider {
public static readonly viewType = 'todomd.webviewTasks';
private _view?: WebviewView;
constructor(
private readonly _extensionUri: Uri,
) { }
public resolveWebviewView(
webviewView: WebviewView,
context: WebviewViewResolveContext,
_token: CancellationToken,
) {
this._view = webviewView;
const localResourceRoots = [
this._extensionUri,
];
if ($config.webview.customCSSPath) {
localResourceRoots.push(Uri.file(path.dirname($config.webview.customCSSPath)));
}
webviewView.webview.options = {
enableScripts: true,
enableCommandUris: true,
localResourceRoots,
};
webviewView.webview.html = this._getHtmlForWebview(webviewView.webview);
webviewView.webview.onDidReceiveMessage(async (message: MessageFromWebview) => {
switch (message.type) {
// ──── Needs to update everything ────────────────────────────
case 'webviewLoaded': {
this.sendEverything();
break;
}
case 'toggleDone': {
await toggleDoneAtLine(await getActiveOrDefaultDocument(), message.value);
await updateEverything();
break;
}
case 'toggleTaskCollapse': {
await toggleTaskCollapse(await getActiveOrDefaultDocument(), message.value);
await updateEverything();
break;
}
case 'editTask': {
await editTask(await getActiveOrDefaultDocument(), message.value);
await updateEverything();
break;
}
case 'startTask': {
await startTaskAtLine(message.value, await getActiveOrDefaultDocument());
await updateEverything();
break;
}
case 'toggleTaskCollapseRecursive': {
await toggleTaskCollapseRecursive(await getActiveOrDefaultDocument(), message.value);
await updateEverything();
break;
}
case 'incrementCount': {
await incrementCountForTask(await getActiveOrDefaultDocument(), message.value, getTaskAtLineExtension(message.value)!);
await updateEverything();
break;
}
case 'decrementCount': {
await decrementCountForTask(await getActiveOrDefaultDocument(), message.value, getTaskAtLineExtension(message.value)!);
await updateEverything();
break;
}
case 'deleteTask': {
await tryToDeleteTask(await getActiveOrDefaultDocument(), message.value);
await updateEverything();
break;
}
case 'editTaskRawText': {
await editTaskRawText(await getActiveOrDefaultDocument(), message.value.lineNumber, message.value.newRawText);
await updateEverything();
break;
}
// ──── No need to update everything ──────────────────────────
case 'showNotification': {
window.showInformationMessage(message.value);
break;
}
case 'goToTask': {
revealTask(message.value);
break;
}
case 'updateWebviewTitle': {
this.updateTitle(message.value);
break;
}
case 'followLink': {
followLink(message.value);
break;
}
case 'setDueDate': {
openSetDueDateInputbox(await getActiveOrDefaultDocument(), [message.value]);
break;
}
}
});
/**
* Update webview on it's visibility change (only when it becomes visible).
*/
webviewView.onDidChangeVisibility(e => {
if (webviewView.visible === true) {
this.sendEverything();
}
});
}
/**
* Send all the needed data to the webview view
*/
sendEverything() {
if (this._view && this._view.visible === true) {
this.sendMessageToWebview({
type: 'updateEverything',
value: {
tasksAsTree: $state.tasksAsTree,
tags: $state.tags,
projects: $state.projects,
contexts: $state.contexts,
defaultFileSpecified: Boolean($config.defaultFile),
activeDocumentOpened: Boolean($state.activeDocument),
config: $config.webview,
},
});
this.updateTitle($state.tasksAsTree.length);
}
}
/**
* Update webview title (counter).
*/
updateTitle(numberOfTasks: number) {
if (this._view) {
this._view.title = `webview (${numberOfTasks})`;
}
}
/**
* Focus main input in webview.
*/
focusFilterInput() {
this.sendMessageToWebview({
type: 'focusFilterInput',
});
}
/**
* Send message. js objects that will be serialized to json.
*/
private sendMessageToWebview(message: MessageToWebview) {
this._view?.webview.postMessage(message);
}
/**
* Generate html template for webview.
*/
private _getHtmlForWebview(webview: Webview) {
const JSUri = webview.asWebviewUri(Uri.joinPath(this._extensionUri, 'media', 'webview.js'));
const CSSUri = webview.asWebviewUri(Uri.joinPath(this._extensionUri, 'media', 'webview.css'));
const codiconCSSUri = webview.asWebviewUri(Uri.joinPath(this._extensionUri, 'media', 'vendor', 'codicon.css'));
const nonce = getNonce();// Use a nonce to only allow a specific script to be run.
const userCSSLink = $config.webview.customCSSPath ? `<link href="${webview.asWebviewUri(Uri.file($config.webview.customCSSPath))}" rel="stylesheet">` : '';
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; font-src ${webview.cspSource}; style-src 'unsafe-inline' ${webview.cspSource}; script-src 'nonce-${nonce}';">
<link href="${codiconCSSUri}" rel="stylesheet" />
<link href="${CSSUri}" rel="stylesheet">
${userCSSLink}
<title>Tasks</title>
</head>
<body>
<div id="app"></div>
<script defer nonce="${nonce}" src="${JSUri}"></script>
</body>
</html>`;
}
}