-
Notifications
You must be signed in to change notification settings - Fork 2
/
mightyThingsEncoder.js
495 lines (412 loc) · 18.1 KB
/
mightyThingsEncoder.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
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
class ChuteVisualizer {
constructor(containerSelector) {
this.container = d3.select(containerSelector);
this.svg = this.container.append("svg");
this.radialContainer = this.svg.append("g");
this.parachute = this.radialContainer.append("g");
this.explanatory = this.radialContainer.append("g");
this.roundedEdgeProportion = 1/12; // proportion of radius to treat as radius for curved arc edges
this.margin = 2;
// inner and outer radius of each ring as a proportion of the total radius
this.ringProportions = [[0.09, 0.37], [0.37, 0.63], [0.63, 0.84], [0.92, 1]];
// not doing this in CSS so it's a legit exportable SVG
this.colors = {
dataTrue: this.container.style("--dataTrue"),
dataFalse: this.container.style("--dataFalse"),
preWordPadding: this.container.style("--preWordPadding"),
interBytePadding: this.container.style("--interBytePadding"),
postWordPadding: this.container.style("--postWordPadding"),
postDataPadding: this.container.style("--postDataPadding")
};
this.angle = d3.scaleLinear()
.range([0, 2 * Math.PI]);
this.size();
this.windowWidth = 0;
this.windowHeight = 0;
d3.select(window).on("resize.vis", () => {
// there's a mobile safari bug that fires resize events when scrolling,
// so manually track the window size. https://stackoverflow.com/a/29940941
const newWidth = document.documentElement.clientWidth;
const newHeight = document.documentElement.clientHeight
if(this.windowWidth !== newWidth || this.windowHeight != newHeight) {
// catching a special case for rotating devices that have width 768.
// gotta run it twice. kinda janky, but here we are. I think it
// has to do with scrollbars.
if(newWidth <= 768 && this.windowWidth > 768 || newWidth == 768) {
this.size();
this.update();
}
this.size();
this.update();
}
});
}
updateData() {
this.data = encoder.encodeAll(strings);
this.update();
}
update() {
this.angle
.domain([0, this.data[0].length]); // in case the number of bits changed (although there's no UI for that)
const rings = this.parachute.selectAll("g.ring").data(this.data);
rings.join("g")
.attr("class", "ring")
.each((rowData, rowIndex, rowG) => {
const row = d3.select(rowG[rowIndex]);
let bits = row.selectAll("g.bit").data(d => d);
const bitsEnter = bits.enter().append("g").attr("class", "bit");
bitsEnter.append("path").attr("class", "bitPath");
bits = bits.merge(bitsEnter);
bits.select("path.bitPath")
.attr("d", (b, bitIndex) => this.makePath(bitIndex, rowIndex))
.attr("stroke", d => {
const normalColor = "#111111";
// const nonDataColor = "none";
if(explain) {
if(d.role == "data") {
return normalColor;
}
else {
return this.colors[d.role];
}
}
else {
return normalColor;
}
})
.attr("stroke-width", this.radius/600)
.attr("stroke-linejoin", "round")
.attr("fill", d => {
if(explain) {
if(d.role == "data") {
return d.value ? this.colors.dataTrue : this.colors.dataFalse;
}
else {
return this.colors[d.role];
}
}
else {
return d.value ? this.colors.dataTrue : this.colors.dataFalse;
}
});
});
const explanatoryRings = this.explanatory.selectAll("g.ring").data(this.data);
explanatoryRings.join("g").attr("class", "ring").each((rowData, rowIndex, rowG) => {
const row = d3.select(rowG[rowIndex]);
let bits = row.selectAll("g.bit").data(d => d);
const bitsEnter = bits.enter().append("g").attr("class", "bit");
bitsEnter.append("text").attr("class", "token");
bits = bits.merge(bitsEnter);
bits.select("text.token")
.text(d => d.bit === 3 && explain ? d.token : "")
.attr("font-family", "Helvetica, sans-serif")
.attr("font-weight", "bold")
.attr("font-size", this.radius/8)
.attr("stroke", "#FFFFFF")
.attr("stroke-width", this.radius/200)
.attr("x", (d, bitIndex) => this.center(bitIndex, rowIndex)[0])
.attr("y", (d, bitIndex) => this.center(bitIndex, rowIndex)[1])
.attr("dx", (d, i, n) => -n[i].getBBox().width/2)
.attr("dy", this.radius/8 * .4);
});
}
makePath(bitIndex, rowIndex) {
// whether or not the inner and outer edges of the rings have angled stitching
const stitched = [[false, true], [true, true], [true, false], [false, false]];
const stitchDepth = 0.04; // proportion of radius
const innerRadius = this.radius * this.ringProportions[rowIndex][0];
const outerRadius = this.radius * this.ringProportions[rowIndex][1];
// arbitrary decision: the inner edge of the stitching is on the
// innerRadius, and the outer edge pokes outside of it.
// odd bits stitch outward going clockwise.
const startAngle = this.angle(bitIndex);
const endAngle = this.angle(bitIndex + 1);
// define the four corner points as [angle, radius]
const corners = [];
if(bitIndex % 2 == 0) {
corners[0] = [startAngle, innerRadius];
corners[1] = [startAngle, outerRadius];
if(stitched[rowIndex][1]) {
corners[2] = [endAngle, outerRadius + this.radius * stitchDepth];
}
else {
corners[2] = [endAngle, outerRadius];
}
if(stitched[rowIndex][0]) {
corners[3] = [endAngle, innerRadius + this.radius * stitchDepth];
}
else {
corners[3] = [endAngle, innerRadius];
}
}
else {
if(stitched[rowIndex][0]) {
corners[0] = [startAngle, innerRadius + this.radius * stitchDepth];
}
else {
corners[0] = [startAngle, innerRadius];
}
if(stitched[rowIndex][1]) {
corners[1] = [startAngle, outerRadius + this.radius * stitchDepth];
}
else {
corners[1] = [startAngle, outerRadius];
}
corners[2] = [endAngle, outerRadius];
corners[3] = [endAngle, innerRadius];
}
const cartesianCorners = corners.map(c => d3.pointRadial(...c));
let pathData = `M ${cartesianCorners[0].join(" ")}
L ${cartesianCorners[1].join(" ")}`;
if(stitched[rowIndex][1]) {
pathData += `L ${cartesianCorners[2].join(" ")}`;
}
else {
pathData += `A ${outerRadius * this.roundedEdgeProportion} ${outerRadius * this.roundedEdgeProportion} 0 0 1 ${cartesianCorners[2].join(" ")}`;
}
pathData += `L ${cartesianCorners[3]}`;
if(stitched[rowIndex][0]) {
pathData += "Z";
}
else {
pathData += `A ${innerRadius * this.roundedEdgeProportion} ${innerRadius * this.roundedEdgeProportion} 0 0 0 ${cartesianCorners[0].join(" ")}`;
}
return pathData;
}
center(bitIndex, rowIndex) {
const startAngle = this.angle(bitIndex);
const endAngle = this.angle(bitIndex + 1);
const avgAngle = (startAngle + endAngle)/2;
const innerRadius = this.radius * this.ringProportions[rowIndex][0];
const outerRadius = this.radius * this.ringProportions[rowIndex][1];
const avgRadius = (innerRadius + outerRadius)/2;
return d3.pointRadial(avgAngle, avgRadius);
}
size() {
this.svg.attr("width", 0);
const containerContainerStyle = getComputedStyle(this.container.node());
const availableWidth = parseFloat(containerContainerStyle.getPropertyValue("width"))
- parseFloat(containerContainerStyle.getPropertyValue("padding-left"))
- parseFloat(containerContainerStyle.getPropertyValue("padding-right"));
this.windowWidth = document.documentElement.clientWidth;
this.windowHeight = document.documentElement.clientHeight;
const availableHeight = this.windowHeight - 20;
this.outerRadius = Math.min(availableWidth, availableHeight)/2;
this.radius = this.outerRadius - (this.outerRadius * this.roundedEdgeProportion/2) - this.margin;
this.svg
.attr("width", 2 * this.outerRadius)
.attr("height", 2 * this.outerRadius);
this.radialContainer
.attr("transform", `translate(${this.outerRadius}, ${this.outerRadius})`);
}
}
class UIControls {
constructor(containerSelector) {
this.container = d3.select(containerSelector);
this.textboxNames = ["Inner ring", "Ring 2", "Ring 3", "Outer ring"];
this.container.html(`<div class="textboxContainer"></div>
<div class="form-check"><label><input id="explainToggle" type="checkbox" class="form-check-input"> Explain</label></div>`);
this.legend = d3.select("#legend");
this.explainCheckbox = this.container.select("#explainToggle")
.on("change", e => {
const checked = e.currentTarget.checked;
explain = checked;
this.update();
vis.size(); // presence of scrollbar may change
vis.update();
});
this.textboxContainer = this.container.select(".textboxContainer");
this.downloadButton = d3.select("#downloadButtonContainer").append("button")
.attr("class", "btn btn-primary")
.attr("id", "downloadButton")
.text("Download")
.on("click", () => {
saveSvgAsPng(vis.svg.node(), "chute.png", { scale: 2 });
});
}
update() {
this.explainCheckbox.property("checked", explain);
this.legend.style("display", explain ? null : "none");
let textboxes = this.textboxContainer.selectAll("div.textbox").data(strings);
const textboxesEnter = textboxes.enter().append("div").attr("class", "textbox")
.html((d, i) => `<div class="mb-3">
<label for="textbox${i}" class="form-label">${this.textboxNames[i]}</label>
<input class="form-control" id="textbox${i}" placeholder="${strings[i]}" data-index="${i}">
<div class="invalid-feedback"></div>
</div>`);
textboxesEnter.select("input").on("input", (e, d) => {
let newString = e.currentTarget.value.toUpperCase();
e.currentTarget.value = newString; // capitalize even if invalid
let valid = true;
try {
encoder.tokenize(newString);
}
catch(er) {
valid = false;
d3.select(e.currentTarget.parentNode).select(".invalid-feedback")
.text(er)
.style("display", "block");
}
d3.select(e.currentTarget).classed("is-invalid", !valid);
if(valid) {
strings[e.currentTarget.dataset.index] = newString;
d3.select(e.currentTarget.parentNode).select(".invalid-feedback")
.style("display", null);
this.update();
vis.updateData();
}
});
textboxes = textboxes.merge(textboxesEnter);
textboxes.select("input")
.property("value", d => d);
}
}
class MightyThingsEncoder {
constructor() {
this.totalBits = 80;
this.byteSize = 7;
this.interByteGap = 3;
this.interByteVal = false;
this.padVal = true;
this.letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
this.inputString = "";
this.outputStrings = "";
}
tokenize(inputString) {
// turn each string into an array of characters or numbers, ignoring
// spaces. if a number is < 128, return a number; otherwise characters.
if(inputString !== undefined) this.inputString = inputString;
const words = this.inputString.split(" ");
const charArray = words.map(w => {
return w.split(/(\d+)|(\D+)/g)
.filter(d => d !== "" && d !== undefined)
.map(d => {
if(!isNaN(parseInt(d))) {
const num = parseInt(d);
if(num < 128) {
return num;
}
else {
throw "Numbers must be between 0 and 127";
}
}
else {
const letters = d.split("");
letters.forEach(l => {
if(this.letters.indexOf(l) + 1 < 1) {
throw "Letters must be capital letters A–Z.";
}
});
return letters;
}
});
});
const tokens = charArray.flat(2);
if(tokens.length > 8) {
throw "A ring can’t hold that much data";
}
else {
this.tokens = tokens;
}
return tokens;
}
binEncoder(token) {
let numVal;
if(typeof(token) == "string") {
numVal = this.letters.indexOf(token) + 1;
}
else {
numVal = token;
}
const binVal = numVal.toString(2).split("");
while(binVal.length < this.byteSize) {
binVal.splice(0, 0, "0");
}
return binVal.join("");
}
encode(inputString) {
if(inputString !== undefined) {
this.inputString = inputString;
}
this.tokenize(this.inputString);
return this.tokens.map(t => this.binEncoder(t));
}
encodePadded(row, inputString) {
if(inputString !== undefined) {
this.inputString = inputString;
}
let encoded = this.encode(this.inputString);
encoded = encoded.map((encodedToken, byteIndex) => {
return encodedToken.split("").map((bit, bitIndex) => {
return {
byte: byteIndex,
bit: bitIndex,
role: "data",
token: this.tokens[byteIndex],
value: bit === "1"
}
});
});
// pad between each byte
for(let i = 1; encoded.length < 2 * encoder.tokens.length - 1; i += 2) {
encoded.splice(i, 0, Array(this.interByteGap).fill({
role: "interBytePadding",
value: this.interByteVal
}));
}
// pad before all bytes
if(this.tokens.length > 0) {
encoded.unshift(Array(this.interByteGap).fill({
role: "preWordPadding",
value: this.interByteVal
}));
}
// pad after all bytes (if there's room)
if(this.tokens.length < 8 && this.tokens.length > 0) {
encoded.push(Array(this.interByteGap).fill({
role: "postWordPadding",
value: this.interByteVal
}));
}
encoded = encoded.flat();
// pad the end until there are 80 bits
const unpaddedLength = encoded.length;
this.remainingBits = this.totalBits - unpaddedLength;
encoded.push(...Array(this.remainingBits).fill({
role: "postDataPadding",
value: this.padVal
}));
if(row === 0) {
this.startBit = 1;
}
encoded = encoded.map((v, i, ar) => {
let shiftedIndex = (i - this.startBit) % ar.length;
shiftedIndex += shiftedIndex < 0 ? ar.length : 0;
return ar[shiftedIndex];
});
// set up next start bit
if(unpaddedLength > 0) {
this.startBit = (this.startBit + (this.totalBits - this.remainingBits) - (unpaddedLength == this.totalBits ? 0: this.interByteGap)) % this.totalBits;
}
return encoded;
}
encodeAll(stringArray) {
this.allOutArray = [];
stringArray.forEach((s, i) => {
const encoded = this.encodePadded(i, s);
this.allOutArray[i] = encoded;
});
return this.allOutArray;
}
}
const encoder = new MightyThingsEncoder();
const vis = new ChuteVisualizer("#chuteContainer");
const ui = new UIControls("#uiControls");
const strings = ["DARE", "MIGHTY", "THINGS", "34 11 58 N 118 10 31 W"];
let explain = false;
function init() {
ui.update();
vis.size();
vis.updateData();
}
init();