extensionUtils.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /*
  2. * @Author: wjc
  3. * @Date: 2021-12-16 11:07:13
  4. * @LastEditors: wjc
  5. * @LastEditTime: 2021-12-16 15:14:55
  6. * @Description:
  7. */
  8. /* eslint-disable */
  9. import * as path from 'path'
  10. import * as vscode from 'vscode'
  11. const fs = require('fs')
  12. /**
  13. * 从某个HTML文件读取能被Webview加载的HTML内容
  14. * @param {*} context 上下文
  15. * @param {*} templatePath 相对于插件根目录的html文件相对路径
  16. */
  17. export function getWebViewContent(context, templatePath) {
  18. const resourcePath = path.join(context.extensionPath, templatePath)
  19. const dirPath = path.dirname(resourcePath)
  20. let html = fs.readFileSync(resourcePath, 'utf-8')
  21. // vscode不支持直接加载本地资源,需要替换成其专有路径格式,这里只是简单的将样式和JS的路径替换
  22. // /(<link.+?href=(?!http)|<script.+?src=(?!http)|<img.+?src="(?!http)|url\("(?!http))(.+?)[\s|>]/g
  23. html = html.replace(/(<link.+?href=(?!http))(.+?)\s/g, (m, $1, $2) => {
  24. return $1 + '"' + vscode.Uri.file(path.resolve(dirPath, $2)).with({ scheme: 'vscode-resource' }).toString() + '" '
  25. })
  26. html = html.replace(/(<script.+?src=(?!http))(.+?)>/g, (m, $1, $2) => {
  27. return $1 + '"' + vscode.Uri.file(path.resolve(dirPath, $2)).with({ scheme: 'vscode-resource' }).toString() + '"> '
  28. })
  29. html = html.replace(/(<img.+?src="(?!http)|url\("(?!http))(.+?)"/g, (m, $1, $2) => {
  30. return $1 + vscode.Uri.file(path.resolve(dirPath, $2)).with({ scheme: 'vscode-resource' }).toString() + '"'
  31. })
  32. return html
  33. }
  34. export async function resolveHandle(message, panel) {
  35. console.log('接收到webview信息', message)
  36. if (message.command === 'getCurrInterface') {
  37. panel.webview.postMessage(Object.assign(message, { command: 'reject', data: '未选择保存路径,取消生成' }))
  38. return
  39. }
  40. if (message.command === 'saveQueryPageFile') {
  41. panel.webview.postMessage(Object.assign(message, { data: 'ok' }))
  42. return
  43. }
  44. if (message.command === 'saveTypingFile') {
  45. panel.webview.postMessage(Object.assign(message, { data: 'ok' }))
  46. return
  47. }
  48. if (message.command === 'saveEditPageFile') {
  49. panel.webview.postMessage(Object.assign(message, { data: 'ok' }))
  50. return
  51. }
  52. }