forked from shader-slang/slang-playground
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathui.js
431 lines (385 loc) · 12.9 KB
/
ui.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
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
// target -> profile mappings
const targetProfileMap = {
// TODO: uncomment when we support specifying profiles.
//"SPIRV": {default:"1.5", options:["1.3", "1.4", "1.5", "1.6"]},
};
var entrypointSelect = null;
// Function to update the profile dropdown based on the selected target
function updateProfileOptions(targetSelect, profileSelect) {
const selectedTarget = targetSelect.value;
// Clear the existing options in profile dropdown
profileSelect.innerHTML = "";
// If the selected target does not have any profiles, hide the profile dropdown.
const profiles = targetProfileMap[selectedTarget] || null;
if (!profiles) {
document.getElementById("profile-dropdown").style.display = "none";
}
else{
document.getElementById("profile-dropdown").style = "";
// Populate the profile dropdown with new options
profiles.options.forEach((profile) => {
const option = document.createElement("option");
option.value = profile;
option.textContent = profile;
profileSelect.appendChild(option);
});
profileSelect.value = profiles.default;
}
// If the target can be compiled as a whole program without entrypoint selection, hide the entrypoint dropdown.
if (isWholeProgramTarget(targetSelect.value)) {
document.getElementById("entrypoint-dropdown").style.display = "none";
document.getElementById("entrypoint-select").value = "";
} else {
document.getElementById("entrypoint-dropdown").style = "";
updateEntryPointOptions();
}
}
function updateEntryPointOptions()
{
if (!compiler)
return;
if (!entrypointSelect)
return;
const prevValue = entrypointSelect.value;
entrypointSelect.innerHTML = "";
var defaultOption = document.createElement("option");
defaultOption.value = "";
defaultOption.textContent = "Entrypoint";
defaultOption.disabled = true;
entrypointSelect.appendChild(defaultOption);
const entryPoints = compiler.findDefinedEntryPoints(monacoEditor.getValue());
var prevValueExists = false;
entryPoints.forEach((entryPoint) => {
const option = document.createElement("option");
option.value = entryPoint;
option.textContent = entryPoint;
entrypointSelect.appendChild(option);
if (entryPoint === prevValue)
{
option.selected = true;
prevValueExists = true;
}
});
if (prevValue == "" && entryPoints.length > 0)
entrypointSelect.value = entryPoints[0];
else if (prevValueExists)
entrypointSelect.value = prevValue;
else
{
entrypointSelect.value = "";
defaultOption.selected = true;
}
}
// Set all containers to overflow:hidden before resizing so they can properly shrink.
function prepareForResize() {
var codeEditors = document.getElementsByClassName("editorContainer");
for (var i = 0; i < codeEditors.length; i++) {
if (codeEditors[i].style.display == "none")
continue;
codeEditors[i].style.overflow = "hidden";
}
document.getElementById("workSpaceDiv").style.overflow = "hidden";
document.getElementById("leftContainerDiv").style["overflow-x"] = "hidden";
targetResultContainer.style.overflow = "hidden";
}
// Restore the containers to overflow:visible after resizing.
function finishResizing() {
var codeEditors = document.getElementsByClassName("editorContainer");
document.getElementById("workSpaceDiv").style.overflow = "visible";
var leftContainer = document.getElementById("leftContainerDiv");
if (leftContainer.clientWidth < 30)
leftContainer.style["overflow-x"] = "hidden";
else
leftContainer.style["overflow-x"] = "visible";
for (var i = 0; i < codeEditors.length; i++) {
if (codeEditors[i].style.display == "none")
continue;
if (codeEditors[i].clientHeight < 30)
codeEditors[i].parentNode.style.overflow = "hidden";
codeEditors[i].style.overflow = "visible";
}
document.getElementById("reflectionTab").style["max-width"] = document.getElementById("rightContainerDiv").clientWidth + "px";
var canvasRect = document.getElementById("canvas").getBoundingClientRect();
renderOverlay.style.top = 5 + "px";
renderOverlay.style.left = (canvasRect.left + 5) + "px";
renderOverlay.style.display = canvasRect.height> 30?"block":"none";
resetMouse();
}
var finishResizingTimeout = null;
window.onresize = function () {
prepareForResize();
if (finishResizingTimeout)
clearTimeout(finishResizingTimeout);
finishResizingTimeout = setTimeout(() => {
finishResizing();
finishResizingTimeout = null;
}, 50);
};
function initializeModal() {
const modal = document.getElementById("helpModal");
const btn = document.getElementById("helpButton");
const closeBtn = document.querySelector(".close");
btn.onclick = () => {
modal.style.display = "flex";
};
closeBtn.onclick = () => {
modal.style.display = "none";
};
window.onclick = (event) => {
if (event.target === modal) {
modal.style.display = "none";
}
};
}
function loadDemo(selectedDemoURL) {
if (selectedDemoURL != "")
{
// Is `selectedDemoURL` a relative path?
var finalURL;
if (!selectedDemoURL.startsWith("http"))
{
// If so, append the current origin to it.
// Combine the url to point to demos/${selectedDemoURL}.
finalURL = new URL("demos/" + selectedDemoURL, window.location.href);
}
else
{
finalURL = new URL(selectedDemoURL);
}
// Retrieve text from selectedDemoURL.
fetch(finalURL)
.then((response) => response.text())
.then((data) => {
monacoEditor.setValue(data);
compileOrRun();
});
}
}
function handleDemoDropdown() {
const selectInput = document.getElementById("demo-select");
selectInput.addEventListener("change", function () {
loadDemo(this.value);
});
}
function restoreSelectedTargetFromURL()
{
const urlParams = new URLSearchParams(window.location.search);
const target = urlParams.get('target');
if (target) {
const targetSelect = document.getElementById("target-select");
const profileSelect = document.getElementById("profile-select");
targetSelect.value = target;
updateProfileOptions(targetSelect, profileSelect);
}
}
function restoreDemoSelectionFromURL()
{
const urlParams = new URLSearchParams(window.location.search);
var demo = urlParams.get('demo');
if (demo) {
if (!demo.endsWith(".slang"))
demo += ".slang";
const demoSelect = document.getElementById("demo-select");
demoSelect.value = demo;
loadDemo(demo);
return true;
}
return false;
}
function loadDemoList()
{
// Fill in demo-select dropdown using demoList.
let demoDropdown = document.getElementById("demo-select");
let firstOption = document.createElement("option");
firstOption.value = "";
firstOption.textContent = "Load Demo";
firstOption.disabled = true;
firstOption.selected = true;
demoDropdown.appendChild(firstOption);
// Create an option for each demo in the list.
demoList.forEach((demo) => {
let option = document.createElement("option");
option.value = demo.url;
option.textContent = demo.name;
if (demo.name == "-")
{
option.disabled = true;
option.textContent = "──────────";
}
demoDropdown.appendChild(option);
});
}
document.addEventListener("DOMContentLoaded", function () {
var initShaderCode = "";
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get('code');
if (code) {
decompressFromBase64URL(code).then((decompressed) => {
initShaderCode = decompressed;
loadEditor(false, "codeEditor", initShaderCode);
});
}
else {
loadEditor(false, "codeEditor", initShaderCode);
}
loadEditor(true, "diagnostics", "Diagnostic Output");
loadEditor(true, "codeGen", "Generated Target Code");
Split({
columnGutters: [
{
track: 1,
element: document.querySelector(".mainContainer > .gutter-horizontal"),
},
],
rowGutters: [
{
track: 1,
element: document.querySelector(".workSpace > .gutter-vertical"),
},
{
track: 1,
element: document.querySelector(".resultSpace > .gutter-vertical"),
},
],
onDragStart: ()=>prepareForResize(),
onDragEnd: ()=>{
finishResizingTimeout = setTimeout(() => {
finishResizing();
finishResizingTimeout = null;
}, 50);},
});
loadDemoList();
handleDemoDropdown();
// Target -> Profile handling
const targetSelect = document.getElementById("target-select");
const profileSelect = document.getElementById("profile-select");
entrypointSelect = document.getElementById("entrypoint-select");
entrypointSelect.addEventListener('focus', updateEntryPointOptions); // for keyboard access
entrypointSelect.addEventListener('mousedown', updateEntryPointOptions); // for mouse access
updateProfileOptions(targetSelect, profileSelect);
targetSelect.addEventListener("change", () => {
updateProfileOptions(targetSelect, profileSelect);
});
// modal functionality
initializeModal();
});
let pakoLoaded = false;
var pako = null;
// Lazy load function that loads pako on the first call
function loadPako() {
if (pako == null)
pako = BrowserCJS.require("https://cdnjs.cloudflare.com/ajax/libs/pako/2.0.4/pako.min.js");
return pako;
}
// Function to compress and decompress text, loading pako if necessary
async function compressToBase64URL(text) {
const pako = loadPako(); // Ensure pako is loaded
// Compress the text
const compressed = pako.deflate(text, { to: 'string' });
const base64 = btoa(String.fromCharCode(...new Uint8Array(compressed)));
return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
async function decompressFromBase64URL(base64) {
const pako = loadPako(); // Ensure pako is loaded
// Decode the base64 URL
base64 = base64.replace(/-/g, '+').replace(/_/g, '/');
const compressed = Uint8Array.from(atob(base64), c => c.charCodeAt(0));
// Decompress the data
const decompressed = pako.inflate(compressed, { to: 'string' });
return decompressed;
}
function showTooltip(button, text) {
document.getElementById("tooltip").textContent = text;
// Position the tooltip near the button
const rect = button.getBoundingClientRect();
tooltip.style.top = `${rect.bottom + window.scrollY + 15}px`;
tooltip.style.left = `${rect.left + window.scrollX}px`;
// Show the tooltip
tooltip.classList.add('show');
// Hide the tooltip after 3 seconds
setTimeout(() => {
tooltip.classList.remove('show');
}, 3000);
}
var btnShareLink = document.getElementById("shareButton");
btnShareLink.onclick = async function () {
if (!monacoEditor) return;
try{
const code = monacoEditor.getValue();
const compressed = await compressToBase64URL(code);
let url = new URL(window.location.href.split('?')[0]);
const compileTarget = document.getElementById("target-select").value;
url.searchParams.set("target", compileTarget)
url.searchParams.set("code", compressed);
navigator.clipboard.writeText(url.href);
showTooltip(btnShareLink, "Link copied to clipboard.");
}
catch(e){
showTooltip(btnShareLink, "Failed to copy link to clipboard.");
}
};
function openTab(tabId)
{
var buttons = [document.getElementById("btnTargetCode"), document.getElementById("btnReflection")];
if (tabId == 0)
{
document.getElementById("codeGen").style = "";
document.getElementById("reflectionTab").style.display = "none";
}
else
{
document.getElementById("codeGen").style.display = "none";
document.getElementById("reflectionTab").style.display = "block";
finishResizing();
}
for (var i = 0; i < buttons.length; i++)
{
if (i == tabId)
buttons[i].classList.add("tabButtonActive");
else
buttons[i].classList.remove("tabButtonActive");
}
}
document.addEventListener('keydown', function(event) {
if (event.key === 'F5')
{
event.preventDefault();
compileOrRun();
}
else if (event.ctrlKey && event.key === 'b')
{
event.preventDefault();
// Your custom code here
onCompile();
}
});
var canvasLastMouseDownPos = {x:0, y:0};
var canvasCurrentMousePos = {x:0, y:0};
var canvasIsMouseDown = false;
var canvasMouseClicked = false;
canvas.addEventListener("mousedown", function(event) {
canvasLastMouseDownPos.x = event.offsetX;
canvasLastMouseDownPos.y = event.offsetY;
canvasCurrentMousePos.x = event.offsetX;
canvasCurrentMousePos.y = event.offsetY;
canvasMouseClicked = true;
canvasIsMouseDown = true;
});
canvas.addEventListener("mousemove", function(event) {
if (canvasIsMouseDown) {
canvasCurrentMousePos.x = event.offsetX;
canvasCurrentMousePos.y = event.offsetY;
}
});
canvas.addEventListener("mouseup", function(event) {
canvasIsMouseDown = false;
});
function resetMouse()
{
canvasIsMouseDown = false;
canvasLastMouseDownPos.x = 0;
canvasLastMouseDownPos.y = 0;
canvasCurrentMousePos.x = 0;
canvasCurrentMousePos.y = 0;
canvasMouseClicked = false;
}