-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
635 lines (541 loc) · 18.8 KB
/
script.js
File metadata and controls
635 lines (541 loc) · 18.8 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
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
const checkResult = (result) => {
let errMsg = null;
if (result == null) {
errMsg = "panic";
} else if (result.error != "") {
errMsg = result.error;
}
return { valid: errMsg == null, errMsg: errMsg };
}
const go = new Go(); // from wasm_exec.js
let mod, inst;
const runBtn = document.getElementById("runBtn");
const debugBtn = document.getElementById("debugBtn");
const continueBtn = document.getElementById("continueBtn");
const debugOutput = document.getElementById("debugOutput");
const debugScope = document.getElementById("debugScope");
const statusBar = document.getElementById("statusBar");
let statusBarTimeout = null;
let runNumber = 0;
const infoBtn = document.getElementById("infoBtn");
let arrowRotation = 0;
const infoSection = document.getElementById("infoSection");
let isInfoSectionOpened = false;
const shareBtn = document.getElementById("shareBtn");
let shareBtnTimeout = null;
const pickVersionBtn = document.getElementById("pickVersionBtn");
const scopeVariables = document.getElementById("scopeVariables");
function reset() {
runBtn.disabled = false;
debugBtn.disabled = false;
continueBtn.disabled = true;
setReadonly(false)
selectOutput();
debugScope.style.display = 'none';
renderScopeVariables([]);
}
window.reset = reset;
function resetOutput() {
output.textContent = "";
}
function setDebug() {
runBtn.disabled = true;
debugBtn.disabled = true;
continueBtn.disabled = false;
setReadonly(true)
resetOutput();
debugScope.style.display = 'block';
}
function selectDebugOption(optionToSelect, optionsToDeselect) {
optionToSelect.classList.add("debugOptionSelected");
if (optionsToDeselect?.length > 0) {
optionsToDeselect.forEach(option => {
option.classList.remove("debugOptionSelected");
});
}
}
function activateDebugOption(optionToSelect, optionsToDeselect) {
optionToSelect.classList.add("active");
if (optionsToDeselect?.length > 0) {
optionsToDeselect.forEach(option => {
option.classList.remove("active");
});
}
}
function selectOutput() {
selectDebugOption(debugOutput, [debugScope]);
activateDebugOption(output, [scopeVariables]);
}
function selectScope() {
selectDebugOption(debugScope, [debugOutput]);
activateDebugOption(scopeVariables, [output]);
}
debugOutput.addEventListener("click", async () => {
selectOutput();
});
debugScope.addEventListener("click", async () => {
selectScope();
});
const VERSIONS = [
{ yaegi: "0.16.1", go: "Go 1.21 and 1.22" },
{ yaegi: "0.15.1", go: "Go 1.18 and 1.19" },
{ yaegi: "0.13.0", go: "Go 1.16 and 1.17" },
];
async function initWasm(version) {
pickVersionBtn.textContent = "Loading ...";
const resp = await fetch(`wasm/yaegi-${version.yaegi}.wasm`);
const buf = await resp.arrayBuffer();
const result = await WebAssembly.instantiate(buf, go.importObject);
mod = result.module;
inst = result.instance;
// Start the Go runtime (long-running)
go.run(inst);
reset();
pickVersionBtn.textContent = formatVersionName(version);
console.log(`Yaegi ${version.yaegi} is ready`);
}
initWasm(VERSIONS[0]);
runBtn.addEventListener("click", async () => {
const code = window.editor.getValue();
resetOutput();
let content = null;
try {
const result = runYaegi(code);
const { valid, errMsg } = checkResult(result);
if (!valid) {
content = errMsg;
showErrorStatus();
} else {
content = result.output;
showSuccessStatus();
}
} catch (ex) {
content = ex;
showErrorStatus();
}
output.textContent = content;
});
const mainSection = document.getElementById('mainSection');
const editor = document.getElementById('editor');
const resizer = document.getElementById('resizer');
const outputDiv = document.getElementById('outputDiv');
const output = document.getElementById('output');
function setReadonly(flag) {
if (window.editor?.updateOptions != null) {
window.editor.updateOptions({ readOnly: flag });
}
}
let isResizing = false;
let lastEditorRatio = 0.618;
function startResize(e) {
isResizing = true;
document.body.style.cursor = 'row-resize';
resizer.classList.add("active");
}
function stopResize() {
isResizing = false;
document.body.style.cursor = 'default';
resizer.classList.remove("active");
}
function doResize(clientY) {
const containerHeight = mainSection.clientHeight > 0 ? mainSection.clientHeight : 1;
let newEditorHeight = clientY - editor.offsetTop;
let newOutputHeight = containerHeight - newEditorHeight - resizer.offsetHeight;
const minHeight = 0.1 * containerHeight;
if (newEditorHeight < minHeight) {
newEditorHeight = minHeight;
}
newOutputHeight = containerHeight - newEditorHeight - resizer.offsetHeight;
if (newOutputHeight < minHeight) {
newOutputHeight = minHeight;
newEditorHeight = containerHeight - newOutputHeight - resizer.offsetHeight;
}
editor.style.height = `${newEditorHeight}px`;
outputDiv.style.height = `${newOutputHeight}px`;
lastEditorRatio = newEditorHeight / containerHeight;
}
resizer.addEventListener('mousedown', startResize);
document.addEventListener('mousemove', (e) => {
if (isResizing) doResize(e.clientY);
});
document.addEventListener('mouseup', stopResize);
resizer.addEventListener('touchstart', (e) => {
startResize(e.touches[0]);
});
document.addEventListener('touchmove', (e) => {
if (isResizing) doResize(e.touches[0].clientY);
});
document.addEventListener('touchend', stopResize);
window.addEventListener('resize', () => {
const containerHeight = mainSection.clientHeight;
const newEditorHeight = containerHeight * lastEditorRatio;
const newOutputHeight = containerHeight - newEditorHeight - resizer.offsetHeight;
editor.style.height = `${newEditorHeight}px`;
outputDiv.style.height = `${newOutputHeight}px`;
});
debugBtn.addEventListener("click", () => {
setDebug();
const code = window.editor.getValue();
const result = startYaegiDebug(code, window.getBreakpointLineNumbers());
const { valid, errMsg } = checkResult(result);
if (!valid) {
output.textContent += errMsg;
showErrorStatus();
}
});
continueBtn.addEventListener("click", () => {
const result = continueYaegiDebug();
const { valid, errMsg } = checkResult(result);
if (!valid) {
output.textContent += errMsg;
}
});
const DebugEventReason = {
debugRun: 0,
DebugPause: 1,
DebugBreak: 2,
DebugEntry: 3,
DebugStepInto: 4,
DebugStepOver: 5,
DebugStepOut: 6,
DebugTerminate: 7,
DebugEnterGoRoutine: 8,
DebugExitGoRoutine: 9
};
const DebugEventReasonName = Object.fromEntries(
Object.entries(DebugEventReason).map(([k, v]) => [v, k])
);
window.onDebugEvent = function (reason, stdout, infoFrames) {
console.log(DebugEventReasonName[reason]);
const position = infoFrames?.[0]?.position;
if (reason == DebugEventReason.DebugTerminate) {
reset();
window.highlightedLineNumber = null;
window.setDecorations();
showSuccessStatus();
return;
} else if (reason == DebugEventReason.DebugBreak && position != null) {
const bp = window.getBreakpointValues().find(bp => bp.position == position);
if (bp != null) {
window.highlightedLineNumber = bp.lineNumber;
console.log(`Highlight line ${bp.lineNumber} (${bp.position})`);
}
window.setDecorations();
renderScopeVariables(infoFrames[0].variables);
}
output.textContent = stdout;
};
function showSuccessStatus() {
showStatus(true);
}
function showErrorStatus() {
showStatus(false);
}
function showStatus(isSuccess) {
runNumber += 1;
showMessage(isSuccess, `Run #${runNumber}: ${isSuccess ? "Success" : "Error"}`);
}
function showMessage(isSuccess, message) {
statusBar.textContent = message;
statusBar.classList.remove(...[isSuccess ? "error" : "success"]);
statusBar.classList.add(...["active", isSuccess ? "success" : "error"]);
if (statusBarTimeout != null) {
clearTimeout(statusBarTimeout);
}
statusBarTimeout = setTimeout(() => {
statusBar.classList.remove("active");
}, 3000);
}
window.showMessage = showMessage;
infoBtn.addEventListener("click", () => {
toggleInfoSection();
});
function toggleInfoSection() {
isInfoSectionOpened = !isInfoSectionOpened;
arrowRotation += 180;
infoBtn.style.setProperty('--arrow-rotation', `${arrowRotation}deg`)
if (isInfoSectionOpened) {
infoSection.classList.add("active");
} else {
infoSection.classList.remove("active");
}
}
window.toggleInfoSection = toggleInfoSection;
function renderScopeVariables(variables) {
scopeVariables.innerHTML = "";
const table = document.createElement("table");
const colgroup = document.createElement("colgroup");
const widths = ["10%", "10%", "80%"];
widths.forEach(w => {
const col = document.createElement("col");
col.style.width = w;
colgroup.appendChild(col);
});
table.appendChild(colgroup);
const header = table.createTHead();
const headerRow = header.insertRow();
["Name", "Type", "Value"].forEach(text => {
const th = document.createElement("th");
th.textContent = text;
headerRow.appendChild(th);
});
const tbody = table.createTBody();
variables.forEach(v => {
const row = tbody.insertRow();
[v.name, v.type, v.value].forEach((col, idx) => {
const td = row.insertCell();
td.textContent = col;
if (idx == 2) {
td.style.cursor = "pointer";
td.classList.add("var-value");
td.addEventListener("click", async () => {
const scopeVars = inspectVariable(v.name, v.value);
if (scopeVars.length <= 0) {
td.classList.add("copied");
if (td.varValueTimeout != null) {
clearTimeout(td.varValueTimeout);
}
td.varValueTimeout = setTimeout(() => {
td.classList.remove("copied");
}, 1000);
await navigator.clipboard.writeText(v.value);
window.showMessage(true, `Copied value of ${v.name} to clipboard`);
}
});
}
});
});
scopeVariables.appendChild(table);
}
shareBtn.addEventListener("click", async () => {
try {
const encoded = window.base64UrlEncode(window.editor.getValue());
const link = `${window.location.href}#${encoded}`;
await navigator.clipboard.writeText(link);
window.showMessage(true, "Copied link to clipboard");
} catch (err) {
console.error("Failed to copy: ", err);
window.showMessage(false, "Failed to copy link");
return;
}
shareBtn.textContent = "Copied!";
shareBtn.classList.add("copied");
if (shareBtnTimeout != null) {
clearTimeout(shareBtnTimeout);
}
shareBtnTimeout = setTimeout(() => {
shareBtn.textContent = "Copy link";
shareBtn.classList.remove("copied");
}, 1000);
});
class ScopeVar {
constructor(str, startIndex, endIndex) {
this.startIndex = startIndex;
this.endIndex = endIndex;
this.value = str.slice(this.startIndex + 1, this.endIndex).trim();
}
}
const OPEN_CURLY = '{';
const CLOSE_CURLY = '}';
const OPEN_SQUARE = '[';
const CLOSE_SQUARE = ']';
const COMMA = ',';
const QUOTE = '"';
function printScopeVars(scopeVars) {
if (scopeVars == null || scopeVars.length <= 0) {
return;
}
scopeVars.forEach(sv => {
console.log(sv);
printScopeVars(processVariableString(sv.value))
});
}
function processVariableString(str) {
const scopeVars = [];
const pushScopeVar = (variableStr, startIndex, endIndex) => {
const scopeVar = new ScopeVar(variableStr, startIndex, endIndex);
if (scopeVar.value != "") {
scopeVars.push(scopeVar);
}
}
let currentStartIndex = 0;
let openChar = null;
let endChar = null;
let open = 0;
let quotesAreOpen = false;
for (let i = 0; i < str.length; i++) {
if (str[i] == QUOTE) {
quotesAreOpen = !quotesAreOpen;
}
if (quotesAreOpen) {
continue;
}
if (str[i] == OPEN_CURLY || str[i] == OPEN_SQUARE) {
if (openChar == null) {
currentStartIndex = i;
openChar = str[i];
endChar = openChar == OPEN_CURLY ? CLOSE_CURLY : CLOSE_SQUARE;
}
open += 1;
} else if (str[i] == CLOSE_CURLY || str[i] == CLOSE_SQUARE) {
open -= 1;
if (open == 0) {
pushScopeVar(str, currentStartIndex, i);
}
} else if (str[i] == COMMA && open == 1) {
pushScopeVar(str, currentStartIndex, i);
currentStartIndex = i;
}
}
return scopeVars;
}
const breadcrumb = [];
const LIST_TYPE_ARRAY = 0;
const LIST_TYPE_OBJ = 1;
function getListType(variableString) {
if (variableString[0] === OPEN_SQUARE) {
return LIST_TYPE_ARRAY;
} else if (variableString[0] === OPEN_CURLY) {
return LIST_TYPE_OBJ;
} else {
const squareIndex = variableString.indexOf(OPEN_SQUARE);
const curlyIndex = variableString.indexOf(OPEN_CURLY);
if (squareIndex === -1 && curlyIndex === -1) {
return LIST_TYPE_ARRAY;
} else if (squareIndex !== -1 && (curlyIndex === -1 || squareIndex < curlyIndex)) {
return LIST_TYPE_ARRAY;
} else {
return LIST_TYPE_OBJ;
}
}
}
function inspectVariable(variablePath, variableString) {
const scopeVars = processVariableString(variableString);
if (scopeVars.length <= 0) {
return scopeVars;
}
let listType = getListType(variableString);
breadcrumb.push(variablePath);
const container = document.createElement("div");
container.classList.add("modalContainer");
const frame = document.createElement("div");
frame.classList.add("modalFrame");
const headerSpan = document.createElement("span");
headerSpan.textContent = breadcrumb.join("");
const header = document.createElement("div");
header.classList.add("modalFrame-header");
header.appendChild(headerSpan);
frame.appendChild(header);
scopeVars.forEach((v, i) => {
let title = `${i}:`;
let path = `[${i}]`;
let content = v.value;
if (listType == LIST_TYPE_OBJ) {
const colonIndex = v.value.indexOf(":");
const firstPart = v.value.substring(0, colonIndex);
title = `${firstPart}:`;
content = v.value.substring(colonIndex + 1).trim();
if (firstPart.includes('"')) {
path = `[${firstPart}]`;
} else {
path = `.${firstPart}`;
}
}
const titleSpan = document.createElement("span");
titleSpan.classList.add("titleSpan");
titleSpan.textContent = title;
const contentSpan = document.createElement("span");
contentSpan.classList.add("contentSpan");
contentSpan.textContent = content;
const contentDiv = document.createElement("div");
contentDiv.classList.add("contentDiv");
contentDiv.appendChild(contentSpan);
contentDiv.addEventListener("click", async () => {
const scopeVars = inspectVariable(path, v.value);
if (scopeVars.length <= 0) {
contentDiv.classList.add("copied");
if (contentDiv.varValueTimeout != null) {
clearTimeout(contentDiv.varValueTimeout);
}
contentDiv.varValueTimeout = setTimeout(() => {
contentDiv.classList.remove("copied");
}, 1000);
await navigator.clipboard.writeText(v.value);
window.showMessage(true, `Copied value to clipboard`);
}
});
const row = document.createElement("div");
row.classList.add("modalFrame-row");
row.appendChild(titleSpan);
row.appendChild(contentDiv);
frame.appendChild(row);
});
container.appendChild(frame);
const overlay = document.createElement("div");
overlay.classList.add("modalOverlay");
overlay.appendChild(container);
overlay.addEventListener("click", (e) => {
if (!container.contains(e.target)) {
overlay.remove();
breadcrumb.pop();
}
});
document.documentElement.appendChild(overlay);
return scopeVars;
}
function pickVersion() {
const container = document.createElement("div");
container.classList.add("modalContainer");
const removeOverlay = (e) => {
if (e == null) {
overlay.remove();
} else if (!container.contains(e.target)) {
overlay.remove();
}
};
const overlay = document.createElement("div");
overlay.classList.add("modalOverlay");
overlay.appendChild(container);
overlay.addEventListener("click", (e) => {
removeOverlay(e);
});
const frame = document.createElement("div");
frame.classList.add("modalFrame");
const headerSpan = document.createElement("span");
headerSpan.textContent = "Select Go version";
const header = document.createElement("div");
header.classList.add("modalFrame-header");
header.appendChild(headerSpan);
frame.appendChild(header);
VERSIONS.forEach((version, i) => {
let title = `Yaegi ${version.yaegi}:`;
let content = version.go;
const titleSpan = document.createElement("span");
titleSpan.classList.add("titleSpan");
titleSpan.textContent = title;
const contentSpan = document.createElement("span");
contentSpan.classList.add("contentSpan");
contentSpan.textContent = content;
const contentDiv = document.createElement("div");
contentDiv.classList.add("contentDiv");
contentDiv.appendChild(contentSpan);
contentDiv.addEventListener("click", async () => {
removeOverlay();
await initWasm(version);
window.showMessage(true, `Loaded ${formatVersionName(version)}`);
});
const row = document.createElement("div");
row.classList.add("modalFrame-row");
row.appendChild(titleSpan);
row.appendChild(contentDiv);
frame.appendChild(row);
});
container.appendChild(frame);
document.documentElement.appendChild(overlay);
}
function formatVersionName(version) {
return `Yaegi ${version.yaegi} (${version.go})`;
}
pickVersionBtn.addEventListener("click", async () => {
pickVersion();
});