Code improvements.
This commit is contained in:
139
extension/src/webview/InternalWebviewManager.ts
Normal file
139
extension/src/webview/InternalWebviewManager.ts
Normal file
@@ -0,0 +1,139 @@
|
||||
import { window, ViewColumn, WebviewPanel } from "vscode";
|
||||
import { WebviewServer } from "./WebviewServer";
|
||||
import { Disposable } from "@hediet/std/disposable";
|
||||
import { WindowWithWebviewData } from "../webviewContract";
|
||||
import { Config } from "../Config";
|
||||
|
||||
export const debugVisualizer = "debugVisualizer";
|
||||
|
||||
export class InternalWebviewManager {
|
||||
private readonly openedWebviews = new Map<
|
||||
WebviewPanel,
|
||||
DebugVisualizerWebview
|
||||
>();
|
||||
|
||||
public readonly dispose = Disposable.fn();
|
||||
|
||||
constructor(
|
||||
private readonly server: WebviewServer,
|
||||
private readonly config: Config
|
||||
) {
|
||||
this.dispose.track(
|
||||
window.registerWebviewPanelSerializer(debugVisualizer, {
|
||||
deserializeWebviewPanel: async (panel, state) => {
|
||||
this.restore(panel);
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
this.dispose.track({
|
||||
dispose: () => {
|
||||
for (const panel of this.openedWebviews.keys()) {
|
||||
panel.dispose();
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
public createNew(expression: string | undefined = undefined) {
|
||||
const webviewPanel = window.createWebviewPanel(
|
||||
debugVisualizer,
|
||||
"Debug Visualizer",
|
||||
ViewColumn.Two,
|
||||
{
|
||||
enableScripts: true,
|
||||
retainContextWhenHidden: true,
|
||||
portMapping: [
|
||||
{
|
||||
webviewPort: this.server.port,
|
||||
extensionHostPort: this.server.port,
|
||||
},
|
||||
],
|
||||
}
|
||||
);
|
||||
|
||||
this.initializeView(webviewPanel, expression);
|
||||
}
|
||||
|
||||
private restore(webviewPanel: WebviewPanel) {
|
||||
this.initializeView(webviewPanel);
|
||||
}
|
||||
|
||||
private initializeView(
|
||||
webviewPanel: WebviewPanel,
|
||||
expression: string | undefined = undefined
|
||||
) {
|
||||
webviewPanel.webview.html = getDebugVisualizerWebviewHtml(
|
||||
this.server,
|
||||
expression,
|
||||
this.config
|
||||
);
|
||||
const view = new DebugVisualizerWebview(webviewPanel);
|
||||
this.openedWebviews.set(webviewPanel, view);
|
||||
webviewPanel.onDidDispose(() => {
|
||||
this.openedWebviews.delete(webviewPanel);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export class DebugVisualizerWebview {
|
||||
constructor(private readonly webviewPanel: WebviewPanel) {}
|
||||
}
|
||||
|
||||
function getDebugVisualizerWebviewHtml(
|
||||
server: WebviewServer,
|
||||
initialExpression: string | undefined = undefined,
|
||||
config: Config
|
||||
) {
|
||||
const isDev = !!process.env.USE_DEV_UI;
|
||||
return `
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline' 'unsafe-eval'; script-src * 'unsafe-inline' 'unsafe-eval'; connect-src * 'unsafe-inline'; img-src * data: blob: 'unsafe-inline'; frame-src *; style-src * 'unsafe-inline'; worker-src * data: 'unsafe-inline' 'unsafe-eval'; font-src * 'unsafe-inline' 'unsafe-eval';">
|
||||
<style>
|
||||
html { height: 100%; width: 100%; padding: 0; margin: 0; }
|
||||
body { height: 100%; width: 100%; padding: 0; margin: 0; }
|
||||
iframe { height: 100%; width: 100%; padding: 0; margin: 0; border: 0; display: block; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<script>
|
||||
Object.assign(window, ${JSON.stringify({
|
||||
webviewData: {
|
||||
serverSecret: server.secret,
|
||||
serverPort: server.port,
|
||||
publicPath: server.publicPath,
|
||||
expression: initialExpression,
|
||||
theme: config.theme,
|
||||
},
|
||||
} as WindowWithWebviewData)});
|
||||
const api = window.VsCodeApi = acquireVsCodeApi();
|
||||
window.addEventListener('message', event => {
|
||||
if (event.source === window.frames[0]) {
|
||||
if (event.data.command === "setState") {
|
||||
console.log("setState", event.data.state);
|
||||
api.setState(event.data.state);
|
||||
}
|
||||
if (event.data.command === "getState") {
|
||||
console.log("getState, sent ", api.getState());
|
||||
window.frames[0].postMessage({ command: "getStateResult", state: api.getState() }, "*");
|
||||
}
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
${
|
||||
isDev
|
||||
? `<iframe sandbox="allow-top-navigation allow-scripts allow-same-origin allow-popups allow-pointer-lock allow-forms" src="${server.getWebviewPageUrl(
|
||||
{
|
||||
mode: "webviewIFrame",
|
||||
expression: initialExpression,
|
||||
}
|
||||
)}"></iframe>`
|
||||
: `<script type="text/javascript" src="${server.webviewBundleUrl}"></script>`
|
||||
}
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
}
|
||||
158
extension/src/webview/WebviewConnection.ts
Normal file
158
extension/src/webview/WebviewConnection.ts
Normal file
@@ -0,0 +1,158 @@
|
||||
import { Disposable } from "@hediet/std/disposable";
|
||||
import { webviewContract } from "../webviewContract";
|
||||
import { ConsoleRpcLogger, RequestHandlingError } from "@hediet/typed-json-rpc";
|
||||
import {
|
||||
EvaluationWatcher,
|
||||
EvaluationWatchService,
|
||||
} from "../EvaluationWatchService";
|
||||
import { WebSocketStream } from "@hediet/typed-json-rpc-websocket";
|
||||
import { observable, autorun } from "mobx";
|
||||
import { WebviewServer } from "./WebviewServer";
|
||||
import * as open from "open";
|
||||
import chromeLauncher = require("chrome-launcher");
|
||||
import { Config } from "../Config";
|
||||
|
||||
export class WebviewConnection {
|
||||
public readonly dispose = Disposable.fn();
|
||||
@observable
|
||||
private watcher: EvaluationWatcher | undefined = undefined;
|
||||
|
||||
private readonly client: typeof webviewContract["TClientInterface"];
|
||||
|
||||
constructor(
|
||||
evaluationWatchService: EvaluationWatchService,
|
||||
stream: WebSocketStream,
|
||||
server: WebviewServer,
|
||||
config: Config,
|
||||
serverSecret: string
|
||||
) {
|
||||
let authenticated = false;
|
||||
|
||||
function throwIfNotAuthenticated() {
|
||||
if (!authenticated) {
|
||||
throw new RequestHandlingError("Not authenticated");
|
||||
}
|
||||
}
|
||||
|
||||
const { client, channel } = webviewContract.registerServerToStream(
|
||||
stream,
|
||||
new ConsoleRpcLogger(),
|
||||
{
|
||||
authenticate: async ({ secret }, { newErr }) => {
|
||||
if (secret !== serverSecret) {
|
||||
return newErr({ errorMessage: "Invalid Secret" });
|
||||
} else {
|
||||
authenticated = true;
|
||||
}
|
||||
},
|
||||
refresh: async () => {
|
||||
throwIfNotAuthenticated();
|
||||
|
||||
if (this.watcher) {
|
||||
this.watcher.refresh();
|
||||
}
|
||||
},
|
||||
setExpression: async ({ newExpression }) => {
|
||||
throwIfNotAuthenticated();
|
||||
|
||||
let oldPreferredDataExtractor: EvaluationWatcher["preferredDataExtractor"];
|
||||
if (this.watcher) {
|
||||
oldPreferredDataExtractor = this.watcher
|
||||
.preferredDataExtractor;
|
||||
this.dispose.untrack(this.watcher).dispose();
|
||||
}
|
||||
this.watcher = this.dispose.track(
|
||||
evaluationWatchService.createEvaluationWatcher(
|
||||
newExpression,
|
||||
{
|
||||
preferredDataExtractor: oldPreferredDataExtractor,
|
||||
}
|
||||
)
|
||||
);
|
||||
},
|
||||
openInBrowser: async ({}) => {
|
||||
throwIfNotAuthenticated();
|
||||
|
||||
const url = server.getWebviewPageUrl({
|
||||
mode: "standalone",
|
||||
expression: this.watcher
|
||||
? this.watcher.expression
|
||||
: undefined,
|
||||
});
|
||||
|
||||
let opened = false;
|
||||
if (config.useChromeKioskMode) {
|
||||
opened = await launchChrome(url);
|
||||
}
|
||||
if (!opened) {
|
||||
open(url);
|
||||
}
|
||||
},
|
||||
setPreferredDataExtractor: async ({ dataExtractorId }) => {
|
||||
throwIfNotAuthenticated();
|
||||
|
||||
if (this.watcher) {
|
||||
this.watcher.setPreferredDataExtractor(dataExtractorId);
|
||||
}
|
||||
},
|
||||
getCompletions: async ({ text, column }) => {
|
||||
throwIfNotAuthenticated();
|
||||
|
||||
const completions = await evaluationWatchService.getCompletions(
|
||||
text,
|
||||
column
|
||||
);
|
||||
return {
|
||||
completions,
|
||||
};
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
this.client = client;
|
||||
|
||||
this.dispose.track([
|
||||
Disposable.create(
|
||||
autorun(() => {
|
||||
if (this.watcher) {
|
||||
client.updateState({
|
||||
newState: this.watcher.state,
|
||||
});
|
||||
}
|
||||
})
|
||||
),
|
||||
Disposable.create(
|
||||
autorun(() => {
|
||||
client.updateLanguageId({
|
||||
languageId: evaluationWatchService.languageId || null,
|
||||
});
|
||||
})
|
||||
),
|
||||
]);
|
||||
|
||||
stream.onClosed.then(() => {
|
||||
this.dispose();
|
||||
});
|
||||
}
|
||||
|
||||
public setExpression(expression: string) {
|
||||
this.client.setExpression({ expression });
|
||||
}
|
||||
|
||||
public setTheme(theme: "light" | "dark"): void {
|
||||
this.client.setTheme({ theme });
|
||||
}
|
||||
}
|
||||
|
||||
async function launchChrome(url: string): Promise<boolean> {
|
||||
try {
|
||||
const _chrome = await chromeLauncher.launch({
|
||||
startingUrl: url,
|
||||
// `--window-size=${width},${height}`
|
||||
chromeFlags: ["--app=" + url],
|
||||
});
|
||||
return true;
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
94
extension/src/webview/WebviewServer.ts
Normal file
94
extension/src/webview/WebviewServer.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
import { WebSocketStream } from "@hediet/typed-json-rpc-websocket";
|
||||
import { AddressInfo } from "net";
|
||||
import WebSocket = require("ws");
|
||||
import { WebviewConnection } from "./WebviewConnection";
|
||||
import * as express from "express";
|
||||
import * as http from "http";
|
||||
import * as serveStatic from "serve-static";
|
||||
import { Config } from "../Config";
|
||||
import cryptoRandomString = require("crypto-random-string");
|
||||
import { distPath } from "debug-visualizer-webview";
|
||||
import { EvaluationWatchService } from "../EvaluationWatchService/EvaluationWatchService";
|
||||
import { URLSearchParams } from "url";
|
||||
import { autorun, reaction } from "mobx";
|
||||
|
||||
export class WebviewServer {
|
||||
private readonly server: http.Server;
|
||||
public readonly secret = cryptoRandomString({ length: 30 });
|
||||
|
||||
public readonly connections = new Set<WebviewConnection>();
|
||||
|
||||
constructor(
|
||||
dataSource: EvaluationWatchService,
|
||||
private readonly config: Config
|
||||
) {
|
||||
const app = express();
|
||||
|
||||
app.use(serveStatic(distPath));
|
||||
|
||||
this.server = app.listen();
|
||||
|
||||
console.log(
|
||||
`Serving "${distPath}" on port ${
|
||||
(this.server.address() as AddressInfo).port
|
||||
}`
|
||||
);
|
||||
|
||||
const wss = new WebSocket.Server({ server: this.server });
|
||||
wss.on("connection", async ws => {
|
||||
const stream = new WebSocketStream(ws);
|
||||
const c = new WebviewConnection(
|
||||
dataSource,
|
||||
stream,
|
||||
this,
|
||||
config,
|
||||
this.secret
|
||||
);
|
||||
this.connections.add(c);
|
||||
await stream.onClosed;
|
||||
this.connections.delete(c);
|
||||
});
|
||||
|
||||
reaction(
|
||||
() => config.theme,
|
||||
theme => {
|
||||
for (const c of this.connections) {
|
||||
c.setTheme(theme);
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
public getWebviewPageUrl(args: {
|
||||
expression?: string;
|
||||
mode: "standalone" | "webviewIFrame";
|
||||
}): string {
|
||||
const port = process.env.USE_DEV_UI ? 8081 : this.port;
|
||||
const params: Record<string, string> = {
|
||||
serverPort: this.port.toString(),
|
||||
serverSecret: this.secret,
|
||||
mode: args.mode,
|
||||
theme: this.config.theme,
|
||||
};
|
||||
if (args.expression !== undefined) {
|
||||
params.expression = args.expression;
|
||||
}
|
||||
|
||||
return `http://localhost:${port}/index.html?${new URLSearchParams(
|
||||
params
|
||||
).toString()}`;
|
||||
}
|
||||
|
||||
public get publicPath(): string {
|
||||
return `http://localhost:${this.port}/`;
|
||||
}
|
||||
|
||||
public get webviewBundleUrl(): string {
|
||||
return `${this.publicPath}main.js`;
|
||||
}
|
||||
|
||||
public get port(): number {
|
||||
const httpPort = (this.server.address() as AddressInfo).port;
|
||||
return httpPort;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user