-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1318 lines (1131 loc) · 37.1 KB
/
Copy pathapp.js
File metadata and controls
1318 lines (1131 loc) · 37.1 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
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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const input = document.querySelector("#prefixInput");
const ghost = document.querySelector("#ghostText");
const suggestions = document.querySelector("#prefixSuggestions");
const message = document.querySelector("#message");
const prefixList = document.querySelector("#prefixList");
const prefixMeta = document.querySelector("#prefixMeta");
const currentDetails = document.querySelector("#currentDetails");
const adjacentDetails = document.querySelector("#adjacentDetails");
const containsInput = document.querySelector("#containsInput");
const containsResult = document.querySelector("#containsResult");
const themeToggle = document.querySelector("#themeToggle");
const presentationControl = document.querySelector("#presentationControl");
const presentationOptions = Array.from(document.querySelectorAll("[data-presentation]"));
const navButtons = Array.from(document.querySelectorAll("[data-nav]"));
const panels = Array.from(document.querySelectorAll(".panel"));
const VERSION_BITS = { 4: 32, 6: 128 };
const MAX_VALUES = { 4: 1n << 32n, 6: 1n << 128n };
const URL_PREFIX_PARAM = "prefix";
const URL_VIEW_PARAM = "view";
const PREFIX_HISTORY_LIMIT = 100;
const MOUSE_BACK_BUTTON = 3;
const MOUSE_FORWARD_BUTTON = 4;
const DEFAULT_SUGGESTIONS = [
"192.168.10.0/24",
"10.0.0.0/8",
"172.16.0.0/12",
"100.64.0.0/10",
"127.0.0.1/32",
"8.8.8.8/32",
"::1/128",
"2001:db8::/32",
"fc00::/7",
"fe80::/10",
"::ffff:192.0.2.1/128",
];
const IPV6_COMPRESSION_LIGATURE = "∷";
const INPUT_WRAP_HINT = "\u200b";
const PRESENTATION_MODES = [
{ id: "regular", label: "Regular" },
{ id: "hex", label: "Hex" },
{ id: "binary", label: "Binary" },
{ id: "integer", label: "Integer" },
];
let current = null;
const loadedPresentationMode = loadPresentationModeFromUrl();
let shouldUseLoadedPresentationMode = Boolean(loadedPresentationMode);
let presentationMode = loadedPresentationMode || PRESENTATION_MODES[0].id;
let typingTimer = 0;
let recents = loadRecents();
let prefixHistory = [];
let prefixHistoryIndex = -1;
let previousPrefixKey = "";
let lastMouseHistoryButton = null;
let lastMouseHistoryButtonTime = 0;
const adjacencyMapResizeObserver = "ResizeObserver" in window
? new ResizeObserver(() => updateAdjacencyMap())
: null;
function parsePrefix(value) {
const raw = cleanPrefixInputValue(value).trim();
if (!raw) {
throw new Error("enter a prefix");
}
const slashCount = (raw.match(/\//g) || []).length;
if (slashCount > 1) {
throw new Error("too many slashes");
}
const [addressText, prefixText] = raw.split("/");
const version = addressText.includes(":") ? 6 : 4;
const bits = VERSION_BITS[version];
const address = version === 4 ? parseIPv4(addressText) : parseIPv6(addressText);
const prefixLength = prefixText === undefined || prefixText === ""
? bits
: parsePrefixLength(prefixText, bits);
const hostBits = BigInt(bits - prefixLength);
const size = 1n << hostBits;
const network = (address >> hostBits) << hostBits;
const last = network + size - 1n;
return {
version,
bits,
address,
prefixLength,
hostBits,
size,
network,
last,
};
}
function parsePrefixLength(value, bits) {
if (!/^\d+$/.test(value)) {
throw new Error("bad prefix length");
}
const prefixLength = Number(value);
if (prefixLength < 0 || prefixLength > bits) {
throw new Error(`prefix length must be 0-${bits}`);
}
return prefixLength;
}
function parseIPv4(value) {
const parts = value.trim().split(".");
if (parts.length !== 4) {
throw new Error("IPv4 needs four octets");
}
return parts.reduce((acc, part) => {
if (!/^\d+$/.test(part)) {
throw new Error("bad IPv4 octet");
}
const octet = Number(part);
if (octet > 255) {
throw new Error("IPv4 octet must be 0-255");
}
return (acc << 8n) + BigInt(octet);
}, 0n);
}
function parseIPv6(value) {
const text = value.trim().toLowerCase();
if (!text || text.includes("%")) {
throw new Error("bad IPv6 address");
}
const compressed = text.includes("::");
if ((text.match(/::/g) || []).length > 1) {
throw new Error("bad IPv6 compression");
}
const [leftText = "", rightText = ""] = text.split("::");
const leftParts = leftText ? leftText.split(":") : [];
const rightParts = rightText ? rightText.split(":") : [];
validateIPv4Tail(leftParts, rightParts);
const left = parseIPv6Parts(leftParts);
const right = parseIPv6Parts(rightParts);
const used = left.length + right.length;
const fill = compressed ? 8 - used : 0;
if ((!compressed && used !== 8) || (compressed && fill < 1)) {
throw new Error("bad IPv6 length");
}
const groups = [...left, ...Array(fill).fill(0), ...right];
if (groups.length !== 8) {
throw new Error("bad IPv6 address");
}
return groups.reduce((acc, group) => (acc << 16n) + BigInt(group), 0n);
}
function validateIPv4Tail(leftParts, rightParts) {
const all = [...leftParts, ...rightParts];
const dotIndexes = all.flatMap((part, index) => (part.includes(".") ? [index] : []));
if (dotIndexes.length > 1 || (dotIndexes.length === 1 && dotIndexes[0] !== all.length - 1)) {
throw new Error("IPv4 tail must be last");
}
}
function parseIPv6Parts(parts) {
const groups = [];
for (const part of parts) {
if (!part) {
throw new Error("bad IPv6 group");
}
if (part.includes(".")) {
const ipv4 = parseIPv4(part);
groups.push(Number((ipv4 >> 16n) & 0xffffn), Number(ipv4 & 0xffffn));
continue;
}
if (!/^[0-9a-f]{1,4}$/.test(part)) {
throw new Error("bad IPv6 group");
}
groups.push(parseInt(part, 16));
}
return groups;
}
function formatAddress(value, version) {
return version === 4 ? formatIPv4(value) : formatIPv6(value);
}
function formatIPv4(value) {
return [24n, 16n, 8n, 0n]
.map((shift) => Number((value >> shift) & 255n))
.join(".");
}
function formatIPv6(value) {
const groups = [];
for (let shift = 112n; shift >= 0n; shift -= 16n) {
groups.push(Number((value >> shift) & 0xffffn));
}
let bestStart = -1;
let bestLength = 0;
for (let index = 0; index < groups.length;) {
if (groups[index] !== 0) {
index += 1;
continue;
}
let end = index;
while (end < groups.length && groups[end] === 0) {
end += 1;
}
const length = end - index;
if (length > bestLength && length > 1) {
bestStart = index;
bestLength = length;
}
index = end;
}
if (bestStart === -1) {
return groups.map((group) => group.toString(16)).join(":");
}
const before = groups.slice(0, bestStart).map((group) => group.toString(16)).join(":");
const after = groups.slice(bestStart + bestLength).map((group) => group.toString(16)).join(":");
if (!before && !after) return "::";
if (!before) return `::${after}`;
if (!after) return `${before}::`;
return `${before}::${after}`;
}
function formatPrefix(prefix) {
return `${formatAddress(prefix.network, prefix.version)}/${prefix.prefixLength}`;
}
function formatInputPrefix(prefix) {
return `${formatAddress(prefix.address, prefix.version)}/${prefix.prefixLength}`;
}
function formatInputPrefixLength(prefixLength) {
const raw = cleanPrefixInputValue();
const slashIndex = raw.indexOf("/");
const addressText = slashIndex === -1 ? raw : raw.slice(0, slashIndex);
return `${addressText}/${prefixLength}`;
}
function formatMask(prefix) {
return formatAddress(maskValue(prefix), prefix.version);
}
function maskValue(prefix) {
return ((1n << BigInt(prefix.prefixLength)) - 1n) << prefix.hostBits;
}
function formatPresentedPrefix(prefix) {
return `${formatPresentedAddress(prefix.network, prefix.version)}/${prefix.prefixLength}`;
}
function formatPresentedAddress(value, version, mode = presentationMode) {
if (mode === "hex") {
return version === 4 ? formatIPv4Hex(value) : formatIPv6Hex(value);
}
if (mode === "binary") {
return version === 4 ? formatIPv4Binary(value) : formatIPv6Binary(value);
}
if (mode === "integer") {
return value.toString();
}
return formatAddress(value, version);
}
function formatPresentedCount(value) {
if (presentationMode === "hex") {
return `0x${value.toString(16)}`;
}
if (presentationMode === "binary") {
return `0b${value.toString(2)}`;
}
return formatCount(value);
}
function formatPresentedAddressPosition(prefix) {
const diff = prefix.address - prefix.network;
const positionSize = `${formatPresentedCount(diff)} / ${formatPresentedCount(prefix.size)}`;
if (prefix.prefixLength >= prefix.bits) {
return positionSize;
}
const child = prefix.address < prefix.network + (prefix.size >> 1n) ? "↙" : "↘";
return `${positionSize} ${child}`;
}
function formatIPv4Hex(value) {
return [24n, 16n, 8n, 0n]
.map((shift) => Number((value >> shift) & 255n).toString(16).padStart(2, "0"))
.join(".");
}
function formatIPv6Hex(value) {
const groups = [];
for (let shift = 112n; shift >= 0n; shift -= 16n) {
groups.push(Number((value >> shift) & 0xffffn).toString(16).padStart(4, "0"));
}
return groups.join(":");
}
function formatIPv4Binary(value) {
return [24n, 16n, 8n, 0n]
.map((shift) => Number((value >> shift) & 255n).toString(2).padStart(8, "0"))
.join(".");
}
function formatIPv6Binary(value) {
const groups = [];
for (let shift = 112n; shift >= 0n; shift -= 16n) {
groups.push(Number((value >> shift) & 0xffffn).toString(2).padStart(16, "0"));
}
return groups.join(":");
}
function formatDisplayText(value) {
return value.replaceAll("::", IPV6_COMPRESSION_LIGATURE);
}
function normalizeDisplayText(value) {
return value
.replaceAll(INPUT_WRAP_HINT, "")
.replace(new RegExp(`${IPV6_COMPRESSION_LIGATURE}[\r\n]*`, "g"), "::")
.replace(/:[\r\n]+/g, ":")
.replace(/\.[\r\n]+/g, ".");
}
function cleanPrefixInputValue(value = input.value) {
return value.replaceAll(INPUT_WRAP_HINT, "");
}
function formatPrefixInputValue(value) {
return cleanPrefixInputValue(value).replace(/([:.])/g, `$1${INPUT_WRAP_HINT}`);
}
function setPrefixInputValue(value) {
input.value = formatPrefixInputValue(value);
}
function syncPrefixInputWrapHints() {
const value = input.value;
const cleanValue = cleanPrefixInputValue(value);
const formattedValue = formatPrefixInputValue(cleanValue);
if (value === formattedValue) {
return cleanValue;
}
const selectionStart = cleanPrefixInputValue(value.slice(0, input.selectionStart ?? value.length)).length;
const selectionEnd = cleanPrefixInputValue(value.slice(0, input.selectionEnd ?? value.length)).length;
input.value = formattedValue;
input.setSelectionRange(
displayIndexForCleanIndex(formattedValue, selectionStart),
displayIndexForCleanIndex(formattedValue, selectionEnd),
);
return cleanValue;
}
function displayIndexForCleanIndex(value, cleanIndex) {
let seen = 0;
for (let index = 0; index < value.length; index += 1) {
if (seen === cleanIndex) {
return index;
}
if (value[index] !== INPUT_WRAP_HINT) {
seen += 1;
}
}
return value.length;
}
function setDisplayText(element, value) {
const displayText = formatDisplayText(value);
const nodes = [];
for (const character of displayText) {
nodes.push(document.createTextNode(character));
if (character === ":" || character === IPV6_COMPRESSION_LIGATURE) {
nodes.push(document.createElement("wbr"));
}
}
element.replaceChildren(...nodes);
element.classList.toggle("display-text--wrap-separator", /[:∷]/.test(displayText));
element.dataset.copyValue = value;
if (value !== displayText) {
element.setAttribute("aria-label", value);
} else {
element.removeAttribute("aria-label");
}
}
function prefixFromNetwork(network, base = current) {
const max = MAX_VALUES[base.version];
const size = base.size;
const clamped = clampBigInt(network, 0n, max - size);
return {
...base,
address: clamped,
network: clamped,
last: clamped + size - 1n,
};
}
function prefixFromNetworkPreservingAddress(network, base = current) {
const max = MAX_VALUES[base.version];
const size = base.size;
const clamped = clampBigInt(network, 0n, max - size);
const addressOffset = base.address - base.network;
const address = clampBigInt(clamped + addressOffset, clamped, clamped + size - 1n);
return {
...base,
address,
network: clamped,
last: clamped + size - 1n,
};
}
function childPrefix(base, second = false) {
if (base.prefixLength >= base.bits) return null;
const size = base.size >> 1n;
const network = base.network + (second ? size : 0n);
return {
...base,
prefixLength: base.prefixLength + 1,
hostBits: base.hostBits - 1n,
size,
network,
address: network,
last: network + size - 1n,
};
}
function parentPrefix(base) {
if (base.prefixLength <= 0) return null;
const prefixLength = base.prefixLength - 1;
const hostBits = BigInt(base.bits - prefixLength);
const size = 1n << hostBits;
const network = (base.network >> hostBits) << hostBits;
return {
...base,
prefixLength,
hostBits,
size,
network,
address: network,
last: network + size - 1n,
};
}
function adjacentPrefix(base, direction) {
const target = base.network + base.size * BigInt(direction);
if (target < 0n || target + base.size > MAX_VALUES[base.version]) {
return null;
}
return prefixFromNetwork(target, base);
}
function render() {
let next = null;
try {
const previousVersion = current?.version;
next = parsePrefix(input.value);
if (previousVersion !== next.version) {
if (shouldUseLoadedPresentationMode) {
shouldUseLoadedPresentationMode = false;
} else {
setDefaultPresentation(next.version);
}
}
current = next;
message.textContent = "";
input.setAttribute("aria-invalid", "false");
savePrefixToUrl(next);
} catch (error) {
message.textContent = error.message;
input.setAttribute("aria-invalid", "true");
updateNavControls(null);
updatePresentationControl(null);
updateGhost();
resizePrefixInput();
checkContainment();
return;
}
renderPrefixList(next);
renderCurrent(next);
renderAdjacent(next);
updateNavControls(next);
updatePresentationControl(next);
checkContainment();
updateSuggestions(next);
updateGhost();
resizePrefixInput();
flashPanels();
}
function renderPrefixList(prefix) {
const windowSize = 17;
const middle = Math.floor(windowSize / 2);
const maxIndex = MAX_VALUES[prefix.version] / prefix.size - 1n;
const index = prefix.network / prefix.size;
let start = index - BigInt(middle);
if (start < 0n) start = 0n;
if (start + BigInt(windowSize - 1) > maxIndex) {
start = maxIndex - BigInt(windowSize - 1);
}
if (start < 0n) start = 0n;
const rows = [];
const rowCount = Number(minBigInt(BigInt(windowSize), maxIndex + 1n));
for (let offset = 0; offset < rowCount; offset += 1) {
const rowIndex = start + BigInt(offset);
const network = rowIndex * prefix.size;
const row = prefixFromNetwork(network, prefix);
rows.push(row);
}
prefixMeta.textContent = `/${prefix.prefixLength}`;
prefixList.replaceChildren(
...rows.map((row) => {
const isCurrent = row.network === prefix.network;
const isPrevious = !isCurrent && isPreviousPrefix(row);
const button = document.createElement("button");
button.type = "button";
button.className = [
"prefix-item",
isCurrent ? "active" : "",
isPrevious ? "previous" : "",
].filter(Boolean).join(" ");
button.dataset.prefix = formatPrefix(row);
button.innerHTML = `<span></span><span></span>`;
setDisplayText(button.children[0], formatPrefix(row));
button.children[1].textContent = isCurrent
? "now"
: isPrevious
? "(previous)"
: signedOffset(row.network, prefix);
button.addEventListener("click", () => setPrefixWithNavigatedAddress(row, prefix));
return button;
}),
);
}
function signedOffset(rowNetwork, prefix) {
const distance = (rowNetwork - prefix.network) / prefix.size;
return distance > 0n ? `+${distance}` : `${distance}`;
}
function renderCurrent(prefix) {
const details = [
["Prefix", formatPresentedPrefix(prefix)],
["Address position / size", formatPresentedAddressPosition(prefix)],
["Version", `IPv${prefix.version}`],
["Mask", formatPresentedAddress(maskValue(prefix), prefix.version)],
["Network", formatPresentedAddress(prefix.network, prefix.version)],
[prefix.version === 4 ? "Broadcast" : "Last", formatPresentedAddress(prefix.last, prefix.version)],
];
currentDetails.replaceChildren(...details.flatMap(([label, value]) => {
const dt = document.createElement("dt");
const dd = document.createElement("dd");
dt.textContent = label;
setDisplayText(dd, value);
return [dt, dd];
}));
}
function renderAdjacent(prefix) {
const items = [
["parent", "Parent", parentPrefix(prefix)],
["left", "Left", adjacentPrefix(prefix, -1)],
["right", "Right", adjacentPrefix(prefix, 1)],
["child-left", "Child 1", childPrefix(prefix, false)],
["child-right", "Child 2", childPrefix(prefix, true)],
].filter(([, , item]) => item);
const map = createAdjacencyMap(items.map(([role]) => role));
const buttons = items.map(([role, label, item]) => {
const isPrevious = isPreviousPrefix(item);
const button = document.createElement("button");
button.type = "button";
button.className = [
"adjacent-button",
`adjacent-button--${role}`,
isPrevious ? "previous" : "",
].filter(Boolean).join(" ");
button.innerHTML = `<span></span><b></b>`;
button.children[0].textContent = isPrevious ? `${label} (previous)` : label;
setDisplayText(button.children[1], formatPrefix(item));
if (isPrevious) {
button.title = `Previous prefix: ${formatPrefix(item)}`;
}
button.addEventListener("click", () => setAdjacentPrefix(item, prefix));
return button;
});
adjacentDetails.replaceChildren(map, ...buttons);
adjacencyMapResizeObserver?.disconnect();
adjacencyMapResizeObserver?.observe(adjacentDetails);
updateAdjacencyMap(map);
}
function createAdjacencyMap(roles) {
const map = document.createElement("div");
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
const dot = document.createElement("button");
map.className = "adjacency-map";
map.dataset.roles = roles.join(" ");
map.classList.toggle("has-previous", Boolean(previousPrefixKey));
svg.classList.add("adjacency-lines");
svg.setAttribute("aria-hidden", "true");
svg.setAttribute("preserveAspectRatio", "none");
dot.className = "adjacency-dot";
dot.type = "button";
dot.title = "Clear previous prefix";
dot.setAttribute("aria-label", "Clear previous prefix");
dot.addEventListener("click", clearPreviousPrefixHighlight);
map.append(svg, dot);
return map;
}
function updateAdjacencyMap(map = adjacentDetails.querySelector(".adjacency-map")) {
if (!map) return;
const svg = map.querySelector(".adjacency-lines");
const dot = map.querySelector(".adjacency-dot");
const mapRect = map.getBoundingClientRect();
const roles = map.dataset.roles.split(" ").filter(Boolean);
svg.replaceChildren();
if (!mapRect.width || !mapRect.height) return;
const centers = Object.fromEntries(roles.flatMap((role) => {
const button = adjacentDetails.querySelector(`.adjacent-button--${role}`);
if (!button) return [];
const rect = button.getBoundingClientRect();
return [[role, [
rect.left + rect.width / 2 - mapRect.left,
rect.top + rect.height / 2 - mapRect.top,
]]];
}));
const center = adjacencyCenter(centers, mapRect);
dot.style.left = `${center[0]}px`;
dot.style.top = `${center[1]}px`;
svg.setAttribute("viewBox", `0 0 ${mapRect.width} ${mapRect.height}`);
const childRoles = roles.filter((role) => role.startsWith("child-") && centers[role]);
const childJunction = childRoles.length > 1
? [
center[0],
childRoles.reduce((sum, role) => sum + centers[role][1], 0) / childRoles.length,
]
: null;
const previousChildRole = childRoles.find((role) => {
const button = adjacentDetails.querySelector(`.adjacent-button--${role}`);
return button?.classList.contains("previous");
});
if (childJunction) {
appendAdjacencyLine(svg, [center, childJunction], Boolean(previousChildRole));
}
roles.forEach((role) => {
const point = centers[role];
if (!point) return;
const button = adjacentDetails.querySelector(`.adjacent-button--${role}`);
const isPrevious = button?.classList.contains("previous");
const routeToPrefix = childJunction && role.startsWith("child-")
? [childJunction, point]
: role.startsWith("child-")
? [center, [center[0], point[1]], point]
: [center, point];
appendAdjacencyLine(svg, routeToPrefix, isPrevious);
});
}
function appendAdjacencyLine(svg, routeToPrefix, isPrevious = false) {
const line = document.createElementNS("http://www.w3.org/2000/svg", "polyline");
const route = isPrevious ? [...routeToPrefix].reverse() : routeToPrefix;
if (isPrevious) {
line.classList.add("previous");
}
line.setAttribute("points", route.map(([x, y]) => `${x},${y}`).join(" "));
svg.append(line);
}
function adjacencyCenter(centers, mapRect) {
if (centers.left && centers.right) {
return [
(centers.left[0] + centers.right[0]) / 2,
(centers.left[1] + centers.right[1]) / 2,
];
}
const rowAnchor = centers.left || centers.right || centers["child-left"] || centers["child-right"];
return [
mapRect.width / 2,
rowAnchor ? rowAnchor[1] : mapRect.height / 2,
];
}
function setPrefix(prefix, remember = true) {
beginPrefixNavigation();
setPrefixInputValue(formatPrefix(prefix));
current = prefix;
if (remember) {
rememberPrefix(cleanPrefixInputValue());
}
recordPrefixHistory(formatInputPrefix(prefix));
render();
}
function setAdjacentPrefix(prefix, base) {
setPrefixWithNavigatedAddress(prefix, base);
}
function setPrefixWithNavigatedAddress(prefix, base) {
beginPrefixNavigation(base);
setPrefixWithAddress(prefix, navigatedAddress(prefix, base));
}
function navigatedAddress(prefix, base) {
if (containsAddress(prefix, base.address)) {
return base.address;
}
const addressOffset = (base.address - base.network) % prefix.size;
return prefix.network + addressOffset;
}
function movePrefix(delta) {
if (!current) return;
beginPrefixNavigation();
const target = current.network + current.size * BigInt(delta);
const next = prefixFromNetworkPreservingAddress(target, current);
setPrefixWithAddress(next, next.address);
}
function resizePrefix(direction) {
if (!current) return;
beginPrefixNavigation();
const next = direction < 0 ? childPrefixContaining(current) : parentPrefix(current);
if (next) {
setPrefixLengthWithAddress(next, current.address);
}
}
function childPrefixContaining(base) {
if (base.prefixLength >= base.bits) return null;
const second = base.address >= base.network + (base.size >> 1n);
return childPrefix(base, second);
}
function containsAddress(prefix, address) {
return address >= prefix.network && address <= prefix.last;
}
function setPrefixWithAddress(prefix, address, remember = true) {
const next = { ...prefix, address };
setPrefixInputValue(formatInputPrefix(next));
current = next;
if (remember) {
rememberPrefix(cleanPrefixInputValue());
}
recordPrefixHistory(formatInputPrefix(next));
render();
}
function setPrefixLengthWithAddress(prefix, address, remember = true) {
const next = { ...prefix, address };
setPrefixInputValue(formatInputPrefixLength(next.prefixLength));
current = next;
if (remember) {
rememberPrefix(cleanPrefixInputValue());
}
recordPrefixHistory(formatInputPrefix(next));
render();
}
function updateNavControls(prefix) {
const controls = prefix
? {
up: {
enabled: Boolean(adjacentPrefix(prefix, -1)),
label: `-${formatPowerOfTwoLabel(prefix.hostBits)}`,
title: `Previous prefix (-${formatCount(prefix.size)})`,
},
down: {
enabled: Boolean(adjacentPrefix(prefix, 1)),
label: `+${formatPowerOfTwoLabel(prefix.hostBits)}`,
title: `Next prefix (+${formatCount(prefix.size)})`,
},
left: {
enabled: Boolean(parentPrefix(prefix)),
label: `/${Math.max(0, prefix.prefixLength - 1)}`,
title: "Parent prefix",
},
right: {
enabled: Boolean(childPrefix(prefix, false)),
label: `/${Math.min(prefix.bits, prefix.prefixLength + 1)}`,
title: "Child prefix",
},
}
: {
up: { enabled: false, label: "-", title: "Previous prefix" },
down: { enabled: false, label: "-", title: "Next prefix" },
left: { enabled: false, label: "-", title: "Parent prefix" },
right: { enabled: false, label: "-", title: "Child prefix" },
};
navButtons.forEach((button) => {
const control = controls[button.dataset.nav];
button.disabled = !control.enabled;
button.textContent = control.label;
button.setAttribute("aria-label", control.title);
button.title = control.title;
});
}
function setDefaultPresentation() {
setPresentationMode(PRESENTATION_MODES[0].id, false);
}
function setPresentationMode(mode, renderPanel = true) {
presentationMode = normalizePresentationMode(mode);
savePresentationModeToUrl();
updatePresentationControl(current);
if (renderPanel && current) {
renderCurrent(current);
}
}
function updatePresentationControl(prefix) {
const modeIndex = Math.max(0, PRESENTATION_MODES.findIndex((item) => item.id === presentationMode));
presentationControl.style.setProperty("--presentation-index", modeIndex);
presentationControl.classList.toggle("is-disabled", !prefix);
presentationOptions.forEach((button, index) => {
const active = index === modeIndex;
button.disabled = !prefix;
button.setAttribute("aria-checked", String(active));
button.tabIndex = active ? 0 : -1;
});
}
function checkContainment() {
containsResult.className = "contains-result";
if (!current) {
containsResult.textContent = "-";
return;
}
const raw = containsInput.value.trim();
if (!raw) {
containsResult.textContent = "-";
return;
}
try {
const candidate = parsePrefix(raw);
if (candidate.version !== current.version) {
containsResult.textContent = `IPv${candidate.version}`;
containsResult.classList.add("no");
return;
}
const contained = candidate.network >= current.network && candidate.last <= current.last;
containsResult.textContent = contained ? "yes" : "no";
containsResult.classList.add(contained ? "yes" : "no");
} catch {
containsResult.textContent = "bad";
containsResult.classList.add("error");
}
}
function updateSuggestions(prefix = current) {
const dynamic = [];
if (prefix) {
dynamic.push(formatPrefix(prefix));
const parent = parentPrefix(prefix);
const firstChild = childPrefix(prefix, false);
const secondChild = childPrefix(prefix, true);
if (parent) dynamic.push(formatPrefix(parent));
if (firstChild) dynamic.push(formatPrefix(firstChild));
if (secondChild) dynamic.push(formatPrefix(secondChild));
}
const values = unique([...dynamic, ...recents, ...DEFAULT_SUGGESTIONS]);
suggestions.replaceChildren(...values.slice(0, 32).map((value) => {
const option = document.createElement("option");
option.value = value;
return option;
}));
}
function updateGhost() {
const value = cleanPrefixInputValue();
const lower = value.toLowerCase();
const match = Array.from(suggestions.options)
.map((option) => option.value)
.find((option) => option.toLowerCase().startsWith(lower) && option.length > value.length);
ghost.dataset.value = match || "";
if (!match) {
ghost.replaceChildren();
return;
}
const typed = document.createElement("span");
const suffix = document.createElement("span");
typed.className = "ghost-prefix";
typed.textContent = formatPrefixInputValue(value);
suffix.textContent = formatPrefixInputValue(match.slice(value.length));
ghost.replaceChildren(typed, suffix);
}
function resizePrefixInput() {
input.style.height = "auto";
input.style.height = `${input.scrollHeight}px`;
}
function rememberPrefix(value) {
recents = unique([value, ...recents]).slice(0, 12);
try {
localStorage.setItem("ipcalc.recents", JSON.stringify(recents));
} catch {
// Browsers can deny storage in private contexts.
}
}
function recordPrefixHistory(value) {
const cleanValue = cleanPrefixInputValue(value).trim();
if (!cleanValue || prefixHistory[prefixHistoryIndex] === cleanValue) return;
prefixHistory = prefixHistory.slice(0, prefixHistoryIndex + 1);
prefixHistory.push(cleanValue);
if (prefixHistory.length > PREFIX_HISTORY_LIMIT) {
prefixHistory = prefixHistory.slice(prefixHistory.length - PREFIX_HISTORY_LIMIT);
}
prefixHistoryIndex = prefixHistory.length - 1;
}
function commitCurrentPrefixHistory() {
if (current) {
recordPrefixHistory(formatInputPrefix(current));
}
}
function beginPrefixNavigation(origin = current) {
commitCurrentPrefixHistory();
previousPrefixKey = prefixKey(origin);
}
function movePrefixHistory(delta) {
const nextIndex = prefixHistoryIndex + delta;
if (nextIndex < 0 || nextIndex >= prefixHistory.length) {
return false;
}
previousPrefixKey = prefixKey(current);
prefixHistoryIndex = nextIndex;
setPrefixInputValue(prefixHistory[prefixHistoryIndex]);
render();
return true;
}
function prefixKey(prefix) {
return prefix