-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathindex.html
executable file
·523 lines (467 loc) · 18.6 KB
/
index.html
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
<!DOCTYPE html>
<html lang="en" dir="ltr" >
<head>
<meta name="http-equiv" content="Content-type: text/html; charset=UTF-8"/>
<link rel='shortcut icon' type='image/x-icon' href='favicon.ico' />
<title>A tour of Nix</title>
<!--[if IE]>
<meta HTTP-EQUIV="REFRESH" content="0; url=https://www.mozilla.org/en-US/firefox/new/">
<![endif]-->
<link href="bootstrap-5.0.2/bootstrap.min.css" rel="stylesheet">
<script src="bootstrap-5.0.2/bootstrap.bundle.min.js"></script>
<script type="text/javascript" src="nix-instantiate.js"></script>
<script type="text/javascript" src="markdown.min.js"></script>
<script type="text/javascript" src="FileSaver.min.js"></script>
<link rel="stylesheet" href="codemirror-5.5/lib/codemirror.css">
<link rel="stylesheet" href="codemirror-5.5/addon/lint/lint.css">
<link rel="stylesheet" href="style.css" type="text/css"/>
<link id ="styleMobile" rel="stylesheet" href="style_mobile.css" type="text/css"/>
<link rel="stylesheet" href="font/font.css" type="text/css"/>
<script type="text/javascript" src="codemirror-5.5/lib/codemirror.js"></script>
<script type="text/javascript" src="codemirror-5.5/addon/lint/lint.js"></script>
<script type="text/javascript" src="codemirror-5.5/mode/shell/shell.js"></script>
<script type="text/javascript" charset="utf-8">
// global variables
var initialized = 0;
var selected_question = 0;
var questions;
var current_question = 0;
var editingQuestionText = false;
// export current question object to questions.json
var saveQuestions = function() {
// http://stackoverflow.com/questions/7486085/copying-array-by-value-in-javascript
var t = JSON.parse(JSON.stringify(questions));
for (i = 0; i < t.length; i++) {
t[i].code = t[i].mycode;
t[i].solution = t[i].mysolution;
delete t[i].mycode;
delete t[i].mysolution;
delete t[i].result;
delete t[i].resultColor;
}
// hack: might not have been synced yet (click next and prev for example, to do so)
t[selected_question].solution = document.getElementById("solution").value;
t[selected_question].code = editor.getValue();
var questionsJSON = JSON.stringify(t, null, 4)
var blob = new Blob([questionsJSON], {type: "text/plain;"});
saveAs(blob, "questions.json");
}
// on import, create a copy of code into mycode so we can use the 'reset' button
var prepare_data = function () {
for(i = 0; i < questions.length; i++) {
questions[i].mycode = questions[i].code;
questions[i].mysolution = questions[i].solution;
}
}
// hack to make the textarea resize to the exact size needed to view all the data and not more
var auto_resize = function (e) {
e.style.height = 'auto';
e.style.height = e.scrollHeight + 2 +'px';
}
// parses the id=23 from the url
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null
}
var indexToPath = function (index) {
if (index === "") {
console.log("index is invalid, returning 0");
return 0;
}
if (index - 1 > questions.length) {
console.log("index is bigger than questions.length -1, returning 0");
return 0;
}
return questions[index - 1].path;
}
var pathToIndex = function (path) {
if (path === "") {
return 0;
}
for (let i = 0; i < questions.length; i++) {
if (questions[i].path === path) {
return i;
}
}
return 0;
}
function load_wanted_page() {
let id = getURLParameter("id");
let i = parseInt(id);
//console.log("parser of getURLParameter found: " + getURLParameter("id"))
//console.log("parser of getURLParameter found: " + i)
if (!isNaN(i)) {
change_question(i-1)
} else {
let v = pathToIndex(id);
change_question(v)
}
}
//loads the questions.json from the webpage
function loadJSON(path, success, error) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
if (success)
success(JSON.parse(xhr.responseText));
} else {
if (error)
error(xhr);
}
}
};
xhr.open("GET", path, true);
xhr.send();
}
loadJSON('questions.json',
function(data) {
questions = data;
const uniqueSet = new Set();
// Iterate through the array
for (const q of questions) {
// If the item is already in the Set, it's not unique
if (q.path === undefined) {
console.log("error: questions contains undefined path: " + q.topic)
return false;
}
if (uniqueSet.has(q.path)) {
console.log("error: questions contains none-unique path for: " + q.path)
return false;
}
// Add the item to the Set to track it
uniqueSet.add(q.path);
}
prepare_data();
load_wanted_page();
},
function(xhr) {
console.error(xhr);
}
);
// shortcuts
var keys = [];
function keysPressed(e) {
keys[e.keyCode] = true;
if (keys[16] && keys[13]) { // shift+return
runNix()
e.preventDefault();
}
if (keys[17] && keys[74]) { // ctrl+ k
console.log("change_question(1);");
change_question(1);
e.preventDefault();
}
if (keys[17] && keys[75]) { // ctrl+.j
console.log("change_question(-1);");
change_question(-1);
e.preventDefault();
}
if (keys[17] && keys[190]) { // ctrl+.
markdown2html();
e.preventDefault();
}
if (keys[17] && keys[188]) { // ctrl+,
load_markdown();
e.preventDefault();
}
if (keys[17] && keys[73]) { // ctrl+i
resetQuestion();
e.preventDefault();
}
if (keys[17] && keys[83]) { // ctrl+i
saveQuestions();
e.preventDefault();
}
}
function keysReleased(e) {
// mark keys that were released
keys[e.keyCode] = false;
}
window.addEventListener("keydown", keysPressed, false);
window.addEventListener("keyup", keysReleased, false);
// implement browser forward and back button actions
window.addEventListener("popstate", function(e) {
let id = getURLParameter("id");
let i = parseInt(id);
//console.log("parser of getURLParameter found: " + getURLParameter("id"))
//console.log("parser of getURLParameter found: " + i)
if (!isNaN(i)) {
change_question_withoutHistoryChange(i - 1 - current_question)
} else {
let v = pathToIndex(id);
change_question_withoutHistoryChange(v - current_question)
}
});
// update current question and modify the window.history
var change_question = function(myinput) {
change_question_withoutHistoryChange(myinput);
window.history.pushState('', '', window.location.pathname + '?id=' + indexToPath(current_question + 1));
}
// update current question and NOT modifying the window.history
var change_question_withoutHistoryChange = function (myinput) {
// save old state
if (editingQuestionText == true)
alert("editor must be closed before opening a different question, now everything is corrupted -> reload and start over. sorry (qknight)")
var output = document.getElementById('output');
// prevent overwriting with 'empty data' on the first page load
if (initialized) {
questions[current_question].mycode = editor.getValue();
questions[current_question].mysolution = document.getElementById('solution').value;
questions[current_question].result = output.value;
questions[current_question].resultColor = output.style.backgroundColor;
auto_resize(output)
}
initialized=1;
current_question += myinput;
output.style.backgroundColor = "grey";
if (current_question < 0)
current_question = 0;
if (current_question >= questions.length-1)
current_question = questions.length-1;
var contentTitle = document.getElementById('contentTitle');
var contentText = document.getElementById('contentText');
var contentSolution = document.getElementById('solution');
var topic = questions[current_question].topic;
var question = questions[current_question].question;
var mycode = questions[current_question].mycode;
var mysolution = questions[current_question].mysolution;
var youtube_url = questions[current_question].youtube;
contentSolution.style.display="none";
contentTitle.innerHTML = String(current_question + 1 + "<font size=\"3%\"> / " + questions.length + "</font>" + " " + topic);
var paypal='<p><form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top"> <input type="hidden" name="cmd" value="_donations"> <input type="hidden" name="business" value="[email protected]"> <input type="hidden" name="lc" value="DE"> <input type="hidden" name="item_name" value="Help Paul and Joachim in making a tour of nix better!"> <input type="hidden" name="no_note" value="0"> <input type="hidden" name="currency_code" value="EUR"> <input type="hidden" name="bn" value="PP-DonationsBF:btn_donate_SM.gif:NonHostedGuest"> <input type="image" src="paypal.gif" border="0" name="submit" alt="Jetzt einfach, schnell und sicher online bezahlen – mit PayPal."> </form></p>'
var youtube = "<p><b>Note:</b> See video <a href='" + youtube_url + "'>@youtube</a></p>";
var text = markdown.toHTML(question) + youtube;
contentText.innerHTML = text.replace("??PAYPAL??", paypal);
var links = document.links;
for (var i = 0, linksLength = links.length; i < linksLength; i++) { //>
if (links[i].hostname != window.location.hostname) {
links[i].target = '_blank';
}
}
contentSolution.value = mysolution;
auto_resize(contentSolution);
editor.setValue(mycode);
if (typeof(questions[current_question].result) !== "undefined")
output.value = questions[current_question].result;
else
output.value = "";
if (typeof(questions[current_question].resultColor) !== "undefined")
output.style.backgroundColor = questions[current_question].resultColor;
auto_resize(output);
auto_resize(contentSolution);
selected_question = current_question;
};
// force the two-paned layout even though horizontal space is 'actually' too little
flipStylesheet = function() {
document.getElementById("styleMobile").disabled = !document.getElementById("styleMobile").disabled;
}
var showSolution = function() {
var s = document.getElementById('solution');
if (s.style.display == "none") {
s.style.display = "flex";
auto_resize(s);
} else {
s.style.display = "none";
}
}
var resetQuestion = function() {
editor.setValue(questions[selected_question].code);
var s = document.getElementById('solution');
s.value = questions[selected_question].solution;
var output = document.getElementById('output');
output.style.backgroundColor = "grey";
console.log("reset question")
}
// embedded 'Questions' editor using the 'editor'
// generate preview & close
var markdown2html = function() {
var contentText = document.getElementById('contentText');
if (editingQuestionText == true) {
var text = editor.getValue();
if (text == questions[selected_question].question) {
// qutting the editor
editor.setValue(questions[selected_question].mycode);
editingQuestionText = false;
} else {
// console.log("6.1")
// changes were detected, so we just update the preview
var p = markdown.toHTML(text);
// console.log("6.2")
contentText.innerHTML = p;
// console.log("6.3")
delete p;
questions[selected_question].question = text;
}
}
}
// embedded 'Questions' editor using the 'editor'
// open the editor
var load_markdown = function() {
if (editingQuestionText == false) {
editingQuestionText = true;
questions[current_question].mycode = editor.getValue();
var text = questions[current_question].question;
editor.setValue(text.split('\\n').join('\n').replace("\\\"", "\""))
}
}
Module['arguments'] = ['-I', 'nixpkgs=nixpkgs', '--eval', '--strict', '--show-trace', '/test.nix'];
function extractLineAndPosition(inputString) {
const pattern = /line:(\d+):(\d+)/;
const match = inputString.match(pattern);
if (match) {
const lineNumber = parseInt(match[1], 10);
const textPosition = parseInt(match[2], 10);
return { found: true, lineNumber, textPosition };
} else {
// Return a default value indicating that the pattern was not found.
return { found: false, lineNumber: -1, textPosition: -1 };
}
}
function highlightError(error_message) {
const result = extractLineAndPosition(error_message);
if (result.found) {
console.log("Pattern found:");
console.log("Line Number:", result.lineNumber);
console.log("Text Position:", result.textPosition);
var marker = document.createElement("div");
marker.setAttribute('class', 'CodeMirror-lint-marker-error');
marker.setAttribute('title', error_message);
editor.setGutterMarker(result.lineNumber - 1,'gutter-error', marker);
} else {
console.log("Pattern not found in the input string.");
}
}
// primary routine to execute the code from the editor in nix-instantiate
var runNix = function() {
editor.clearGutter('gutter-error');
var start = new Date().getTime();
// Module['arguments'] = ['-I', 'nixpkgs=nixpkgs', '--eval', '--strict', '--show-trace', '/test.nix'];
// run the solution
var correct_solution;
Module['print'] = function(text) {
// Module['return'] = text + '\n';
correct_solution = text;
var end = new Date().getTime();
var time = end - start;
console.log('Execution time: ' + time + ' ms');
};
Module['printErr'] = function(text) {
//this should not happen
//TODO exception handling
};
var solution_text = questions[current_question].solution;
FS.writeFile('/test.nix', solution_text, {encoding: 'utf8'});
//var result = FS.readFile('test.nix', {encoding: 'utf8'});
//console.log(result);
// Module['arguments'] = ['-I', 'nixpkgs=nixpkgs', '--eval', '--strict', '--show-trace', '/test.nix'];
Module.callMain(Module['arguments']);
//run the user input
console.log("running runNix()");
document.getElementById('runInfo').innerHTML = "computation in progress";
document.getElementById('output').value = "";
Module['print'] = function(text) {
// Module['return'] = text + '\n';
var o = document.getElementById('output');
if (text == correct_solution){
console.log("correct answer");
o.value = text;
o.style.backgroundColor = "#44aa44";
// setTimeout(function () {o.style.backgroundColor = "grey"}, 2000);
} else {
console.log("incorrect answer");
o.value = "your solution:\n" + text + "\nexpected was:\n" + correct_solution;
o.style.backgroundColor = "#aa4444";
// setTimeout(function () {o.style.backgroundColor = "grey"}, 2000);
}
auto_resize(o);
document.getElementById('runInfo').innerHTML = "";
};
Module['printErr'] = function(text) {
text = text.replace("[31;1m", "");
text = text.replace("[1m", "");
text = text.replace("[1m", "");
text = text.replace("[0m","");
text = text.replace("[0m","");
text = text.replace("/test.nix","line");
text = text.replace("/test.nix","line");
text = text.replace("/test.nix","line");
text = text.replace("/test.nix","line");
text = text.replace(//g, "");
// text = text.replace(":error:", ":\nerror");
console.log(text);
highlightError(text); // runNix() return one line per error (up to several lines) and highlightError is called per line
// Module['return'] = text + '\n';
document.getElementById('runInfo').innerHTML = "";
var o = document.getElementById('output')
o.value += text +"\n";
auto_resize(o)
console.log("incorrect answer");
// o.value += text;
o.style.backgroundColor = "#aa4444";
// setTimeout(function () {o.style.backgroundColor = "grey"}, 2000);
};
var input_text = editor.getValue();
FS.writeFile('/test.nix', input_text, {encoding: 'utf8'});
// Module['arguments'] = ['-I', 'nixpkgs=nixpkgs', '--eval', '--strict', '--show-trace', '/test.nix'];
//var result = FS.readFile('test.nix', {encoding: 'utf8'});
//console.log(result);
Module.callMain(Module['arguments']);
};
</script>
</head>
<body>
<div id="spinner" class="spinner-flex-container-row">
<div class="spinner-flex-container-col">
<div id="spinner-icon"><img src="nix.gif"></div>
<div id="status">Downloading...</div>
<progress value="0" max="100" id="progress" hidden=1>progress</progress>
</div>
</div>
<div class="flex-container-col">
<div id="header_container" class="flex-container-row">
<div id="header"><h1>A tour of Nix</h1></div>
<div class="d-flex mt-1 gap-2 pe-2">
<a target="_blank" href="https://github.com/nixcloud/tour_of_nix" id="gotogh"></a>
<div role="button" id="rotate" onclick="flipStylesheet()"></div>
</div>
</div>
<div id="middle" class="flex-container-row">
<div id="left" class="flex-container-col">
<div id="adsfas" class="flex-container-col">
<textarea class="input" id="input" rows="8">demo text textarea</textarea>
<div id="editorButtonGroup" class="flex-container-row">
<button type="button" class="myButton button" id="resetButton" onClick="resetQuestion()" title="">reset</button>
<button type="button" class="myButton button" id="solutionButton" onClick="showSolution()" title="">solution</button>
<button type="button" class="myButton button" id="runButton" onClick="runNix()" title="use shift+return">run</button>
</div>
</div>
<textarea id="output" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"></textarea>
<textarea id="solution" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"></textarea>
<div id="runInfo"></div>
</div>
<div id="right" class="flex-container-col">
<div id="questionNavigation" class="flex-container-row">
<button type="button" class="myButton button" id="prevButton" title="use ctrl+k" onClick="change_question(-1)" >prev</button>
<button type="button" class="myButton button" id="nextButton" title="use ctrl+j" onClick="change_question(1)" >next</button>
</div>
<h2><div id="contentTitle">A tour of Nix_</div></h2>
<div id="contentText">If you can see this, <b>questions.json</b> wasn't loaded properly!<br><br>
Javascript execution: <b><div id="testJS">failed, are you blocking JS execution? This webpage won't work without JS!</div></b>.
</div>
</div>
</div>
</div>
<div id="footerFG"> </div>
<div id="footerBG"><img src="footerBG.jpg" width="100%" height="100%"/></div>
<script type="text/javascript">
var input = document.getElementById('input');
var editor = CodeMirror.fromTextArea(input, {
lineNumbers: true,
viewportMargin: Infinity,
gutters: ['gutter-error'],
});
document.getElementById('testJS').innerHTML = "works! Maybe wait a little longer as this webpage is rather big with 27Mib!";
</script>
</body>
</html>