-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathextension.js
271 lines (231 loc) · 7.56 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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
const vscode = require("vscode");
const io = require('socket.io-client');
const os = require('os');
const prefixAliasPath = () => "";
const ioOptions = {
path: prefixAliasPath("/socket.io"),
'pingInterval': 5000,
'pingTimeout': 15000
};
const localDir = ".kineviz-grove"
let socket = null;
function connectSocket(baseUrl) {
if (!socket) {
socket = io(`${baseUrl}/groveHotReload/`, ioOptions);
socket.on('connect', () => {
console.log('Connected to Grove hot reload socket');
});
socket.on('reloadResult', (result) => {
if (!result.success) {
vscode.window.showErrorMessage(`Reload failed: ${result.message}`);
}
});
socket.on('reloadError', (error) => {
vscode.window.showErrorMessage(`Reload error: ${error.message}`);
});
socket.on('disconnect', () => {
console.log('Disconnected from Grove hot reload socket');
});
}
return socket;
}
// This method is called when your extension is activated
// Your extension is activated the very first time the command is executed
/**
* @param {vscode.ExtensionContext} context
*/
function activate(context) {
// Create ~/.grove directory if it doesn't exist
const homedir = os.homedir();
const grovePath = vscode.Uri.file(`${homedir}/${localDir}`);
vscode.workspace.fs.createDirectory(grovePath);
// Use the console to output diagnostic information (console.log) and errors (console.error)
// This line of code will only be executed once when your extension is activated
console.log(
'Congratulations, your extension "helloworldvscode" is now active!'
);
const handleUri = async (uri) => {
const queryParams = new URLSearchParams(uri.query);
if (queryParams.has("open")) {
const baseUrl = queryParams.get("baseUrl");
const fileName = queryParams.get("open");
const workspaceEdit = new vscode.WorkspaceEdit();
// Create full path structure in ~/.grove instead of /tmp
const [protocol, host] = baseUrl.split("://");
const homedir = os.homedir();
const tempFolderUri = vscode.Uri.file(`${homedir}/${localDir}/${protocol}/${host}/${fileName}`).fsPath;
const fileUri = vscode.Uri.file(`${tempFolderUri}.grove`);
// Ensure all parent directories exist
const parentDir = fileUri.fsPath.substring(0, fileUri.fsPath.lastIndexOf('/'));
await vscode.workspace.fs.createDirectory(vscode.Uri.file(parentDir));
try {
// Fetch file contents from server
const apiKey = getApiKey(baseUrl);
if (!apiKey) {
vscode.window.showErrorMessage(`No API key found for ${baseUrl}`);
return;
}
const response = await fetch(`${baseUrl}${fileName}`, {
headers: {
'x-api-key': apiKey
}
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const fileContent = await response.json();
const mdContent = convertGroveToMd(fileContent);
// Create file
workspaceEdit.createFile(fileUri, { ignoreIfExists: true });
await vscode.workspace.applyEdit(workspaceEdit);
// Write content
await vscode.workspace.fs.writeFile(fileUri, Buffer.from(mdContent, 'utf8'));
// Open document
const document = await vscode.workspace.openTextDocument(fileUri);
await vscode.languages.setTextDocumentLanguage(document, "markdown");
await vscode.window.showTextDocument(document);
} catch (error) {
vscode.window.showErrorMessage(`Failed to fetch file: ${error.message}`);
}
}
};
context.subscriptions.push(
vscode.window.registerUriHandler({
handleUri,
})
);
// Register save event listener
const saveDisposable = vscode.workspace.onDidSaveTextDocument(async (document) => {
if (!document.fileName.includes(localDir)) {
return;
}
// Derive baseUrl from document path
const splitPath = document.fileName.split("/");
const groveIndex = splitPath.indexOf(".kineviz-grove");
const protocol = splitPath[groveIndex + 1];
const host = splitPath[groveIndex + 2];
const projectId = splitPath[groveIndex + 6];
const fileName = splitPath.slice(groveIndex + 7).join("/").replace(".grove", "");
const graphxrBaseUrl = `${protocol}://${host}`;
// Get api key
const apiKey = getApiKey(graphxrBaseUrl);
if (!apiKey) {
vscode.window.showErrorMessage(`No API key found for ${graphxrBaseUrl}`);
return;
}
// Parse the document content to find markdown code blocks
const content = document.getText();
const codeBlockRegex = /(?:<!--(.*)-->\n)?```(\w+)?\n([\s\S]*?)```/g;
const blocks = [];
let match;
while ((match = codeBlockRegex.exec(content)) !== null) {
const cellOptionsStr = match[1];
const codeContent = match[3].trim();
let cellOptions = {};
if (cellOptionsStr) {
cellOptions = JSON.parse(cellOptionsStr);
}
blocks.push({
type: "codeTool",
data: {
codeData: {
value: codeContent,
pinCode: cellOptions.pinCode ?? false,
dname: cellOptions.dname ?? crypto.randomUUID(),
codeMode: cellOptions.codeMode ?? "javascript2",
},
},
});
}
// Create form data
const formData = new FormData();
formData.append("fileName", fileName);
formData.append("projectId", projectId);
formData.append(
"data",
new Blob(
[
JSON.stringify({
blocks: blocks,
version: "2.19.1",
}),
],
{ type: "text/plain" }
)
);
try {
const simpleUploadUrl = `${graphxrBaseUrl}/api/grove/simpleUploadFile`
const response = await fetch(
simpleUploadUrl,
{
method: "POST",
headers: {
Accept: "application/json",
"x-api-key": apiKey,
},
body: formData,
}
);
const data = await response.text();
console.log(data);
// Use WebSocket for reload
socket = connectSocket(graphxrBaseUrl);
socket.emit('requestReload', { fileName, projectId });
} catch (error) {
vscode.window.showErrorMessage(`Upload failed: ${error.message}`);
}
});
context.subscriptions.push(saveDisposable);
}
function convertGroveToMd(grove) {
const blocks = grove.blocks;
const mdBlocks = blocks.map((block) => {
if (block.type === "codeTool") {
const {
pinCode,
dname,
codeMode,
value,
} = block.data.codeData;
const cellOptions = {
pinCode,
dname,
codeMode,
}
const cellOptionsStr = `<!--${JSON.stringify(cellOptions)}-->`;
return `${cellOptionsStr}\n\`\`\`${convertCodeModeToMd(codeMode)}\n${value}\n\`\`\``;
}
return block.data.text;
});
return mdBlocks.join("\n\n");
}
function convertCodeModeToMd(codeMode) {
/**
* Convert code mode to one which will be highlighted correctly by vscode markdown block highlighting
*/
switch (codeMode) {
case "javascript2":
return "js";
default:
return codeMode;
}
}
function convertCodeModeMdToGrove(codeMode) {
switch (codeMode) {
case "js":
return "javascript2";
default:
return codeMode;
}
}
// This method is called when your extension is deactivated
function deactivate() {}
function getApiKey(origin) {
const config = vscode.workspace.getConfiguration('grovebook');
const apiKeys = config.get('apiKeys');
return apiKeys[origin];
}
module.exports = {
activate,
deactivate,
};