Skip to content

Instantly share code, notes, and snippets.

@mizchi
Created July 12, 2021 10:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mizchi/ed3b5b70742556b2e25cd9ad64a5ee01 to your computer and use it in GitHub Desktop.
Save mizchi/ed3b5b70742556b2e25cd9ad64a5ee01 to your computer and use it in GitHub Desktop.
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