-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
583 lines (559 loc) · 20.8 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
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
<!DOCTYPE html>
<html>
<head>
<title>Canvas</title>
<meta charset="UTF-8" />
<script src="bigDecimal.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="toptitle" style="text-align: center;">
<a style="height:10px; margin-top:0; margin-bottom: 10px; font-weight:bold; font-size:2em;" href=https://github.com/dzaima/Canvas>Canvas</a>
</div>
<div id="p" style="width:40%;"><span id="bytecount" style="font-size:12px">0 bytes</span></div>
<div id="textareas">
<div class="left" id="progdiv">
<textarea id="program" placeholder="Enter code..." spellcheck="false" onclick="setTimeout(updater, 0);" oninput="setTimeout(updater, 0);" style="height:150px"></textarea>
</div>
<div align="left" class="right" id="inpdiv">
<textarea id="inputs" placeholder="Enter inputs in each line" spellcheck="false" style="width:100%; height:150px"></textarea>
<div id="docs" style="display:none" align="left">
<div style="padding-bottom: 5px">
<input id="search" style="width:93%;" onclick="setTimeout(updater, 0);" oninput="setTimeout(updater, 0);"
placeholder="search for chars, descriptions, ect."/>
</div>
<div id="docs-scroll">
<table id="docstable" style="width:99%" align="left">
<col width="3%" />
<col width="95%" />
<thead>
<tr>
<th>chr</th>
<th>description</th>
</tr>
</thead>
</table>
</div>
</div>
<div id="stepData" style="display:none">
<span class="codebox">
<h2>State</h2>
<span id="codeState" class="code"></span><br><br>
X = <span id="stateX"></span><br>
Y = <span id="stateY"></span><br>
α = <span id="stateAlpha"></span><br>
ω = <span id="stateOmega"></span><br>
remainders = <span id="stateRemainders"></span><br>
superscripts = <span id="stateSups"></span><br>
background = <span id="bgState"></span><br>
<h2>Program stack</h2>
<span class="code" id="ptrstackState"></span>
<h2>Stack</h2>
<div class="code" id="stackState"></div>
</span>
</div>
</div>
<textarea id="result" placeholder="Output will be here" spellcheck="false" style="width:100%; background-color: #333333; height:390px" readonly></textarea>
</div>
<div id="overlay">
<div id="overlayMenu">
<center>
<span id="menuTitle" style="font-size:1.4em"></span>
<br>
<input id="saveName" style="position: relative; top:5%" placeholder="enter name" onclick="setTimeout(updateSaveList, 0);" oninput="setTimeout(updateSaveList, 0);"/>
<br><br>
<div id="saveList">
</div>
</center>
</div>
</div>
<div id="buttonPanel">
<div style="width:120px" class="left">
<button id="runBtn" onclick="runMain()" style="width:100%">run (ctrl+enter) </button>
<button id="loadFile" onclick="loadFile()" style="width:100%">load encoded file</button>
<button id="saveFile" onclick="saveFile()" style="width:100%">save encoded file</button>
</div>
<div style="width:60px" class="left">
<button id="stopBtn" onclick="stop()" style="width:100%; display:none">stop</button>
<button id="topost" onclick="postify()" style="width:100%">postify </button>
<button id="toCMC" onclick="CMCify()" style="width:100%">CMCify </button>
</div>
<div class="left" style="width:100px">
<input id="devChk" type="checkbox" onClick="devUpdate()">dev mode</input><br>
<div class="left" style="width:60px">
<button id="loadpermalink" onclick="loadPermalink()" style="width:100%; display:none">reload</button>
<button id="stepBtn" onclick="step()" style="width:100%; display:none">step</button>
</div>
</div>
</div>
<input id="fakeFileInp" type="file" style="display:none" />
<a id="fakeLink" style="display:none" />
<script>
program.focus();
var latestVersion = 8;
var module = 0; // node is annoying & this can't be a more meaningful variable name
var usedVersion = latestVersion;
var devMode = false;
var debug = 0; // 0 - no debug; 1 - program debug; 2 - interpreter debug
var running = false;
var stepping = false;
var stepNow = false;
var devLoaded = false;
var lastSearch = "";
if (devChk.checked) devUpdate(); // for Firefox-ish reloads that keep checked
var debugLog = console.log;
// loading initial permalinked data
var args = location.search.substring(1).split(",");
for (var i = 0; i < args.length; i++) {
var carg = args[i];
var parts = carg.split("=");
if (parts[0]==='u')
program.value = unescape(atob(parts[1].replace(/_/g, "=")));
if (parts[0]==='i')
inputs.value = unescape(atob(parts[1].replace(/_/g, "=")));
if (parts[0]==='v')
usedVersion = +parts[1];
if (parts[0]==='dev') {
devChk.click();
}
if (parts[0]==='d') {
debug = +parts[1];
}
if (parts[0]==='tests') {
setTimeout(tests, 200);
}
if (parts[0]==='search') {
devChk.click();
search.value=unescape(parts[1]);
}
}
if (latestVersion !== usedVersion) {
toptitle.innerHTML+='<a style="color:#D2D2D2" onclick="toLatest()" href="#" title="using v'+usedVersion+' for compatibility; Click to switch to v'+latestVersion+'">v'+usedVersion+'</a>'
}
// dev mode
function toLatest() {
window.location = permalink(2)+(devMode? ",dev" : "");
}
let strComp1 = "enter parts in the input field as separate lines, with ¶ as newlines and ŗ as popping from stack\nThis doesn't count the starting quote in the bytecount\nI.split`\\n`#:clip(compressString(p.p))#QL╷;∑Lŗ -> ŗ bytes∙p.F#";
let strComp2 = "enter parts in the input field as separate lines, with ¶ as newlines and ŗ as popping from stack\nThis doesn't count the starting quote in the bytecount\n\ndebugCompression=true;I.split`\\n`#:clip(compressString(p.p))#QL╷;∑Lŗ -> ŗ bytesO∙p.F;compressionParts.slice(0,-1).map(c=>c.map(c=>[c.type,c.length]))#{{┤“q&„:└×U;÷] *]";
if (!localStorage.saves) {
localStorage.saves = JSON.stringify([
["string compress", strComp1, "", 1],
["number compress", "clip(compressNum(p.p))#p.F#", "", 1],
]);
}
if (JSON.parse(localStorage.saves).find(c=>c[1]==strComp1)) {
let saves = JSON.parse(localStorage.saves);
saves[JSON.parse(localStorage.saves).findIndex(c=>c[1]==strComp1)][1] = strComp2;
localStorage.saves = JSON.stringify(saves);
}
function devUpdate() {
devMode^= true;
if (devMode) {
if (!devLoaded) {
$.getScript("docs.js").fail((_,_2,c)=>console.error("docs.js failed to load:", c));
devLoaded = true;
}
progdiv.appendChild(inputs);
progdiv.appendChild(result);
docs.before(buttonPanel);
inputs.style.width="99%";
result.style.width="99%";
docs.style.display = "block";
loadpermalink.style.display = "block";
stepBtn.style.display = "block";
stopBtn.style.display = "block";
if (!debug) debug = 1;
} else {
inpdiv.appendChild(inputs);
textareas.appendChild(result);
textareas.after(buttonPanel);
inputs.style.width="100%";
result.style.width="100%";
docs.style.display = "none";
if (stepping && running) stepNow = true;
stepping = false;
stepData.style.display = "none";
loadpermalink.style.display = "none";
stepBtn.style.display = "none";
stopBtn.style.display = "none";
if (debug === 1) debug = 0;
}
}
function loadPermalink(forceOnline) {
window.location = permalink(forceOnline? 1 : 0) + ",dev";
}
function step() {
if (!stepping) enterStepping();
if (running) stepNow = true;
else runMain();
}
function stop() {
running = false;
if (stepping) stopStepping();
stepNow = true;
}
function enterStepping() {
stepping = true;
docs.style.display = "none";
stepData.style.display = "block";
}
function stopStepping() {
stepping = false;
docs.style.display = "block";
stepData.style.display = "none";
}
// saving to encoded file
function saveFile() {
const prog = program.value;
fakeLink.download = "encoded.canvas";
var binary = "";
for (var i = 0; i < prog.length; i++) {
binary+= String.fromCodePoint(codepage.indexOf(prog.charAt(i)));
}
fakeLink.href = 'data:text/plain;base64,' + btoa(binary);
fakeLink.click();
}
// loading from encoded file
var fr;
function loadFile() {
fakeFileInp.click();
}
$("#fakeFileInp").change(function () {
var f = fakeFileInp.files[0];
fr = new FileReader();
fr.onload = recieved;
fr.readAsBinaryString(f);
});
function recieved() {
var binary = fr.result;
var newProgram = "";
for (var i = 0; i < binary.length; i++) {
newProgram+= codepage.charAt(binary.charCodeAt(i));
}
program.value = newProgram;
update();
}
function postify() {
let pl = permalink(1);
let prog = program.value;
result.value = `# [Canvas](https://github.com/dzaima/Canvas), ${prog.length} [byte${prog.length===1? "" : "s"}](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)`;
for (var cs of program.value.split("\n")) result.value+= "\n "+cs;
result.value+= `\n\n[Try it here!](${pl})`;
}
function CMCify() {
let pl = permalink(1);
let prog = program.value;
result.value = `Canvas, ${prog.length} byte${prog.length===1? "" : "s"}: [\`${prog.replace(/\n/g, "\\n")}\`](${pl})`;
result.value+= `\nCanvas, [${prog.length} byte${prog.length===1? "" : "s"}](${pl})`;
}
// permalink stuff
function permalink(param) {
let res;
if (param === 1) res = "https://dzaima.github.io/Canvas/?";
else res = [location.protocol, '//', location.host, location.pathname].join('')+"?";
res+= "u="+ (btoa(escape(program.value)).replace(/=/g, "_"));
var inputs = document.getElementById("inputs").value;
if (inputs !== "")
res+= ",i="+ btoa(escape(inputs)).replace(/=/g, "_");
res+= ",v="+(param===2? latestVersion : version);
result.value = res;
if (param === 2) {
result.select();
document.execCommand("copy");
}
return res;
}
// byte count updating & program running
function runMain() {
if (running) throw "already running!";
var inputstrs = inputs.value.split("\n");
var inputsParsed = [];
var cres = "";
for (var i = 0; i < inputstrs.length; i++) {
var cl = inputstrs[i];
if (cl === "```") {
var arr = [];
i++;
while (i < inputstrs.length && inputstrs[i] !== "```") {
arr.push(inputstrs[i]);
i++;
}
cres = new Canvas(arr.join("\n"), null);
} else {
var ev;
try {
ev = eval(cl);
} catch (e) {
ev = undefined;
}
if (typeof ev === "number") ev = new Big(cl);
cres = ev === undefined? cl : ev;
}
inputsParsed.push(cres);
}
run(program.value, inputsParsed);
}
function updater() {
setTimeout (update, 0);
setTimeout (update, 10);
}
var menu = 0;
var inputFocused;
function update() {
var bytecount = program.value.length;
var startPos = program.selectionStart;
var endPos = program.selectionEnd;
var co = bytecount +" byte"+ (bytecount===1? "" : "s");
if (endPos !== startPos) {
co+= " ("+ (endPos-startPos) +" byte"+ (endPos-startPos===1? "" : "s") +" selected)";
if (document.activeElement === program) search.value = [...program.value.substring(startPos,endPos)].filter(c=>c.charCodeAt()>127).join("|")
}
document.getElementById("bytecount").innerHTML = co;
if (search.value !== lastSearch && typeof searched !== 'undefined') searched(search.value);
//console.log(startPos+" "+endPos);
}
function updateSaveList() {
let saves = JSON.parse(localStorage.saves);
let searched = saveName.value;
let validSaves = saves.map(c=>c[0]).filter(c=>c.includes(searched));
saveList.innerHTML = validSaves.map(c=>`<a href=# onclick="saveClicked('${c}')">${c}</a>`).join('<hr>');
return validSaves;
}
function saveClicked(name) {
if (menu === 1) saveSave(name);
else loadSave(name);
}
function loadSave(name) {
let sa = JSON.parse(localStorage.saves);
let save = sa.find(c=>c[0] === name);
if (save) {
overlay.style.display = "none";
program.focus();
program.value = save[1];
inputs.value = save[2];
if (save[3]) inputs.focus();
else program.focus();
} else {
console.warn("No save named "+name+" found");
}
menu = 0;
overlay.style.display = "none";
}
function saveSave(name) {
overlay.style.display = "none";
program.focus();
let sa = JSON.parse(localStorage.saves);
sa = sa.filter(c=>c[0] !== name);
sa.push([name, program.value, inputs.value, inputFocused]);
localStorage.saves = JSON.stringify(sa);
}
document.addEventListener ("keydown", e => {
if (e.ctrlKey && e.code === "KeyB") {
bpS = document.getElementById("program").selectionStart;
bpE = document.getElementById("program").selectionEnd;
e.preventDefault();
}
if (menu) {
if (e.key === "Escape") {
e.preventDefault();
menu = 0;
overlay.style.display = "none";
(inputFocused? inputs : program).focus();
} else if (e.key === "Enter") {
e.preventDefault();
if (menu === 1) {
saveSave(saveName.value);
} else {
loadSave(updateSaveList()[0]);
}
menu = 0;
}
} else if (e.key === 'r' && e.ctrlKey) {
e.preventDefault();
loadPermalink();
} else if (e.key === 'i' && e.ctrlKey) {
e.preventDefault();
inputs.focus();
} else if (e.key === 'p' && e.ctrlKey) {
e.preventDefault();
program.focus();
} else if (e.key === 'g' && e.ctrlKey) {
e.preventDefault();
search.focus();
} else if (e.ctrlKey && e.code === "Enter") {
e.preventDefault();
runMain();
} else if (e.key === 's' && e.ctrlKey) {
e.preventDefault();
inputFocused = +(document.activeElement === inputs);
overlay.style.display = "block";
prevFocused =
saveName.focus();
menuTitle.innerText = "Save";
menu = 1;
updateSaveList();
} else if (e.key === 'o' && e.ctrlKey) {
e.preventDefault();
inputFocused = +(document.activeElement === inputs);
overlay.style.display = "block";
saveName.value = "";
saveName.focus();
menuTitle.innerText = "Open";
menu = 2;
updateSaveList();
}
});
document.onkeydown = updater;
update();
// loading the appropriate version JS file
const JSname = latestVersion === usedVersion ? "main.js" : "old/main" + usedVersion + ".js";
let doneSteps = 0;
$.ajax({
url: JSname,
success: function (JScode) {
try {
eval("async()=>{}")
} catch(e) {
JScode = JScode.replace(/\b(async|await)\b/g, "");
console.log("Looks like async isn't supported. Removing it from the code with Regex. Programs which run indefinitely can (and should) hang the page.");
}
window.eval(JScode);
console.log("main.js loaded!");
doneSteps++;
if (doneSteps === 2 && args.includes("run")) runMain();
},
error: (e)=>console.error(e),
});
const asciiArtName = usedVersion < 2 ? "old/asciiartB2.js" : usedVersion < 3 ? "old/asciiartB3.js" : "asciiart.js";
$.ajax({
url: asciiArtName,
success: function (JScode) {
window.eval(JScode);
console.log("Canvas loaded!");
doneSteps++;
if (doneSteps === 2 && args.includes("run")) runMain();
},
error: (e)=>console.error(e),
});
function clip(str) {
const ta = document.createElement("textarea");
document.body.appendChild(ta);
ta.value = str;
ta.focus();
ta.select();
document.execCommand('copy');
ta.remove();
return str;
}
async function tests() {
let failed = 0;
// run all examples
for (let c of data) {
// console.log("Testing",c.c,[c])
let ae = c.examples || [];
if (c.types.length) {
for (let ct of c.types) ae.push(...ct.e)
}
cexample: for (let e of ae) { // test examples
console.groupEnd();
if (!e.raw || e.raw.includes("//NOTTEST")) continue;
let toEval = "["+e.raw.replace("//TEST","").replace(/¶/g, "\\n")+"]";
let outputs = [];
try {
outputs.push(eval(toEval));
} catch (e) {}
try {
outputs.push(eval(toEval.replace(/\\(?!n)/g,"\\\\")));
} catch (e) {}
outputs = outputs.filter(c=>c);
if (outputs.length === 0) {
console.error("Malfunctioned example:", toEval);
failed++;
continue;
}
let cc = new CanvasCode(e.c, []);
let out;
console.groupCollapsed(`%ctesting \`${e.c}\`; expecting`, "font-weight: normal;", outputs);
try {
out = await cc.run(0, false, false);
} catch (e) {
stop();
failed++;
console.groupEnd();
console.error("Interpreter errored:",e);
continue;
}
function rec(x) {
if (isArr(x)) return x.map(c=>rec(c));
else if (isArt(x)) return x.toString();
else if (isNum(x)) return x.doubleValue();
else return x;
}
let stack = rec(cc.stack);
for (let expected of outputs) {
let expStr = (expected.length > 1 || isArr(expected[0]))? null : expected[0]+"";
// console.log(expected,stack, equal(expected,stack));
// let expNorm = isArr(expected)? bigify(expected) : null;
try {
if (expStr!==null && out === expStr) {
console.log("pass: output");
continue cexample;
} else if (equal(stack[stack.length-1], expected[0])) {
console.log("pass: ToS");
continue cexample;
} else if (equal(stack, expected)) {
console.log("pass: stack");
continue cexample;
}
} catch (e) {
console.error("what", e);
}
}
failed++;
console.groupEnd();
console.error("got",out,stack);
}
}
console.groupEnd();
// test numbers
for (i in new Array(300).fill()) {
let r = compressNum(+i);
let cc = new CanvasCode(r, []);
let res = await cc.run(0, false, false);
console.log("testing", i, r);
if (res !== i) {
failed++;
console.error(i+" failed as "+r);
}
}
// compress strings
let strings = [
[11, "yay","1!111!1!11!111!!1"],
[11, "_--__--_-__---____-_", "__/---\\__"],
[17, "bad compression", "!"],
...new Array(145).fill().map((_, i) => ["5", "1".repeat(i+1)]),
...new Array(145).fill().map((_, i) => ["5", "-".repeat(i+1)]),
...new Array(300).fill().map(()=> [0, new Array(18).fill().map(_=>stringChars.replace("¶ŗ","")[Math.random()*(stringChars.length-2) |0]).join('')]),
];
for (let [length, ...parts] of strings) {
let compressed = compressString(parts);
console.log("testing", parts, compressed);
let cc = new CanvasCode(compressed, []);
let res = await cc.run(0, false, false);
if (length && (typeof length === 'number'? compressed.length !== length : compressed.length > +length)) console.warn("unexpected length: wanted "+length+", got "+compressed.length);
if (res !== parts.join('')) {
console.error("Compression failed!");
failed++;
}
}
if (failed) {
console.warn(failed+" tests not passed…");
} else {
console.log("Passed all tests!");
}
}
</script>
</body>
</html>