-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
467 lines (414 loc) · 13.5 KB
/
Copy pathscript.js
File metadata and controls
467 lines (414 loc) · 13.5 KB
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
const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // abcdefghijklmnopqrstuvwxyz
const frequencies = [
0.082, 0.015, 0.028, 0.043, 0.127, 0.022, 0.02, 0.061, 0.07, 0.0015, 0.0077,
0.04, 0.024, 0.067, 0.075, 0.019, 0.00095, 0.06, 0.063, 0.091, 0.028,
0.0098, 0.024, 0.0015, 0.02, 0.00074,
]; // Taken from https://en.wikipedia.org/wiki/Letter_frequency
const charFrequencies = frequencies
.map((f, i) => [letters[i], f])
.sort(([, f1], [, f2]) => f2 - f1);
let substitutions = Array(letters.length).fill("?");
const history = {
rootNode: { value: substitutions.slice(), children: [] },
};
history.current = history.rootNode;
let hoverElement;
const letterInputs = Array(letters.length);
function init() {
createCiphertextInput();
createLetterContainer();
createHoverElement();
registerListeners();
update();
}
function createCiphertextInput() {
const ciphertextContainer = document.getElementById("ciphertextTable");
const sampleRow = document.createElement("tr");
const inputCell = document.createElement("td");
const textareaInput = document.createElement("textarea");
textareaInput.className = "textareaInput";
textareaInput.placeholder = "Enter ciphertext sample";
textareaInput.onbeforeinput = (e) => {
if (
!textareaInput.value &&
e.data !== null &&
ciphertextContainer.lastChild === sampleRow
) {
createCiphertextInput();
}
};
textareaInput.oninput = update;
textareaInput.onblur = () => {
if (
!textareaInput.value &&
ciphertextContainer.children.length > 1 &&
ciphertextContainer.lastChild !== sampleRow
) {
ciphertextContainer.removeChild(sampleRow);
}
};
new ResizeObserver(() => {
textareaOutput.style.height = textareaInput.offsetHeight + "px";
}).observe(textareaInput);
inputCell.appendChild(textareaInput);
const outputCell = document.createElement("td");
const textareaOutput = document.createElement("textarea");
textareaOutput.className = "textareaOutput";
textareaOutput.disabled = true;
outputCell.appendChild(textareaOutput);
sampleRow.append(inputCell, outputCell);
ciphertextContainer.appendChild(sampleRow);
}
function createLetterContainer() {
const letterContainer = document.getElementById("letterContainer");
for (let i = 0; i < letters.length; i++) {
letterContainer.appendChild(createLetterBox(i));
}
}
function createLetterBox(index) {
const letterBox = document.createElement("label");
letterBox.className = "letterbox";
const content = document.createElement("div");
content.className = "letterboxContent";
const input = document.createElement("input");
input.className = "letterboxInput";
input.type = "text";
input.onbeforeinput = (e) => {
e.preventDefault();
if (e.data === null) {
if (
e.inputType === "deleteContentForward" ||
e.inputType === "deleteContentBackward"
) {
substitutions[index] = "?";
update();
}
return;
}
const chars = e.data.trim().toUpperCase();
const c = chars.charAt(chars.length - 1);
if (c !== "?" && !letters.includes(c)) {
return;
}
substitutions[index] = c;
update();
};
input.value = substitutions[index];
letterInputs[index] = input;
content.appendChild(input);
letterBox.append(letters[index], content);
return letterBox;
}
function createHoverElement() {
hoverElement = document.createElement("div");
hoverElement.className = "absolute";
document.getElementById("hoverContainer").appendChild(hoverElement);
}
function registerListeners() {
window.addEventListener("resize", update);
document.getElementById("suggUsedCipherCbx").onchange = update;
document.getElementById("suggUsedClearCbx").onchange = update;
const canvas = document.getElementById("historyCanvas");
canvas.addEventListener("mousemove", function (e) {
var rect = canvas.getBoundingClientRect();
mouseX = e.clientX - rect.left;
mouseY = e.clientY - rect.top;
const handled = handleMouse(
history.rootNode,
20,
canvas.height / 2,
canvas.height - 20,
mouseX,
mouseY,
false
);
if (!handled) {
hoverElement.hidden = true;
}
});
canvas.addEventListener("click", function (e) {
var rect = canvas.getBoundingClientRect();
mouseX = e.clientX - rect.left;
mouseY = e.clientY - rect.top;
handleMouse(
history.rootNode,
20,
canvas.height / 2,
canvas.height - 20,
mouseX,
mouseY,
true
);
});
}
function update() {
updateLetterContainer();
updateTranslations();
updateFrequencyAnalysis();
updateHistory();
drawHistory();
}
function updateLetterContainer() {
for (let i = 0; i < letters.length; i++) {
letterInputs[i].value = substitutions[i];
letterInputs[i].classList.remove("invalid");
}
for (let i = 0; i < letters.length; i++) {
for (let j = i + 1; j < letters.length; j++) {
if (
substitutions[i] === substitutions[j] &&
substitutions[i] !== "?"
) {
letterInputs[i].classList.add("invalid");
letterInputs[j].classList.add("invalid");
}
}
}
}
function updateTranslations() {
const ciphertextTable = document.getElementById("ciphertextTable");
for (const row of ciphertextTable.rows) {
row.cells[1].lastChild.value = cipherToClear(
row.cells[0].lastChild.value
);
}
}
function cipherToClear(cipher) {
let clear = "";
for (const char of cipher) {
const upChar = char.toUpperCase();
if (letters.includes(upChar)) {
const sub = substitutions[letters.indexOf(upChar)];
clear += char === upChar ? sub : sub.toLowerCase();
} else {
clear += char;
}
}
return clear;
}
function updateFrequencyAnalysis() {
const freqAnalTable = document.getElementById("freqAnalTableBody");
const ciphertextTable = document.getElementById("ciphertextTable");
const counts = new Array(letters.length).fill(0);
for (const row of ciphertextTable.rows) {
for (const char of row.cells[0].lastChild.value) {
counts[letters.indexOf(char.toUpperCase())]++; // all relevant functions ignore the NaN at -1
}
}
const sum = counts.reduce((prev, cur) => prev + cur);
if (sum === 0) {
freqAnalTable.innerHTML = "<tr><td colspan=5>No data</td></tr>";
return;
}
let charCounts = counts
.map((c, i) => [letters[i], c])
.filter(([, count]) => count !== 0)
.sort(([, c1], [, c2]) => c2 - c1);
if (!document.getElementById("suggUsedCipherCbx").checked) {
charCounts = charCounts.filter(
([char]) => substitutions[letters.indexOf(char)] === "?"
);
}
let relevantCharFrequencies = charFrequencies;
if (!document.getElementById("suggUsedClearCbx").checked) {
relevantCharFrequencies = charFrequencies.filter(
([char]) => !substitutions.includes(char)
);
}
freqAnalTable.innerHTML = "";
const numAvailableSuggestions =
charCounts.length < relevantCharFrequencies.length
? charCounts.length
: relevantCharFrequencies.length;
for (let i = 0; i < numAvailableSuggestions; i++) {
[cipherChar, cipherCount] = charCounts[i];
[suggClearChar, suggClearFreq] = relevantCharFrequencies[i];
if (substitutions[letters.indexOf(cipherChar)] === suggClearChar) {
continue;
}
const row = document.createElement("tr");
const cipherCharCell = document.createElement("td");
cipherCharCell.textContent = cipherChar;
const cipherFreqCell = document.createElement("td");
cipherFreqCell.textContent = formatFractionAsPercent(cipherCount / sum);
const suggClearCharCell = document.createElement("td");
suggClearCharCell.textContent = suggClearChar;
const suggClearFreqCell = document.createElement("td");
suggClearFreqCell.textContent = formatFractionAsPercent(suggClearFreq);
const acceptCell = document.createElement("td");
const acceptButton = document.createElement("button");
acceptButton.textContent = "\u2713";
acceptButton.onclick = createAcceptHandler(cipherChar, suggClearChar);
acceptCell.appendChild(acceptButton);
row.append(
cipherCharCell,
cipherFreqCell,
suggClearCharCell,
suggClearFreqCell,
acceptCell
);
freqAnalTable.appendChild(row);
}
if (freqAnalTable.innerHTML === "") {
freqAnalTable.innerHTML =
"<tr><td colspan=5>No suggestions available</td></tr>";
}
}
function formatFractionAsPercent(num) {
return (100 * num).toFixed(2) + "%";
}
function createAcceptHandler(cipher, clear) {
return () => {
substitutions[letters.indexOf(cipher)] = clear;
update();
};
}
function updateHistory() {
const contained = treeFind(history.rootNode, substitutions);
if (contained) {
history.current = contained;
return;
}
const newCurrent = {
value: substitutions.slice(),
children: [],
};
history.current.children.push(newCurrent);
history.current = newCurrent;
}
function treeFind(node, value) {
if (arrayEquals(node.value, value)) {
return node;
}
for (let child of node.children) {
const found = treeFind(child, value);
if (found) {
return found;
}
}
return undefined;
}
function arrayEquals(a1, a2) {
if (!a1 || !a2 || a1.length !== a2.length) {
return false;
}
for (let i = 0; i < a1.length; i++) {
if (a1[i] !== a2[i]) {
return false;
}
}
return true;
}
function drawHistory() {
const minCanvasHeight = 200;
const canvas = document.getElementById("historyCanvas");
const canvasContext = canvas.getContext("2d");
const requiredHeight = 2 * 10 * requiredTreeWidth(history.rootNode);
canvas.height = Math.max(requiredHeight, minCanvasHeight);
const requiredWidth = 20 + 30 * treeHeight(history.rootNode);
// Subtract 2 from the body width to account for canvas border
canvas.width = Math.max(requiredWidth, document.body.clientWidth - 2);
canvasContext.fillStyle = "white";
canvasContext.fillRect(0, 0, canvas.height, canvas.width);
canvasContext.fillStyle = "black";
drawTree(
canvasContext,
history.rootNode,
20,
canvas.height / 2,
canvas.height - 20,
-1,
-1
);
}
function requiredTreeWidth(node) {
if (node.children.length === 0) {
return 1;
}
let max = 0;
for (let child of node.children) {
max = Math.max(max, requiredTreeWidth(child));
}
return max * node.children.length;
}
function treeHeight(node) {
if (node.children.length === 0) {
return 1;
}
let max = 0;
for (let child of node.children) {
max = Math.max(max, treeHeight(child));
}
return max + 1;
}
function drawTree(canvasContext, node, x, y, space, px, py) {
if (px !== -1 && py !== -1) {
line(canvasContext, x, y, px, py);
}
const childCount = node.children.length;
const segmentSize = space / childCount;
const startY = y - space / 2 + segmentSize / 2;
for (let i = 0; i < childCount; i++) {
drawTree(
canvasContext,
node.children[i],
x + 30,
startY + segmentSize * i,
space / childCount,
x,
y
);
}
const color = arrayEquals(node.value, substitutions)
? "#ff0000"
: "#000000";
circle(canvasContext, x, y, color);
}
function handleMouse(node, x, y, space, mouseX, mouseY, isClick) {
if (Math.abs(mouseX - x) <= 10 && Math.abs(mouseY - y) <= 10) {
if (isClick) {
substitutions = node.value.slice();
update();
} else {
drawHoverText(x, y, node.value);
}
return true;
}
const childCount = node.children.length;
const segmentSize = space / childCount;
const startY = y - space / 2 + segmentSize / 2;
for (let i = 0; i < childCount; i++) {
const handled = handleMouse(
node.children[i],
x + 30,
startY + segmentSize * i,
space / childCount,
mouseX,
mouseY,
isClick
);
if (handled) {
return true;
}
}
return false;
}
function drawHoverText(x, y, subst) {
hoverElement.innerText = subst;
hoverElement.style.left = x + "px";
hoverElement.style.top = y - 25 + "px";
hoverElement.hidden = false;
}
function circle(canvasContext, x, y, color) {
canvasContext.beginPath();
canvasContext.arc(x, y, 5, 0, Math.PI * 2);
canvasContext.fillStyle = color;
canvasContext.fill();
}
function line(canvasContext, x1, y1, x2, y2) {
canvasContext.beginPath();
canvasContext.moveTo(x1, y1);
canvasContext.lineTo(x2, y2);
canvasContext.stroke();
}
init();