-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1020 lines (923 loc) · 34.9 KB
/
index.html
File metadata and controls
1020 lines (923 loc) · 34.9 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Binary Formatter Demo (Comments + Dynamic Contrast)</title>
<link rel="stylesheet" href="src/styles/main.css" />
<!-- Add Prism.js CSS -->
<link
href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css"
rel="stylesheet"
/>
</head>
<body>
<div id="app-container" role="main">
<div class="header-area">
<h1>32-bit Binary Formatter</h1>
<div class="theme-switch-wrapper">
<span class="theme-label" id="theme-label-text">Dark Mode</span>
<label class="theme-switch" for="theme-checkbox">
<input
type="checkbox"
id="theme-checkbox"
aria-label="Toggle dark mode"
role="switch"
aria-checked="false"
/>
<div class="slider round"></div>
</label>
</div>
</div>
<div class="input-grid">
<div class="input-group">
<label for="decimalInput">Decimal Number (0 - 4,294,967,295):</label>
<input
type="number"
id="decimalInput"
min="0"
max="4294967295"
aria-describedby="decimalInputHelp"
/>
<div id="decimalInputHelp" class="sr-only">
Enter a decimal number between 0 and 4,294,967,295 to see its binary
representation
</div>
</div>
<div class="input-group">
<label for="textColorInput">Text Color:</label>
<select id="textColorInput" aria-label="Choose text color">
<optgroup label="Light Colors">
<option value="#FFFFFF">White</option>
<option value="#E2E8F0">Light Gray</option>
<option value="#EDF2F7">Light Blue Gray</option>
<option value="#F7FAFC">Off White</option>
</optgroup>
<optgroup label="Dark Colors">
<option value="#000000">Black</option>
<option value="#1A202C">Dark Gray</option>
<option value="#2D3748">Navy Gray</option>
<option value="#4A5568">Medium Gray</option>
</optgroup>
</select>
</div>
</div>
<div
class="highlight-controls-container"
role="region"
aria-label="Segment highlighting controls"
>
<h3>Segment Highlighting:</h3>
<div class="highlight-grid" role="group" aria-label="Binary segments">
<div
class="segment-control-block"
role="group"
aria-label="Segment 0 controls"
>
<div class="segment-header">
<label for="enableHighlight0">Segment 0</label>
<input
type="checkbox"
id="enableHighlight0"
data-index="0"
class="highlight-enable-checkbox"
aria-controls="presetColors0"
/>
</div>
<select
id="presetColors0"
data-index="0"
class="preset-color-select"
aria-label="Color preset for segment 0"
tabindex="-1"
></select>
</div>
<div
class="segment-control-block"
role="group"
aria-label="Segment 1 controls"
>
<div class="segment-header">
<label for="enableHighlight1">Segment 1</label>
<input
type="checkbox"
id="enableHighlight1"
data-index="1"
class="highlight-enable-checkbox"
aria-controls="presetColors1"
/>
</div>
<select
id="presetColors1"
data-index="1"
class="preset-color-select"
aria-label="Color preset for segment 1"
tabindex="-1"
></select>
</div>
<div
class="segment-control-block"
role="group"
aria-label="Segment 2 controls"
>
<div class="segment-header">
<label for="enableHighlight2">Segment 2</label>
<input
type="checkbox"
id="enableHighlight2"
data-index="2"
class="highlight-enable-checkbox"
aria-controls="presetColors2"
/>
</div>
<select
id="presetColors2"
data-index="2"
class="preset-color-select"
aria-label="Color preset for segment 2"
tabindex="-1"
></select>
</div>
<div
class="segment-control-block"
role="group"
aria-label="Segment 3 controls"
>
<div class="segment-header">
<label for="enableHighlight3">Segment 3</label>
<input
type="checkbox"
id="enableHighlight3"
data-index="3"
class="highlight-enable-checkbox"
aria-controls="presetColors3"
/>
</div>
<select
id="presetColors3"
data-index="3"
class="preset-color-select"
aria-label="Color preset for segment 3"
tabindex="-1"
></select>
</div>
</div>
</div>
<div class="example-container">
<label>Example Function Call:</label>
<div
id="functionCallExample"
class="code-block"
role="region"
aria-label="Example code"
></div>
</div>
<div class="output-container">
<label>Formatted Output:</label>
<div
class="output-display"
role="region"
aria-label="Binary representation"
>
<div id="output" aria-live="polite"></div>
</div>
</div>
<div class="real-world-example-container">
<h3>Real-World Example: Network Subnet Analysis</h3>
<p>
This example demonstrates how to use the binary formatter in a
practical networking context. The code analyzes subnet configurations
and provides detailed binary representations of network components.
</p>
<div class="code-container">
<div class="code-header">
<span class="code-title">Network Subnet Analysis</span>
<button class="copy-button" aria-label="Copy code to clipboard">
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
<path
d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"
></path>
</svg>
Copy
</button>
</div>
<pre class="language-javascript"><code id="realWorldExample">/**
* Analyzes a network subnet configuration and provides detailed information
* about the subnet mask, network address, and available host addresses.
*
* @param {number} ipAddress - The IP address in decimal format
* @param {number} subnetMask - The subnet mask in decimal format
* @returns {Object} Analysis results including binary representations
*/
function analyzeSubnet(ipAddress, subnetMask) {
// Format the IP address and subnet mask in binary
const ipBinary = formatBinary({
number: ipAddress,
textColor: "#FFFFFF", // White text for dark mode
mode: "dark"
});
const maskBinary = formatBinary({
number: subnetMask,
textColor: "#FFFFFF",
mode: "dark"
});
// Calculate network address (IP AND subnet mask)
const networkAddress = ipAddress & subnetMask;
const networkBinary = formatBinary({
number: networkAddress,
textColor: "#FFFFFF",
mode: "dark"
});
// Calculate broadcast address (network address OR inverted subnet mask)
const invertedMask = ~subnetMask >>> 0; // Convert to unsigned 32-bit
const broadcastAddress = networkAddress | invertedMask;
const broadcastBinary = formatBinary({
number: broadcastAddress,
textColor: "#FFFFFF",
mode: "dark"
});
// Calculate number of available host addresses
const numHosts = Math.pow(2, 32 - countSetBits(subnetMask)) - 2;
return {
ipAddress: {
decimal: ipAddress,
binary: ipBinary
},
subnetMask: {
decimal: subnetMask,
binary: maskBinary
},
networkAddress: {
decimal: networkAddress,
binary: networkBinary
},
broadcastAddress: {
decimal: broadcastAddress,
binary: broadcastBinary
},
numHosts: numHosts
};
}
/**
* Helper function to count the number of set bits in a number
* @param {number} num - The number to analyze
* @returns {number} Count of set bits
*/
function countSetBits(num) {
let count = 0;
while (num) {
count += num & 1;
num >>>= 1;
}
return count;
}
// Example usage:
// IP Address Conversion:
// 192.168.1.1 in decimal is converted to a single 32-bit number:
// 192 * (256^3) + 168 * (256^2) + 1 * (256^1) + 1 * (256^0)
// = 192 * 16,777,216 + 168 * 65,536 + 1 * 256 + 1 * 1
// = 3,221,225,472 + 11,010,048 + 256 + 1
// = 3,232,235,777
const ipAddress = 3232235777; // 192.168.1.1
// Subnet Mask Conversion:
// 255.255.255.0 in decimal is converted to a single 32-bit number:
// 255 * (256^3) + 255 * (256^2) + 255 * (256^1) + 0 * (256^0)
// = 255 * 16,777,216 + 255 * 65,536 + 255 * 256 + 0 * 1
// = 4,278,190,080 + 16,711,680 + 65,280 + 0
// = 4,294,967,040
// This mask represents a /24 network (24 bits for network, 8 bits for hosts)
const subnetMask = 4294967040; // 255.255.255.0
// The subnet mask 255.255.255.0 is chosen because:
// 1. It's a common subnet mask for small networks
// 2. It provides 254 usable host addresses (2^8 - 2)
// 3. It's easy to understand and visualize in binary
// 4. It's commonly used in home and small office networks
const subnetInfo = analyzeSubnet(ipAddress, subnetMask);
console.log("Subnet Analysis Results:");
// Subnet Analysis Results:
console.log("IP Address:", subnetInfo.ipAddress.binary);
// IP Address: 11000000 10101000 00000001 00000001
console.log("Subnet Mask:", subnetInfo.subnetMask.binary);
// Subnet Mask: 11111111 11111111 11111111 00000000
console.log("Network Address:", subnetInfo.networkAddress.binary);
// Network Address: 11000000 10101000 00000001 00000000
console.log("Broadcast Address:", subnetInfo.broadcastAddress.binary);
// Broadcast Address: 11000000 10101000 00000001 11111111
console.log("Available Hosts:", subnetInfo.numHosts);
// Available Hosts: 254</code></pre>
</div>
</div>
<footer class="app-footer">
<a
href="https://github.com/ICJIA/32-bit-binary-formatter"
target="_blank"
rel="noopener noreferrer"
>
View on GitHub
</a>
</footer>
</div>
<!-- Add Prism.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-javascript.min.js"></script>
<script type="module">
/**
* Configuration object for binary formatting
* @typedef {Object} FormatBinaryConfig
* @property {number} [number=0] - The decimal number to convert (0 to 4,294,967,295)
* @property {(string|null)[]} [segmentColors=[null, null, null, null]] - Array of 4 preset IDs or null values for segment highlighting
* @property {string} [textColor="#000000"] - Hex color code for text in light mode, "#e2e8f0" in dark mode
* @property {('light'|'dark')} [mode="dark"] - Current theme mode
*
* @example
* // Default config object:
* const defaultConfig = {
* number: 0,
* segmentColors: [null, null, null, null],
* textColor: "#e2e8f0", // Default for dark mode
* mode: "dark"
* };
*
* // Example custom config:
* const customConfig = {
* number: 123456789,
* segmentColors: ["light-red", null, "dark-blue", null],
* textColor: "#000000",
* mode: "light"
* };
*/
// --- Constants ---
const MIN_UINT32 = 0;
const MAX_UINT32 = 4294967295; // 2^32 - 1
const MIN_CONTRAST_RATIO = 8.0; // Minimum contrast ratio for accessibility
// Add logging utility
const logger = {
info: (message, data = null) => {
console.log(`%c[INFO] ${message}`, "color: #4299e1", data || "");
},
warn: (message, data = null) => {
console.warn(`%c[WARN] ${message}`, "color: #ecc94b", data || "");
},
error: (message, data = null) => {
console.error(`%c[ERROR] ${message}`, "color: #f56565", data || "");
},
success: (message, data = null) => {
console.log(`%c[SUCCESS] ${message}`, "color: #48bb78", data || "");
},
};
// Add animation utility
function animateElement(element, className, duration = 500) {
element.classList.add(className);
setTimeout(() => {
element.classList.remove(className);
}, duration);
}
/**
* @typedef {Object} ColorPreset
* @property {string} name - Display name of the color preset
* @property {string} value - Hex color value for the background
* @property {string} textColor - Hex color value for the text
* @property {string} id - Unique identifier for the preset
*/
/**
* @typedef {Object} ThemePalette
* @property {string} name - Name of the theme
* @property {ColorPreset[]} colors - Array of color presets for the theme
*/
/**
* Preset color palettes for both light and dark themes.
* All colors are verified to have at least 8:1 contrast ratio with their text color.
* @type {Object.<string, ColorPreset[]>}
*/
const presetPalettes = {
"Light Mode": [
{
name: "Light Red",
value: "#FFE5E5", // Very light red background
textColor: "#000000", // Black text
id: "light-red",
},
{
name: "Light Orange",
value: "#FFE5D5", // Very light orange background
textColor: "#000000",
id: "light-orange",
},
{
name: "Light Yellow",
value: "#FFF8E5", // Very light yellow background
textColor: "#000000",
id: "light-yellow",
},
{
name: "Light Green",
value: "#E5FFE5", // Very light green background
textColor: "#000000",
id: "light-green",
},
{
name: "Light Blue",
value: "#E5F6FF", // Very light blue background
textColor: "#000000",
id: "light-blue",
},
{
name: "Light Purple",
value: "#F2E5FF", // Very light purple background
textColor: "#000000",
id: "light-purple",
},
{
name: "Light Gray",
value: "#F5F5F5", // Very light gray background
textColor: "#000000",
id: "light-gray",
},
],
"Dark Mode": [
{
name: "Dark Red",
value: "#8B0000", // Deep red background
textColor: "#FFFFFF", // White text
id: "dark-red",
},
{
name: "Dark Brown",
value: "#3E2723", // Deep brown background
textColor: "#FFFFFF",
id: "dark-brown",
},
{
name: "Dark Gold",
value: "#4A3800", // Deep gold background
textColor: "#FFFFFF",
id: "dark-gold",
},
{
name: "Dark Teal",
value: "#004D40", // Deep teal background
textColor: "#FFFFFF",
id: "dark-teal",
},
{
name: "Dark Indigo",
value: "#1A237E", // Deep indigo background
textColor: "#FFFFFF",
id: "dark-indigo",
},
{
name: "Dark Violet",
value: "#311B92", // Deep violet background
textColor: "#FFFFFF",
id: "dark-violet",
},
{
name: "Dark Gray",
value: "#212121", // Deep gray background
textColor: "#FFFFFF",
id: "dark-gray",
},
],
};
/**
* Maps preset IDs to their corresponding hex color values.
* @type {Object.<string, string>}
*/
let presetIdToHexMap = {};
/**
* Builds the map for quick preset ID to Hex color lookup.
* Should be called once on initialization.
* @returns {void}
*/
function buildPresetMap() {
presetIdToHexMap = {}; // Clear map
for (const groupName in presetPalettes) {
presetPalettes[groupName].forEach((color) => {
if (color.id) {
presetIdToHexMap[color.id] = color.value;
}
});
}
}
// --- Contrast Calculation Utilities ---
/**
* Calculates the relative luminance of a hex color.
* @param {string} hexColor - Color in #RRGGBB format.
* @returns {number} Relative luminance (0-1).
* @throws {Error} If the hex color format is invalid.
*/
function getLuminance(hexColor) {
if (!/^#[0-9A-Fa-f]{6}$/.test(hexColor)) {
throw new Error(`Invalid hex color format: ${hexColor}`);
}
const rgb = parseInt(hexColor.slice(1), 16);
const r = (rgb >> 16) & 0xff;
const g = (rgb >> 8) & 0xff;
const b = (rgb >> 0) & 0xff;
const sR = r / 255;
const sG = g / 255;
const sB = b / 255;
const linR =
sR <= 0.03928 ? sR / 12.92 : Math.pow((sR + 0.055) / 1.055, 2.4);
const linG =
sG <= 0.03928 ? sG / 12.92 : Math.pow((sG + 0.055) / 1.055, 2.4);
const linB =
sB <= 0.03928 ? sB / 12.92 : Math.pow((sB + 0.055) / 1.055, 2.4);
return 0.2126 * linR + 0.7152 * linG + 0.0722 * linB;
}
/**
* Calculates the contrast ratio between two relative luminances.
* @param {number} lum1 - Luminance of the first color.
* @param {number} lum2 - Luminance of the second color.
* @returns {number} Contrast ratio.
* @throws {Error} If either luminance is invalid.
*/
function getContrastRatio(lum1, lum2) {
if (
typeof lum1 !== "number" ||
typeof lum2 !== "number" ||
lum1 < 0 ||
lum2 < 0
) {
throw new Error("Invalid luminance values");
}
const lighter = Math.max(lum1, lum2);
const darker = Math.min(lum1, lum2);
return (lighter + 0.05) / (darker + 0.05);
}
/**
* Default configuration values
* @type {FormatBinaryConfig}
*/
const DEFAULT_CONFIG = {
number: 0,
segmentColors: [null, null, null, null],
textColor: document.body.classList.contains("light-mode")
? "#000000"
: "#FFFFFF",
mode: document.body.classList.contains("light-mode") ? "light" : "dark",
};
/**
* Converts a decimal number to a 32-bit binary string based on a config object.
* Uses preset IDs for segment colors and looks up the hex value.
* Dynamically adjusts text color on shaded segments for better contrast if needed.
* @param {Partial<FormatBinaryConfig>} config - The configuration object (partial)
* @returns {string} An HTML string of the formatted binary number, or an error message string
*/
function formatBinary(config = {}) {
// Merge provided config with defaults
const fullConfig = {
...DEFAULT_CONFIG,
...config,
};
logger.info("Formatting binary number with config:", fullConfig);
if (typeof fullConfig.number !== "number") {
logger.error("Invalid number in config");
return '<span class="error-message">Error: Invalid number passed.</span>';
}
try {
const {
number,
segmentColors = DEFAULT_CONFIG.segmentColors,
textColor = DEFAULT_CONFIG.textColor,
mode = DEFAULT_CONFIG.mode,
} = fullConfig;
const baseTextColor = textColor;
const baseTextLuminance = getLuminance(baseTextColor);
const isBaseTextLight = baseTextLuminance > 0.5;
const unsignedInt = number >>> 0;
const binaryString = unsignedInt.toString(2).padStart(32, "0");
const segments = binaryString.match(/.{1,8}/g) || [];
logger.info("Processing binary segments:", segments);
const styledSegments = segments.map((segment, index) => {
const presetId = Array.isArray(segmentColors)
? segmentColors[index]
: null;
const highlightColor = presetId ? presetIdToHexMap[presetId] : null;
let segmentTextColor = baseTextColor;
// Only check contrast if this segment has highlighting enabled
if (highlightColor) {
try {
const highlightLuminance = getLuminance(highlightColor);
const contrastRatio = getContrastRatio(
baseTextLuminance,
highlightLuminance
);
// Silently adjust text color if contrast is below threshold
if (contrastRatio < MIN_CONTRAST_RATIO) {
segmentTextColor = isBaseTextLight ? "#000000" : "#FFFFFF";
}
} catch (e) {
// If contrast calculation fails, use the base text color
segmentTextColor = baseTextColor;
}
}
let style = `color: ${segmentTextColor};`;
if (highlightColor) {
style += ` background-color: ${highlightColor};`;
}
return `<span style="${style}" class="binary-segment">${segment}</span>`;
});
logger.success("Binary formatting complete");
return styledSegments.join(" ");
} catch (error) {
logger.error("Error in formatBinary:", error);
return '<span class="error-message">Error processing binary format.</span>';
}
}
// --- DOM Element References ---
const decimalInputElement = document.getElementById("decimalInput");
const textColorInputElement = document.getElementById("textColorInput");
const outputElement = document.getElementById("output");
const functionCallExampleElement = document.getElementById(
"functionCallExample"
);
const highlightEnableCheckboxes = document.querySelectorAll(
".highlight-enable-checkbox"
);
const presetColorSelects = document.querySelectorAll(
".preset-color-select"
);
const themeCheckbox = document.getElementById("theme-checkbox");
const themeLabel = document.getElementById("theme-label-text");
/**
* Populates a single preset color dropdown, setting option value to preset ID.
* @param {HTMLSelectElement} selectElement - The dropdown element.
*/
function populatePresetDropdown(selectElement) {
selectElement.innerHTML = "";
const defaultOption = document.createElement("option");
defaultOption.value = "";
defaultOption.textContent = "Select Preset...";
defaultOption.disabled = true;
defaultOption.selected = true;
selectElement.appendChild(defaultOption);
for (const groupName in presetPalettes) {
const optgroup = document.createElement("optgroup");
optgroup.label = groupName;
presetPalettes[groupName].forEach((color) => {
const option = document.createElement("option");
option.value = color.id; // Use ID as the value
option.textContent = color.name;
option.style.backgroundColor = color.value; // Style uses hex
option.style.color = color.textColor || "inherit";
optgroup.appendChild(option);
});
selectElement.appendChild(optgroup);
}
}
/**
* Handles checkbox change event for segment highlighting
* @param {Event} event - The checkbox change event
*/
function handleHighlightCheckboxChange(event) {
const checkbox = event.target;
const index = checkbox.dataset.index;
const selectElement = document.getElementById(`presetColors${index}`);
logger.info(`Highlight checkbox ${index} changed:`, checkbox.checked);
if (checkbox.checked) {
selectElement.classList.add("visible");
selectElement.tabIndex = 0;
const currentTheme = document.body.classList.contains("light-mode")
? "Light Mode"
: "Dark Mode";
const firstColor = presetPalettes[currentTheme][0];
if (firstColor) {
selectElement.value = firstColor.id;
// Animate the segment control block
const segmentBlock = checkbox.closest(".segment-control-block");
animateElement(segmentBlock, "segment-highlight-animation");
}
} else {
selectElement.classList.remove("visible");
selectElement.tabIndex = -1;
selectElement.value = "";
}
updateOutput();
}
/**
* Reads UI controls, validates number input, creates config object with preset IDs,
* calls formatBinary, and updates the output display and example code display.
*/
function updateOutput() {
let isValidNumber = false;
let decimalNumber = NaN;
const rawValue = decimalInputElement.value;
logger.info("Updating output with value:", rawValue);
if (rawValue.trim() !== "") {
const parsedValue = parseInt(rawValue, 10);
if (
!isNaN(parsedValue) &&
parsedValue >= MIN_UINT32 &&
parsedValue <= MAX_UINT32 &&
String(parsedValue) === rawValue.trim()
) {
decimalNumber = parsedValue;
isValidNumber = true;
decimalInputElement.classList.remove("input-error");
logger.success("Valid number entered:", decimalNumber);
} else {
logger.warn("Invalid number entered:", rawValue);
}
}
if (!isValidNumber) {
outputElement.innerHTML = `<span class="error-message">Please enter a valid integer between ${MIN_UINT32} and ${MAX_UINT32}.</span>`;
functionCallExampleElement.textContent = "// Invalid input number";
decimalInputElement.classList.add("input-error");
return;
}
const textColor = textColorInputElement.value;
const segmentHighlightIds = [];
highlightEnableCheckboxes.forEach((checkbox) => {
const index = checkbox.dataset.index;
const presetSelect = document.getElementById(`presetColors${index}`);
segmentHighlightIds[index] =
checkbox.checked && presetSelect.value ? presetSelect.value : null;
});
const config = {
number: decimalNumber,
segmentColors: segmentHighlightIds,
textColor: textColor,
mode: document.body.classList.contains("light-mode")
? "light"
: "dark",
};
const formattedHtml = formatBinary(config);
outputElement.innerHTML = formattedHtml;
// Animate newly highlighted segments
const segments = outputElement.querySelectorAll(".binary-segment");
segments.forEach((segment, index) => {
if (segmentHighlightIds[index]) {
animateElement(segment, "highlight-animation");
}
});
const configString = JSON.stringify(
config,
(key, value) => {
if (key === "segmentColors") {
return value.map((id) => (id === null ? null : String(id)));
}
return value;
},
2
);
const exampleCallString = `// Configuration Object using selections above:
const config = ${configString};
// Function Call:
const binaryString = formatBinary(config);
`;
functionCallExampleElement.textContent = exampleCallString;
}
/**
* Resets all controls to their default state
*/
function resetControlsToDefault() {
// Reset all checkboxes and hide select boxes
highlightEnableCheckboxes.forEach((checkbox) => {
checkbox.checked = false;
const index = checkbox.dataset.index;
const selectElement = document.getElementById(`presetColors${index}`);
selectElement.classList.remove("visible");
selectElement.tabIndex = -1;
selectElement.value = "";
});
// Generate a new random number
const randomNum = Math.floor(Math.random() * (MAX_UINT32 + 1));
decimalInputElement.value = randomNum;
}
/**
* Applies the selected theme (light/dark) to the body, updates the label,
* sets the default text color picker value, and saves the preference to localStorage.
* Also resets all controls to their default state.
* @param {boolean} isLight - True if light mode should be applied, false for dark.
*/
function applyTheme(isLight) {
logger.info(`Applying theme: ${isLight ? "light" : "dark"}`);
const defaultTextColor = isLight ? "#000000" : "#FFFFFF";
textColorInputElement.value = defaultTextColor;
if (isLight) {
document.body.classList.add("light-mode");
themeLabel.textContent = "Light Mode";
localStorage.setItem("theme", "light");
} else {
document.body.classList.remove("light-mode");
themeLabel.textContent = "Dark Mode";
localStorage.setItem("theme", "dark");
}
// Reset all controls to default state
resetControlsToDefault();
// Update the output with the new random number and default state
updateOutput();
logger.success(`Theme applied: ${isLight ? "light" : "dark"}`);
}
// --- Event Listeners ---
// Update output when number input changes
decimalInputElement.addEventListener("input", updateOutput);
// Update output when text color picker changes
textColorInputElement.addEventListener("change", updateOutput);
// Update output when highlight enable checkbox changes
highlightEnableCheckboxes.forEach((checkbox) => {
checkbox.addEventListener("change", handleHighlightCheckboxChange);
});
// Update output when preset color selection changes
presetColorSelects.forEach((select) => {
select.addEventListener("change", (event) => {
updateOutput();
});
});
// Apply theme when theme switch changes
themeCheckbox.addEventListener("change", (event) => {
applyTheme(event.target.checked);
updateOutput();
});
// Add keyboard navigation for segment controls
function handleSegmentKeydown(event) {
const checkbox = event.target;
const index = parseInt(checkbox.dataset.index);
const selectElement = document.getElementById(`presetColors${index}`);
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
checkbox.checked = !checkbox.checked;
handleHighlightCheckboxChange({ target: checkbox });
}
}
// Add keyboard event listeners
highlightEnableCheckboxes.forEach((checkbox) => {
checkbox.addEventListener("keydown", handleSegmentKeydown);
});
// --- Initial Setup ---
/**
* Initializes the application UI on page load.
*/
function initializeUI() {
buildPresetMap(); // Create the ID -> Hex map
presetColorSelects.forEach(populatePresetDropdown); // Fill dropdowns
// Ensure all checkboxes are off and select boxes are hidden
highlightEnableCheckboxes.forEach((checkbox) => {
checkbox.checked = false;
const index = checkbox.dataset.index;
const selectElement = document.getElementById(`presetColors${index}`);
selectElement.classList.remove("visible");
selectElement.value = "";
});
// Set Random Default Number
const randomNum = Math.floor(Math.random() * (MAX_UINT32 + 1));
decimalInputElement.value = randomNum;
// Load Theme and Set Initial Text Color
const savedTheme = localStorage.getItem("theme");
const prefersLight = savedTheme === "light";
themeCheckbox.checked = prefersLight; // Set switch state
const initialTextColor = prefersLight ? "#000000" : "#FFFFFF";
textColorInputElement.value = initialTextColor; // Set default text color
// Apply theme class and label
if (prefersLight) {
document.body.classList.add("light-mode");
themeLabel.textContent = "Light Mode";
} else {
document.body.classList.remove("light-mode");
themeLabel.textContent = "Dark Mode";
}
// Initial Render
updateOutput();
}
// Run initialization after the DOM is fully loaded.
document.addEventListener("DOMContentLoaded", initializeUI);
// Add copy button functionality
const copyButton = document.querySelector(".copy-button");
const realWorldExample = document.getElementById("realWorldExample");
copyButton.addEventListener("click", () => {
const text = realWorldExample.textContent;
navigator.clipboard.writeText(text).then(() => {
copyButton.innerHTML = `
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<polyline points="20 6 9 17 4 12"></polyline>