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 proposed webview view API #104601

Merged
merged 12 commits into from
Aug 20, 2020
13 changes: 12 additions & 1 deletion extensions/image-preview/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@
"activationEvents": [
"onCustomEditor:imagePreview.previewEditor",
"onCommand:imagePreview.zoomIn",
"onCommand:imagePreview.zoomOut"
"onCommand:imagePreview.zoomOut",
"onView:cats.cat"
],
"contributes": {
"customEditors": [
Expand All @@ -39,6 +40,16 @@
]
}
],
"views": {
"explorer": [
{
"type": "webview",
"id": "cats.cat",
"name": "Cat",
"visibility": "visible"
}
]
},
"commands": [
{
"command": "imagePreview.zoomIn",
Expand Down
21 changes: 20 additions & 1 deletion extensions/image-preview/src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
*--------------------------------------------------------------------------------------------*/

import * as vscode from 'vscode';
import { BinarySizeStatusBarEntry } from './binarySizeStatusBarEntry';
import { PreviewManager } from './preview';
import { SizeStatusBarEntry } from './sizeStatusBarEntry';
import { BinarySizeStatusBarEntry } from './binarySizeStatusBarEntry';
import { ZoomStatusBarEntry } from './zoomStatusBarEntry';

export function activate(context: vscode.ExtensionContext) {
Expand All @@ -32,4 +32,23 @@ export function activate(context: vscode.ExtensionContext) {
context.subscriptions.push(vscode.commands.registerCommand('imagePreview.zoomOut', () => {
previewManager.activePreview?.zoomOut();
}));

vscode.window.registerWebviewViewProvider('cats.cat', new class implements vscode.WebviewViewProvider {
async resolveWebviewView(webviewView: vscode.WebviewView, _state: unknown) {
await new Promise(resolve => setTimeout(resolve, 2000));

webviewView.webview.html = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body style="background-color: transparent">
<img src="https://media.giphy.com/media/E6jscXfv3AkWQ/giphy.gif">
</body>
</html>`;

}
Copy link
Member

Choose a reason for hiding this comment

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

I assume this won't be merged ;-)

});
}
112 changes: 112 additions & 0 deletions src/vs/vscode.proposed.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2048,4 +2048,116 @@ declare module 'vscode' {
notebook: NotebookDocument | undefined;
}
//#endregion


//#region https://github.com/microsoft/vscode/issues/46585

/**
* A webview based view.
*/
export interface WebviewView {
/**
* Identifies the type of the webview view, such as `'hexEditor.dataView'`.
*/
readonly viewType: string;

/**
* The underlying webview for the view.
*/
readonly webview: Webview;

/**
* Event fired when the view is disposed.
*
* Views are disposed of in a few cases:
*
* - When a view is collapsed and `retainContextWhenHidden` has not been set.
* - When a view is hidden by a user.
*
* Trying to use the view after it has been disposed throws an exception.
*/
readonly onDidDispose: Event<void>;

/**
* Tracks if the webview is currently visible.
*
* Views are visible when they are on the screen and expanded.
*/
readonly visible: boolean;

/**
* Event fired when the visibility of the view changes
*/
readonly onDidChangeVisibility: Event<void>;
}

interface WebviewViewResolveContext<T = unknown> {
/**
* Persisted state from the webview content.
*
* To save resources, VS Code normally deallocates webview views that are not visible. For example, if the user
* collapse a view or switching to another top level activity, the underlying webview document is deallocates.
*
* You can prevent this behavior by setting `retainContextWhenHidden` in the `WebviewOptions`. However this
* increases resource usage and should be avoided wherever possible. Instead, you can use persisted state to
* save off a webview's state so that it can be quickly recreated as needed.
*
* To save off a persisted state, inside the webview call `acquireVsCodeApi().setState()` with
* any json serializable object. To restore the state again, call `getState()`. For example:
*
* ```js
* // Within the webview
* const vscode = acquireVsCodeApi();
*
* // Get existing state
* const oldState = vscode.getState() || { value: 0 };
*
* // Update state
* setState({ value: oldState.value + 1 })
* ```
*
* VS Code ensures that the persisted state is saved correctly when a webview is hidden and across
* editor restarts.
*/
readonly state: T | undefined;
}

/**
* Provider for creating `WebviewView` elements.
*/
export interface WebviewViewProvider {
/**
* Revolves a webview view.
*
* `resolveWebviewView` is called when a view first becomes visible. This may happen when the view is
* first loaded or when the user hides and then shows a view again.
*
* @param webviewView Webview panel to restore. The serializer should take ownership of this panel. The
* provider must set the webview's `.html` and hook up all webview events it is interested in.
* @param context Additional metadata about the view being resolved.
* @param token Cancellation token indicating that the view being provided is no longer needed.
*
* @return Optional promise indicating that the view has been fully resolved.
*/
resolveWebviewView(webviewView: WebviewView, context: WebviewViewResolveContext, token: CancellationToken): Promise<void> | void;
Copy link
Member

Choose a reason for hiding this comment

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

Return Thenable instead

}

namespace window {
/**
* Register a new provider for webview views.
*
* @param viewId Unique id of the view. This should match the `id` from the
* `views` contribution in the package.json.
* @param provider Provider for the webview views.
*
* @return Disposable that unregisters the provider.
*/
export function registerWebviewViewProvider(viewId: string, provider: WebviewViewProvider, options?: {
/**
* Content settings for the webview created for this view.
*/
readonly webviewOptions?: WebviewPanelOptions;
}): Disposable;
}
//#endregion
}
68 changes: 57 additions & 11 deletions src/vs/workbench/api/browser/mainThreadWebview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { IInstantiationService } from 'vs/platform/instantiation/common/instanti
import { ILabelService } from 'vs/platform/label/common/label';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { IProductService } from 'vs/platform/product/common/productService';
import { Registry } from 'vs/platform/registry/common/platform';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IUndoRedoService, UndoRedoElementType } from 'vs/platform/undoRedo/common/undoRedo';
import * as extHostProtocol from 'vs/workbench/api/common/extHost.protocol';
Expand All @@ -33,8 +34,9 @@ import { CustomEditorInput } from 'vs/workbench/contrib/customEditor/browser/cus
import { CustomDocumentBackupData } from 'vs/workbench/contrib/customEditor/browser/customEditorInputFactory';
import { ICustomEditorModel, ICustomEditorService } from 'vs/workbench/contrib/customEditor/common/customEditor';
import { CustomTextEditorModel } from 'vs/workbench/contrib/customEditor/common/customTextEditorModel';
import { WebviewExtensionDescription, WebviewIcons } from 'vs/workbench/contrib/webview/browser/webview';
import { Webview, WebviewExtensionDescription, WebviewIcons, WebviewOverlay } from 'vs/workbench/contrib/webview/browser/webview';
import { WebviewInput } from 'vs/workbench/contrib/webview/browser/webviewEditorInput';
import { Extensions, IViewWebviewViewResolverRegistry } from 'vs/workbench/contrib/webview/browser/webviewView';
import { ICreateWebViewShowOptions, IWebviewWorkbenchService, WebviewInputOptions } from 'vs/workbench/contrib/webview/browser/webviewWorkbenchService';
import { IBackupFileService } from 'vs/workbench/services/backup/common/backup';
import { IEditorGroup, IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
Expand Down Expand Up @@ -119,6 +121,10 @@ export class MainThreadWebviews extends Disposable implements extHostProtocol.Ma
private readonly _proxy: extHostProtocol.ExtHostWebviewsShape;
private readonly _webviewInputs = new WebviewInputStore();
private readonly _revivers = new Map<string, IDisposable>();

private readonly _webviewViewProviders = new Map<string, IDisposable>();
private readonly _webviewViews = new Map<string, WebviewOverlay>();

private readonly _editorProviders = new Map<string, IDisposable>();
private readonly _webviewFromDiffEditorHandles = new Set<string>();

Expand Down Expand Up @@ -212,7 +218,7 @@ export class MainThreadWebviews extends Disposable implements extHostProtocol.Ma

const extension = reviveWebviewExtension(extensionData);
const webview = this._webviewWorkbenchService.createWebview(handle, webviewPanelViewType.fromExternal(viewType), title, mainThreadShowOptions, reviveWebviewOptions(options), extension);
this.hookupWebviewEventDelegate(handle, webview);
this.hookupWebviewEventDelegate(handle, webview.webview);

this._webviewInputs.add(handle, webview);

Expand Down Expand Up @@ -240,8 +246,8 @@ export class MainThreadWebviews extends Disposable implements extHostProtocol.Ma
}

public $setHtml(handle: extHostProtocol.WebviewPanelHandle, value: string): void {
const webview = this.getWebviewInput(handle);
webview.webview.html = value;
const webview = this.getWebview(handle);
webview.html = value;
}

public $setOptions(handle: extHostProtocol.WebviewPanelHandle, options: modes.IWebviewOptions): void {
Expand Down Expand Up @@ -285,7 +291,7 @@ export class MainThreadWebviews extends Disposable implements extHostProtocol.Ma

const handle = webviewInput.id;
this._webviewInputs.add(handle, webviewInput);
this.hookupWebviewEventDelegate(handle, webviewInput);
this.hookupWebviewEventDelegate(handle, webviewInput.webview);

let state = undefined;
if (webviewInput.webview.state) {
Expand Down Expand Up @@ -316,6 +322,38 @@ export class MainThreadWebviews extends Disposable implements extHostProtocol.Ma
this._revivers.delete(viewType);
}

public $registerWebviewViewProvider(viewType: string): void {
if (this._webviewViewProviders.has(viewType)) {
throw new Error(`View provider for ${viewType} already registered`);
}

Registry.as<IViewWebviewViewResolverRegistry>(Extensions.WebviewViewResolverRegistry)
.register(viewType, {
resolve: async (webview: WebviewOverlay) => {
this._webviewViews.set(viewType, webview);

const handle = viewType;
this.hookupWebviewEventDelegate(handle, webview);

let state = undefined;
if (webview.state) {
try {
state = JSON.parse(webview.state);
} catch (e) {
console.error('Could not load webview state', e, webview.state);
}
}

try {
await this._proxy.$resolveWebviewView(handle, viewType, state);
} catch (error) {
onUnexpectedError(error);
webview.html = MainThreadWebviews.getWebviewResolvedFailedContent(viewType);
}
}
});
}

public $registerTextEditorProvider(extensionData: extHostProtocol.WebviewExtensionDescription, viewType: string, options: modes.IWebviewPanelOptions, capabilities: extHostProtocol.CustomTextEditorCapabilities): void {
this.registerEditorProvider(ModelType.Text, extensionData, viewType, options, capabilities, true);
}
Expand Down Expand Up @@ -353,7 +391,7 @@ export class MainThreadWebviews extends Disposable implements extHostProtocol.Ma
const resource = webviewInput.resource;

this._webviewInputs.add(handle, webviewInput);
this.hookupWebviewEventDelegate(handle, webviewInput);
this.hookupWebviewEventDelegate(handle, webviewInput.webview);
webviewInput.webview.options = options;
webviewInput.webview.extension = extension;

Expand Down Expand Up @@ -460,14 +498,14 @@ export class MainThreadWebviews extends Disposable implements extHostProtocol.Ma
model.changeContent();
}

private hookupWebviewEventDelegate(handle: extHostProtocol.WebviewPanelHandle, input: WebviewInput) {
private hookupWebviewEventDelegate(handle: extHostProtocol.WebviewPanelHandle, webview: WebviewOverlay) {
const disposables = new DisposableStore();

disposables.add(input.webview.onDidClickLink((uri) => this.onDidClickLink(handle, uri)));
disposables.add(input.webview.onMessage((message: any) => { this._proxy.$onMessage(handle, message); }));
disposables.add(input.webview.onMissingCsp((extension: ExtensionIdentifier) => this._proxy.$onMissingCsp(handle, extension.value)));
disposables.add(webview.onDidClickLink((uri) => this.onDidClickLink(handle, uri)));
disposables.add(webview.onMessage((message: any) => { this._proxy.$onMessage(handle, message); }));
disposables.add(webview.onMissingCsp((extension: ExtensionIdentifier) => this._proxy.$onMissingCsp(handle, extension.value)));

disposables.add(input.webview.onDispose(() => {
disposables.add(webview.onDispose(() => {
disposables.dispose();

this._proxy.$onDidDisposeWebviewPanel(handle).finally(() => {
Expand Down Expand Up @@ -554,6 +592,14 @@ export class MainThreadWebviews extends Disposable implements extHostProtocol.Ma
return !!webview.webview.contentOptions.enableCommandUris && link.scheme === Schemas.command;
}

private getWebview(handle: extHostProtocol.WebviewPanelHandle): Webview {
const webview = this.tryGetWebviewInput(handle)?.webview ?? this._webviewViews.get(handle);
if (!webview) {
throw new Error(`Unknown webview handle:${handle}`);
}
return webview;
}

private getWebviewInput(handle: extHostProtocol.WebviewPanelHandle): WebviewInput {
const webview = this.tryGetWebviewInput(handle);
if (!webview) {
Expand Down
Loading