-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebViewServer.js
More file actions
94 lines (91 loc) · 2.39 KB
/
webViewServer.js
File metadata and controls
94 lines (91 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/* jslint esversion:11 */
const vscode = require("vscode");
const fs = require("fs");
const extensionConfig = require("../extensionConfig.js");
const path = require("path");
const logger = require("../utils/logger.js");
// 最好能使用单例模式就好了
const webViewServer = {
create(viewColumn) {
this.panel = vscode.window.createWebviewPanel(
"docsifyPreviewer", // Webview id
"docsify Preview",
{ viewColumn: viewColumn, preserveFocus: decideFocus(viewColumn) },
{
enableScripts: true,
retainContextWhenHidden: true,
}
);
let innerPanel = this.panel;
this.panel.iconPath = extensionConfig.panelIconPath;
try {
this.panel.webview.html = getHtmlContent(extensionConfig.webViewHtmlPath);
} catch (err) {
logger.error(err);
}
return;
function getHtmlContent(filePath) {
let html = fs.readFileSync(filePath, "utf8");
return replaceVarialbe(html);
function replaceVarialbe(html) {
return html.replace(/\$\{([^\}]+)\}/g, (match, src) => {
return getSrcPath(src);
});
}
function getSrcPath(srcPath) {
const onDiskPath = vscode.Uri.file(
path.join(extensionConfig.webViewAssetsPath, srcPath)
);
const styleSrc = innerPanel.webview.asWebviewUri(onDiskPath);
return styleSrc;
}
}
},
postMessage(message) {
if (this.panel) {
this.panel.webview.postMessage(message);
}
},
onMessage(callback) {
this.panel.webview.onDidReceiveMessage((message) => {
callback(null, message);
});
},
jumpFirstTime(url, linePercent) {
this.postMessage({
command: "jumpFirstTime",
url: url,
linePercent: linePercent,
});
},
jump(url) {
this.postMessage({ command: "jump", url: url });
},
scroll(linePercent) {
this.postMessage({ command: "scroll", linePercent: linePercent });
},
setTitile(title) {
if (this.panel) {
this.panel.title = title;
}
},
onClose(callback) {
this.panel.onDidDispose(() => {
callback();
this.panel = null;
});
},
reveal(viewColumn) {
this.panel?.reveal(viewColumn, decideFocus(viewColumn));
},
close() {
this.panel?.dispose();
},
get visible() {
return this.panel?.visible;
},
};
function decideFocus(viewColumn) {
return vscode.ViewColumn.Two == viewColumn;
}
module.exports = webViewServer;