Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import vscode from "vscode";
import path from "path";
export function activate(context: vscode.ExtensionContext) {
context.subscriptions.push(
vscode.Disposable.from(registerOpenCommand(context))
);
}
function openPreview(
jsPath: vscode.Uri,
title: string,
initialUri: string,
initialContent: string
) {
const panel = vscode.window.createWebviewPanel(
"hello",
"hello",
vscode.ViewColumn.Beside,
{
enableScripts: true,
}
);
panel.title = title;
panel.webview.html = _getHtml(jsPath);
let ready = false;
return vscode.Disposable.from(
// receive message from webview
panel.webview.onDidReceiveMessage((message) => {
if (message.type === "ready") {
if (ready) return;
ready = true;
panel.webview.postMessage({
type: "set-code",
value: initialContent,
uri: initialUri,
});
}
}),
// receive text changes
vscode.workspace.onDidChangeTextDocument((event) => {
const value = event.document.getText();
const uri = event.document.uri.toString();
panel.webview.postMessage({
type: "set-code",
value,
uri,
});
})
);
}
function registerOpenCommand(context: vscode.ExtensionContext) {
return vscode.commands.registerCommand("viscode-extension.helloWorld", () => {
vscode.window.showInformationMessage("Hello World from viscode-extension!");
const jsPath = vscode.Uri.file(
path.join(context.extensionPath, "dist/vistree-ext.es.js")
).with({
scheme: "vscode-resource",
});
const activeEditor = vscode.window.activeTextEditor;
if (activeEditor == null) {
vscode.window.showErrorMessage("typescript active window required");
return;
}
const initialText = activeEditor?.document.getText() ?? "plane";
const initialUri = activeEditor?.document.uri.toString();
return openPreview(jsPath, "hello", initialUri, initialText);
});
}
function _getHtml(js: vscode.Uri) {
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
* {
box-sizing: border-box;
}
html,
body,
#root {
margin: 0;
width: 100vw;
height: 100vh;
overflow: hidden;
}
</style>
</head>
<body>
<script type="module" src="${js.toString()}"></script>
<div id="root"></div>
</body>
</html> `;
}
export function deactivate() {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment