any-rule/src/diagram/index.ts

46 lines
2.0 KiB
TypeScript
Raw Normal View History

import { Webview, window, ViewColumn, Uri, ExtensionContext } from 'vscode';
import * as path from 'path';
import * as fs from 'fs';
/**
* webview需要的一种特殊路径格式
* from: https://www.cnblogs.com/liuxianan/p/vscode-plugin-webview.html
* vscode-resource:/Users/toonces/projects/vscode-cat-coding/media/cat.gif
* @param context
* @param relativePath images/test.jpg
*/
function getExtensionFileVscodeResource(context: ExtensionContext, relativePath: string) {
const diskPath = Uri.file(path.join(context.extensionPath, relativePath));
return diskPath.with({ scheme: 'vscode-resource' }).toString();
}
/**
* HTML文件读取能被Webview加载的HTML内容
* from: https://www.cnblogs.com/liuxianan/p/vscode-plugin-webview.html
* @param {*} context
* @param {*} templatePath html文件相对路径
*/
function getWebViewContent(context: ExtensionContext, templatePath: string) {
const resourcePath = path.join(context.extensionPath, templatePath);
const dirPath = path.dirname(resourcePath);
let html = fs.readFileSync(resourcePath, 'utf-8');
// vscode不支持直接加载本地资源需要替换成其专有路径格式这里只是简单的将样式和JS的路径替换
html = html.replace(/(<link.+?href="|<script.+?src="|<img.+?src=")(.+?)"/g, (m, $1, $2) => {
return $1 + Uri.file(path.resolve(dirPath, $2)).with({ scheme: 'vscode-resource' }).toString() + '"';
});
return html;
}
export default function useDiagram(context: ExtensionContext) {
const panel = window.createWebviewPanel(
'Diagram',
'Diagram',
ViewColumn.One,
{
enableScripts: true,
}
);
panel.webview.html = getWebViewContent(context, 'out/diagram/index.html')
.replace('{{ inject-script }}', `<script src="${getExtensionFileVscodeResource(context, 'out/diagram/diagram.js')}"></script>`);
}