import * as vscode from 'vscode' ; import * as path from 'path' ; import * as fs from 'fs' ; import { showMessage , isProduction } from '../util/vscodeUtil' ; import { WebviewMsg } from '../util/dataStatement' ; interface WebviewPanelOption { type : string ; title : string ; fileName : string ; } param templatePath param content const getWebViewContent = ( templatePath , content ? ) : string => { const dirPath = path . dirname ( templatePath ) ; let res = content || fs . readFileSync ( templatePath , 'utf-8' ) ; res = res . replace ( /(<link.+?href="|<script.+?src="|<img.+?src=")(.+?)"/g , ( m , $1 , $2 ) => `${ $1 }${ vscode . Uri . file ( path . resolve ( dirPath , $2 ) ) . with ( { scheme : 'vscode-resource' } ) . toString ( ) }"` ) ; return res ; } ; class WebView { private currentPanel ! : vscode . WebviewPanel ; public readonly context : vscode . ExtensionContext ; public MessageCallBack : Function ; public constructor ( context , callBack ) { this . context = context ; this . MessageCallBack = callBack ; } public create ( WebviewPanelOption , column = vscode . ViewColumn . One ) { const srcPath = isProduction ( ) ? 'out' : 'src' ; this . currentPanel = vscode . window . createWebviewPanel ( WebviewPanelOption . type , WebviewPanelOption . title , column , { localResourceRoots : [ vscode . Uri . file ( path . join ( this . context . extensionPath , `${ srcPath }/assets` ) ) , ] , enableScripts : true , retainContextWhenHidden : true , } ) ; const htmlPath = path . join ( this . context . extensionPath , `${ srcPath }/views/${ WebviewPanelOption . fileName }.html` ) ; this . currentPanel . webview . html = getWebViewContent ( htmlPath ) ; this . currentPanel . webview . onDidReceiveMessage ( this . handleMessage . bind ( this ) , undefined , this . context . subscriptions ) ; } /**
     * 关闭webview
     */ public close ( ) { if ( ! this . currentPanel ) return ; this . currentPanel . dispose ( ) ; } public handleMessage ( message ) { const { command , data } = message ; if ( command !== 'msg' ) { this . MessageCallBack ( message ) ; return ; } showMessage ( data , command ) ; } param command param message public postMessage ( command , data ) { if ( ! this . currentPanel ) return ; this . currentPanel . webview . postMessage ( { command , data } ) ; } } export default WebView ;