-
Notifications
You must be signed in to change notification settings - Fork 0
/
extension.js
192 lines (177 loc) · 5.82 KB
/
extension.js
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
const vscode = require('vscode');
const fs = require('fs');
/**
* @param {vscode.ExtensionContext} context
*/
function activate(context) {
// Track currently webview panel
let currentPanel = undefined;
let disposable = vscode.commands.registerCommand('webber.livepreview', () => {
const columnToShowIn = vscode.window.activeTextEditor
? vscode.window.activeTextEditor.viewColumn
: undefined;
// if (currentPanel) {
// // If we already have a panel, show it in the target column
// currentPanel.reveal(vscode.ViewColumn.Two);
// } else {
// // Otherwise, create a new panel
let currentPanel = vscode.window.createWebviewPanel(
"webber",
"Webber Live Preview",
vscode.ViewColumn.Two,
{
enableScripts: true,
retainContextWhenHidden: true,
localResourceRoots: [
vscode.Uri.file(context.extensionPath + '/media')
]
}
);
currentPanel.visible = true;
const filePath = vscode.Uri.file(context.extensionPath + '/media/index.html');
currentPanel.webview.html = fs.readFileSync(filePath.fsPath, 'utf8').replaceAll('__LF__', currentPanel.webview.asWebviewUri(vscode.Uri.file(context.extensionPath + '/media')));
currentPanel.iconPath = vscode.Uri.file(context.extensionPath + '/media/favicon.ico');
// // Reset when the current panel is closed
// currentPanel.onDidDispose(
// () => {
// currentPanel = undefined;
// },
// null,
// context.subscriptions
// );
var builderProcess = null;
function rebuild(doc, pwn) {
// console.log('rebuild called');
if (builderProcess != null) {
// console.warn('rebuild killed previous build');
builderProcess.kill('SIGKILL');
}
let document = doc ?? vscode.window.activeTextEditor.document;
// console.log('pwn', pwn);
let previewNames = pwn ?? [];
// console.log('previewNames', previewNames);
// console.log('rebuild looking for preview, lines: ' + document.lineCount);
for (let lineIndex = 0; lineIndex < document.lineCount; lineIndex++) {
const line = document.lineAt(lineIndex);
if (line.isEmptyOrWhitespace) continue;
if (!line.text.includes('_Preview')) continue;
let p1 = line.text.indexOf('class');
let p2 = line.text.indexOf('_Preview');
let p3 = line.text.indexOf('WebPreview');
if (!(p1 < p2 && p2 < p3)) continue;
previewNames.push(line.text.split('_Preview')[0].split('class ')[1]);
}
if (previewNames.length == 0) {
currentPanel.webview.postMessage({ type: 'previews.notfound' });
return;
}
document.save();
let filePath = document.fileName;
if (!filePath.endsWith('.swift')) return;
if (!filePath.includes('/Sources/')) return;
let cwd = filePath.split('/Sources/')[0];
let moduleName = filePath.split('/Sources/')[1].split('/')[0]
let previews = previewNames.map(name => moduleName + '/' + name ).join(',')
const command = `swift run -Xswiftc -DWEBPREVIEW ` + moduleName + ` --previews ` + previews + ` --build-path ./.build/.live`;
builderProcess = require('child_process')
.spawn(
'swift',
[
'run',
'--build-path', '.build/.live/',
'-Xswiftc', '-DWEBPREVIEW',
moduleName,
'--previews', previews
],
{ cwd }
);
var errors = '';
var resultJSON = '';
currentPanel.webview.postMessage({ type: 'build.start' });
builderProcess.stdout.on('data', function(msg) {
resultJSON += msg.toString();
// console.log('out line: ' + msg.toString());
});
builderProcess.stderr.on('data', function(msg) {
errors += msg.toString();
});
builderProcess.on('error', (error) => {
currentPanel.webview.postMessage({ type: 'build.fail' });
// console.error(`error: ${error.message}`);
});
builderProcess.on('close', (code) => {
if (code == 0) {
let previewData = JSON.parse(resultJSON);
// console.dir(previewData);
previewData.path = document.fileName;
currentPanel.webview.postMessage({ type: 'build.success', data: previewData });
} else if (code == 1 && errors.includes('unable to attach DB')) {
// console.warn('rebuild need restart');
rebuild();
} else {
if (!code) return;
currentPanel.webview.postMessage({ type: 'build.fail' });
}
});
}
vscode.workspace.onDidChangeTextDocument(changeEvent => {
if (changeEvent.document.uri != vscode.window.activeTextEditor.document.uri) return;
rebuild();
});
var lastATE = null;
vscode.window.onDidChangeActiveTextEditor(function (editor) {
if (editor) lastATE = editor;
if (builderProcess != null) {
// console.warn('rebuild killed previous build');
builderProcess.kill('SIGKILL');
}
let isSwift = editor.document.fileName.endsWith('.swift');
currentPanel.webview.postMessage({
type: 'document.switch',
data: {
path: editor.document.fileName,
isSwift: isSwift
}
});
if (isSwift) rebuild();
});
currentPanel.webview.onDidReceiveMessage(
message => {
switch (message.command) {
case 'addPreview':
if (lastATE.document.fileName.endsWith('.swift')) {
fs.appendFile(lastATE.document.fileName,
`
class MyNew_Preview: WebPreview {
override class var title: String { "My preview" } // optional
override class var width: UInt { 100 } // optional
override class var height: UInt { 100 } // optional
@Preview override class var content: Preview.Content {
// add styles if needed
// AppStyles.id(.happyStyle)
// add here as many elements as needed
Div("Hello world")
}
}
`
, function (err) {
if (err) throw err;
rebuild(lastATE.document, ['MyNew']);
});
}
return;
}
},
undefined,
context.subscriptions
);
if (vscode.activeTextEditor != undefined) rebuild();
});
context.subscriptions.push(disposable);
}
// this method is called when your extension is deactivated
function deactivate() {}
module.exports = {
activate,
deactivate
}