-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathvisualizer.html
606 lines (526 loc) · 14 KB
/
visualizer.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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Knitout Visualizer</title>
</head>
<style>
code.knitout {
display:block;
height:10em;
overflow:auto;
background:#eee;
border-radius:5px;
}
#dropTarget {
position:fixed;
left:0;
bottom:0;
width:100%;
height:100%;
background:#ccc;
outline:4px dashed #eee;
outline-offset:-20px;
z-index:100;
visibility:hidden;
}
#dropTarget.active {
visibility:visible;
background:#eee;
outline-color:#ccc;
}
#file {
display:none;
}
.knitoutBox {
background:yellow;
}
body {
display:flex;
flex-flow: column;
width:100vw;
height:100vh;
margin:0;
padding:0;
overflow:hidden;
}
#top {
width:100vw;
height:content-min;
margin: 4px;
display:flex;
flex-flow:row wrap;
align-items:center;
}
#bottom {
width:100vw;
flex-grow:1;
display:flex;
flex-flow: row;
}
#visualizer {
width:50vw;
position:relative;
}
#show {
width: 100%;
height: 100%;
position:absolute;
}
#editor {
flex-grow:1;
flex-basis:20vw;
display:flex;
flex-flow: column;
}
#editor-text {
width:100%;
flex-grow:1;
}
button, #fileLabel {
box-sizing: border-box;
cursor:pointer;
background-color: #8FCF96;
padding: 4px 8px;
margin: 0 2px;
box-shadow: 0 0 2px 0 rgba(0,0,0,0.2);
text-decoration: none;
font-family: serif;
font-size: 16px;
line-height: 1;
border-style: solid;
border-width: 2px;
border-color: #8FCF96;
}
button:hover, #fileLabel:hover {
background-color: #CBF3AB;
border-style: solid;
border-width: 2px;
border-color: #8FCF96;
}
button:active, #fileLabel:active {
background-color: #CBF3ff;
}
#top span {
display:block;
margin: 0 8px 0 2px;
padding: 0;
}
#top .infoLink {
flex-grow:1;
text-align:right
}
#top .infoLink + .infoLink {
flex-grow:0;
}
.infoLink {
color:#888;
}
.infoLink a {
color:#666;
}
.infoLink a:hover {
color:#444;
}
.highlight {
background-color: #ffeeb7;
}
#codeWrapper {
flex-grow:1;
flex-basis:20vw;
max-width:30em;
display:block;
margin:0;
position:relative;
}
#code1 {
position: absolute;
width:100%; height:100%;
box-sizing: border-box;
margin: 0;
padding: 0;
background-color: #f3f3f3;
overflow: scroll;
display:flex;
flex-flow: column;
}
.lineNumber {
color: #888;
width: 2.5em;
display: inline-block;
text-align: right;
margin-right: 1em;
}
.line {
display: inline-block;
padding: 0.2em 2em 0.2em 0.5em;
width: 100%;
box-sizing: border-box;
}
</style>
<body>
<div id="top">
<input id="file" type="file" />
<label id="fileLabel" for="file"><span>Load a knitout or js file</span></label>
<span id="fileName">(no file loaded)</span>
<button id="reload">Reload</button>
<button id="compile">Run/Show</button>
<button id="save" onclick="saveKnitout();">Save Knitout</button>
<button id="save" onclick="saveJavascript();">Save Javascript</button>
<label for="showKnitout"><input type="checkbox" name="showKnitout" id="showKnitout" onchange="toggleKnitout()">Show Knitout</label>
<span class="infoLink"><a href="https://github.com/textiles-lab/knitout-live-visualizer" target="_blank">github page</a>;</span>
<span class="infoLink"><a href="https://github.com/textiles-lab/knitout-live-visualizer/issues" target="_blank">report a bug</a></span>
</div>
<div id="bottom">
<div id="editor">
<div id="editor-text">
//import the knitout writer code and instantiate it as an object
const knitout = require('knitout');
k = new knitout.Writer({carriers:['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']});
// add some headers relevant to this job
k.addHeader('Machine','SWGXYZ');
k.addHeader('Gauge','15');
const Carrier = '7';
k.inhook(Carrier);
for(var i=3;i>=0;i -= 2){
k.tuck("-","f"+i,Carrier);
}
for(var i=0;i<=3;i += 2){
k.tuck("+","f"+i,Carrier);
}
for(var i=3;i>=0;i--){
k.knit("-","f"+i,Carrier);
}
k.xfer("f0","b0");
k.xfer("f1","bs1");
k.xfer("f2","b2");
k.xfer("f3","bs3");
k.xfer("b0","fs0");
k.xfer("bs1","f1");
k.xfer("b2","fs2");
k.xfer("bs3","f3");
k.xfer("fs0", "b0");
k.xfer("fs2", "b2");
for(var i=0;i<2;i++){
k.knit("+","b0",Carrier);
k.knit("+","b2",Carrier);
k.knit("-","f3",Carrier);
k.knit("-","f1",Carrier);
}
k.outhook(Carrier);
k.write('wristband.k');
</div>
</div>
<pre id="codeWrapper" style="display:none;">
<code id="code1">
</code>
</pre>
<div id="visualizer">
<canvas class="ShowKnitout" id="show"></canvas>
</div>
<button id="resetZoom" style="position: absolute; bottom: 0em; right: 0em;">Reset Zoom</button>
</div>
<div id="dropTarget"></div>
<script src="parseKnitout.js"></script>
<script src="CellMachine.js"></script>
<script src="VectorTilesLib.js"></script>
<script src="VectorTiles.js"></script>
<script src="evalJS.js"></script>
<script src="show-knitout.js"></script>
<script src="./ace-builds/src-noconflict/ace.js" type="text/javascript" charset="utf-8"></script>
<script>
let editor = ace.edit("editor-text");
//themes are available here: https://github.com/ajaxorg/ace/tree/master/lib/ace/theme
editor.setTheme("ace/theme/tomorrow");
editor.session.setMode("ace/mode/javascript");
var show = document.getElementById('show');
window.addEventListener('resize', function(){
show.showKnitout.requestDraw();
});
show.showKnitout.clickLine = function(source) {
console.log("Jump to: " + source);
let line = parseInt(source);
editor.gotoLine(line);
};
editor.selection.addEventListener('changeCursor',function(){
let cursor = editor.selection.getCursor();
let range = editor.selection.getRange();
const start = range.start.row + 1;
const end = range.end.row + 1;
show.showKnitout.setHighlightFn(function(source){
let line = parseInt(source);
if (line >= start && line <= end) {
return true;
} else {
return false;
}
});
});
let oldHoveredRow = NaN;
show.showKnitout.onHoverSource = function(source) {
if (oldHoveredRow === oldHoveredRow) {
editor.session.removeGutterDecoration(oldHoveredRow-1, "knitoutBox");
}
let line = parseInt(source);
oldHoveredRow = line;
if (line === line) {
editor.session.addGutterDecoration(oldHoveredRow-1, "knitoutBox");
}
};
show.showKnitout.onDoubleClickSource = function(source) {
//console.log("onDoubleClick '" + source + "'"); //DEBUG
let line = parseInt(source);
if (line === line) {
//console.log("Should scroll to " + line);
editor.scrollToLine(line-1, true, true, () => {});
}
};
document.getElementById("resetZoom").onclick = function (evt) {
show.showKnitout.resetZoom();
}
let knitout;
function updateVisualizer(centerView) {
updateKnitoutMode();
let code = editor.getValue();
if (isKnitout()) {
//mark up code with line numbers:
knitout = '';
code.split('\n').forEach(function(line, lineNumber){
knitout += line;
if (line.indexOf(';') === -1) {
knitout += ';!source:' + (lineNumber+1);
}
knitout += '\n';
});
} else {
knitout = evalJS(code);
}
//console.log(knitout);
show.showKnitout.parse(knitout, false, centerView);
}
//Timing code:
if (false) {
function TimingMachine() {
this.count = 0;
this.ignored = 0;
}
function countOp() { this.count += 1; }
function ignoreOp() { this.ignored += 1; }
["in","out","inhook","releasehook","outhook","stitch","rack","pause","x-stitch-number"].forEach(function(op) {
TimingMachine.prototype[op] = ignoreOp;
});
["knit","tuck","split","miss"].forEach(function(op) {
TimingMachine.prototype[op] = countOp;
});
TimingMachine.prototype.setCarriers = function() { }
TimingMachine.prototype.stretchLoops = function() { }
const oldUpdateVisualizer = updateVisualizer;
updateVisualizer = function timeUpdateVisualizer(centerView) {
const TIMING_ITERS = 100;
//time code generation:
let codeParse = {
min:Infinity,
total:0.0,
boxInstructions:NaN,
otherInstructions:NaN
};
(() => {
for (let iter = 0; iter < TIMING_ITERS; ++iter) {
let before = performance.now();
updateKnitoutMode();
let code = editor.getValue();
if (isKnitout()) {
//mark up code with line numbers:
knitout = '';
code.split('\n').forEach(function(line, lineNumber){
knitout += line;
if (line.indexOf(';') === -1) {
knitout += ';!source:' + (lineNumber+1);
}
knitout += '\n';
});
} else {
knitout = evalJS(code);
}
const tm = new TimingMachine();
parseKnitout(knitout, tm, false);
let after = performance.now();
codeParse.min = Math.min(codeParse.min, after - before);
codeParse.total += (after - before);
if (codeParse.boxInstructions === codeParse.boxInstructions) {
console.assert(tm.count === codeParse.boxInstructions);
console.assert(tm.ignored === codeParse.otherInstructions);
}
codeParse.boxInstructions = tm.count;
codeParse.otherInstructions = tm.ignored;
}
})();
//time visualization overall:
(() => {
let min = Infinity;
let total = 0.0;
for (let iter = 0; iter < TIMING_ITERS; ++iter) {
let before = performance.now();
oldUpdateVisualizer(centerView);
let after = performance.now();
min = Math.min(min, after - before);
total += (after - before);
}
console.log("Had " + codeParse.boxInstructions + " box-generating instructions and " + codeParse.otherInstructions + " other instructions; user code + parse took " + codeParse.min + " ms min / " + codeParse.total / TIMING_ITERS + " ms avg over " + TIMING_ITERS + " runs.");
console.log("Update took " + min + " ms min, " + (total / TIMING_ITERS) + " ms avg over " + TIMING_ITERS + " iterations.");
console.log(" User/source: " + codeParse.min + " ms min ; vis: " + (min - codeParse.min) + " ms min; vis/ins: " + (min - codeParse.min) / codeParse.boxInstructions + " ms / instruction min.");
//codeParse.total / TIMING_ITERS + " ms avg over " + TIMING_ITERS + " runs.");
//console.log("Update took " + min + " ms min, " + (total / TIMING_ITERS) + " ms avg over " + TIMING_ITERS + " iterations.");
})();
};
}
updateVisualizer(true);
let compile = document.getElementById("compile");
compile.addEventListener('click', function() { updateVisualizer(false); } );
let reload = document.getElementById("reload");
let currentSource = null; //{file:file} or {url:url} or null
reload.addEventListener('click', function() {
if (currentSource) {
if (currentSource.file) {
readFile(currentSource.file);
} else if (currentSource.url) {
readURL(currentSource.url);
}
}
});
function setSource(source, text) {
const sameFile = JSON.stringify(currentSource) === JSON.stringify(currentSource);
currentSource = source;
const name = (source.file ? source.file.name : source.url);
document.getElementById('fileName').innerText = name;
console.log("read " + name);
let oldText = text;
//line ending conversion:
text = text.replace(/\r\n/g,"\n");
if (oldText != text) {
console.warn("Converted dos-style line endings to unix-style.")
}
editor.setValue(text, -1);
updateVisualizer(!sameFile);
}
function readURL(url) {
console.log("Attempting to read url: '" + url + "'");
let request = new XMLHttpRequest();
request.addEventListener('load', () => {
setSource({url:url}, request.responseText);
});
request.open('GET', url);
request.send();
}
function readFile(file) {
console.log("Attempting to read file: '" + file.name + "'");
//generate new data:
var reader = new FileReader();
reader.onload = () => {
setSource({file:file}, reader.result);
};
console.log("reading " + file.name);
reader.readAsText(file);
}
function isKnitout() {
const line = editor.getSession().getLine(0);
return /^;!knitout-\d+/.test(line);
}
function updateKnitoutMode() {
if (isKnitout()) {
//knitout!
editor.getSession().setMode("ace/mode/plain_text");
} else {
//javascript!
editor.getSession().setMode("ace/mode/javascript");
}
}
editor.getSession().on('change', updateKnitoutMode);
/*
var dropTarget = document.getElementById("dropTarget");
//dragging into the window also loads files:
dropTarget.addEventListener('dragover', function(evt){
dropTarget.classList.add("active");
evt.preventDefault();
return false;
});
dropTarget.addEventListener('dragleave', function(evt){
dropTarget.classList.remove("active");
evt.preventDefault();
return false;
});
dropTarget.addEventListener('drop', function(evt){
dropTarget.classList.remove("active");
try {
readFile(evt.dataTransfer.files[0]);
} catch (e) {
console.log(e);
}
evt.preventDefault();
return false;
});
//dragging into the window shows the target:
document.addEventListener('dragover', function(evt){
dropTarget.classList.add("active");
evt.preventDefault();
return false;
});
*/
const code = document.getElementById("code1");
const codeWrapper = document.getElementById("codeWrapper");
const knitoutCheckbox = document.getElementById("showKnitout");
function toggleKnitout() {
if (knitoutCheckbox.checked) {
codeWrapper.style.display = '';
} else {
codeWrapper.style.display = 'none';
}
}
toggleKnitout();
function saveKnitout() {
// Remove source line comments
let commentFreeKnitout = "";
let lines = knitout.split("\n");
for (let i = 0; i < lines.length; ++i) {
let sourceCommentIndex = lines[i].indexOf(";!source:");
if (sourceCommentIndex >= 0) {
lines[i] = lines[i].substring(0, sourceCommentIndex);
}
commentFreeKnitout += lines[i] + "\n";
}
fileSave(commentFreeKnitout, "knitoutFile.k");
}
function saveJavascript(){
fileSave(editor.getValue(), "knitoutFile.js");
}
function fileSave(sourceText, fileIdentity) {
var workElement = document.createElement("a");
if ('download' in workElement) {
workElement.href = "data:" + 'text/plain' + "charset=utf-8," + escape(sourceText);
workElement.setAttribute("download", fileIdentity);
document.body.appendChild(workElement);
var eventMouse = document.createEvent("MouseEvents");
eventMouse.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
workElement.dispatchEvent(eventMouse);
document.body.removeChild(workElement);
} else throw 'File saving not supported for this browser';
}
var file = document.getElementById("file");
file.addEventListener('change', function(evt){
try {
readFile(file.files[0]);
file.value = "";
} catch (e) {
console.log(e);
}
evt.preventDefault();
return false;
});
{ //check for '?load=....' in the URL:
const m = document.location.search.match(/^\?load=(.+)$/);
if (m) {
readURL(m[1]);
}
}
</script>
</body>