-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1536 lines (1341 loc) · 56.2 KB
/
Copy pathscript.js
File metadata and controls
1536 lines (1341 loc) · 56.2 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
/**
* Randomizer — Fast, Flexible & Animated Client-Side Engine
* Synchronization with GitHub Graphite Design Language & Time-Calculator Layout
*/
document.addEventListener('DOMContentLoaded', () => {
// --- Application State ---
let activeTab = 'numbers'; // 'numbers' | 'list' | 'colors' | 'dice' | 'coin'
let isAnimated = true;
let isSoundEnabled = true;
let isRolling = false;
let rollTimer = null;
let totalRollsCount = 0;
let historyList = [];
// Mode-specific state
let activeColorMode = 'single'; // 'single' | 'palette'
let activePaletteType = 'random';
let activeDiceSides = 6;
let currentColorData = null;
// Storage Keys
const STORAGE_KEY_ANIMATED = 'randomizer_animated';
const STORAGE_KEY_SOUND = 'randomizer_sound';
const STORAGE_KEY_HISTORY = 'randomizer_history';
const STORAGE_KEY_TOTAL_ROLLS = 'randomizer_total_rolls';
const STORAGE_KEY_SETTINGS = 'randomizer_user_settings';
const STORAGE_KEY_TAB_RESULTS = 'randomizer_tab_results';
// Per-tab latest results
let tabResults = {
numbers: null,
list: null,
colors: null,
dice: null,
coin: null
};
// --- DOM Elements ---
// Top Navbar
const toggleAnimated = document.getElementById('toggle-animated');
const btnToggleSound = document.getElementById('btn-toggle-sound');
const iconSoundOn = document.getElementById('icon-sound-on');
const iconSoundOff = document.getElementById('icon-sound-off');
const statCount = document.getElementById('stat-count');
const statTotalRolls = document.getElementById('stat-total-rolls');
const toastContainer = document.getElementById('toast-container');
const glowOrb1 = document.getElementById('glow-orb-1');
const glowOrb2 = document.getElementById('glow-orb-2');
// Tabs
const tabButtons = {
numbers: document.getElementById('tab-numbers'),
list: document.getElementById('tab-list'),
colors: document.getElementById('tab-colors'),
dice: document.getElementById('tab-dice'),
coin: document.getElementById('tab-coin')
};
const modeViews = {
numbers: document.getElementById('mode-numbers-view'),
list: document.getElementById('mode-list-view'),
colors: document.getElementById('mode-colors-view'),
dice: document.getElementById('mode-dice-view'),
coin: document.getElementById('mode-coin-view')
};
// Mode 1: Numbers DOM
const numMin = document.getElementById('num-min');
const numMax = document.getElementById('num-max');
const numCount = document.getElementById('num-count');
const checkUnique = document.getElementById('check-unique');
const checkDecimals = document.getElementById('check-decimals');
const numSort = document.getElementById('num-sort');
// Mode 2: List DOM
const listInput = document.getElementById('list-input');
const listItemsCount = document.getElementById('list-items-count');
const listPickCount = document.getElementById('list-pick-count');
const checkListRemove = document.getElementById('check-list-remove');
const btnListShuffle = document.getElementById('btn-list-shuffle');
const btnListClear = document.getElementById('btn-list-clear');
// Mode 3: Colors DOM
const btnColorSingle = document.getElementById('btn-color-single');
const btnColorPalette = document.getElementById('btn-color-palette');
const paletteTypeWrapper = document.getElementById('palette-type-wrapper');
const selectPaletteType = document.getElementById('select-palette-type');
const colorPreviewContainer = document.getElementById('color-preview-container');
// Mode 4: Dice DOM
const diceCount = document.getElementById('dice-count');
const diceModifier = document.getElementById('dice-modifier');
// Mode 5: Coin DOM
const coinWrapper = document.getElementById('coin-wrapper');
const coinDisc = document.getElementById('coin-disc');
let coinRotationY = 0;
// Live Result Stage DOM
const primaryResultText = document.getElementById('primary-result-text');
const resultBreakdown = document.getElementById('result-breakdown');
const btnCopyResult = document.getElementById('btn-copy-result');
const copyBtnLabel = document.getElementById('copy-btn-label');
const btnRoll = document.getElementById('btn-roll');
const btnRollText = document.getElementById('btn-roll-text');
// Right Sidebar (History) DOM
const historyEmpty = document.getElementById('history-empty');
const historyItemsList = document.getElementById('history-items-list');
const btnClearHistory = document.getElementById('btn-clear-history');
const btnCopyHistory = document.getElementById('btn-copy-history');
const copySummaryText = document.getElementById('copy-summary-text');
// Current latest raw result for easy copying
let latestResultRaw = '';
// =========================================================================
// Web Audio Synthesizer (Zero External Audio Files)
// =========================================================================
let audioCtx = null;
function getAudioContext() {
if (!audioCtx) {
const AudioContextClass = window.AudioContext || window.webkitAudioContext;
if (AudioContextClass) {
audioCtx = new AudioContextClass();
}
}
if (audioCtx && audioCtx.state === 'suspended') {
audioCtx.resume();
}
return audioCtx;
}
let clickNoiseBuffer = null;
function getClickNoiseBuffer(ctx) {
if (!clickNoiseBuffer) {
const length = Math.floor(ctx.sampleRate * 0.008);
clickNoiseBuffer = ctx.createBuffer(1, length, ctx.sampleRate);
const data = clickNoiseBuffer.getChannelData(0);
for (let i = 0; i < length; i++) {
data[i] = (Math.random() * 2 - 1) * Math.exp(-i / (length * 0.25));
}
}
return clickNoiseBuffer;
}
function playTickSound() {
if (!isSoundEnabled) return;
try {
const ctx = getAudioContext();
if (!ctx) return;
const now = ctx.currentTime;
// 1. Tactile percussive thud (pitch dropping sine 460Hz -> 65Hz in 12ms)
const osc = ctx.createOscillator();
const oscGain = ctx.createGain();
osc.type = 'sine';
osc.frequency.setValueAtTime(460, now);
osc.frequency.exponentialRampToValueAtTime(65, now + 0.012);
oscGain.gain.setValueAtTime(0.038, now);
oscGain.gain.exponentialRampToValueAtTime(0.0001, now + 0.014);
osc.connect(oscGain);
oscGain.connect(ctx.destination);
osc.start(now);
osc.stop(now + 0.015);
// 2. Crisp mechanical transient (filtered noise snap)
const noise = ctx.createBufferSource();
noise.buffer = getClickNoiseBuffer(ctx);
const filter = ctx.createBiquadFilter();
filter.type = 'bandpass';
filter.frequency.setValueAtTime(2600, now);
filter.Q.setValueAtTime(1.5, now);
const noiseGain = ctx.createGain();
noiseGain.gain.setValueAtTime(0.022, now);
noiseGain.gain.exponentialRampToValueAtTime(0.0001, now + 0.008);
noise.connect(filter);
filter.connect(noiseGain);
noiseGain.connect(ctx.destination);
noise.start(now);
noise.stop(now + 0.009);
} catch (e) {}
}
function playSuccessSound() {
if (!isSoundEnabled) return;
try {
const ctx = getAudioContext();
if (!ctx) return;
const now = ctx.currentTime;
// Chord: note 1
const osc1 = ctx.createOscillator();
const gain1 = ctx.createGain();
osc1.type = 'sine';
osc1.frequency.setValueAtTime(587.33, now); // D5
gain1.gain.setValueAtTime(0.06, now);
gain1.gain.exponentialRampToValueAtTime(0.001, now + 0.25);
osc1.connect(gain1);
gain1.connect(ctx.destination);
osc1.start(now);
osc1.stop(now + 0.25);
// Chord: note 2
const osc2 = ctx.createOscillator();
const gain2 = ctx.createGain();
osc2.type = 'sine';
osc2.frequency.setValueAtTime(880, now + 0.06); // A5
gain2.gain.setValueAtTime(0.08, now + 0.06);
gain2.gain.exponentialRampToValueAtTime(0.001, now + 0.35);
osc2.connect(gain2);
gain2.connect(ctx.destination);
osc2.start(now + 0.06);
osc2.stop(now + 0.35);
} catch (e) {}
}
// =========================================================================
// True Cryptographic Random Utilities
// =========================================================================
function cryptoRandomFloat() {
const array = new Uint32Array(1);
window.crypto.getRandomValues(array);
return array[0] / (0xFFFFFFFF + 1);
}
function cryptoRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
if (min > max) {
const temp = min;
min = max;
max = temp;
}
return Math.floor(cryptoRandomFloat() * (max - min + 1)) + min;
}
function cryptoShuffle(array) {
const arr = [...array];
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(cryptoRandomFloat() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
function adjustPrimaryFontSize(text) {
if (!text) return;
const len = String(text).length;
if (len > 35) {
primaryResultText.style.fontSize = '1.35rem';
} else if (len > 20) {
primaryResultText.style.fontSize = '1.8rem';
} else if (len > 12) {
primaryResultText.style.fontSize = '2.2rem';
} else {
primaryResultText.style.fontSize = '';
}
}
function escapeHtml(str) {
if (str === null || str === undefined) return '';
return String(str)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
// =========================================================================
// Mode Switching & Per-Tab Results
// =========================================================================
function renderTabResult(result) {
if (!result) {
primaryResultText.textContent = '';
primaryResultText.style.fontSize = '';
latestResultRaw = '';
resultBreakdown.innerHTML = '';
resultBreakdown.classList.add('hidden');
if (activeTab === 'coin') {
flipCoinVisual(true, false);
}
return;
}
latestResultRaw = result.raw || result.primary;
primaryResultText.classList.remove('animating');
primaryResultText.classList.remove('result-pop');
adjustPrimaryFontSize(result.primary);
primaryResultText.textContent = result.primary;
if (result.breakdown) {
resultBreakdown.innerHTML = `<span>${escapeHtml(result.breakdown)}</span>`;
resultBreakdown.classList.remove('hidden');
} else {
resultBreakdown.classList.add('hidden');
}
if (result.mode === 'color' && result.colorData) {
currentColorData = result.colorData;
const isPalette = Array.isArray(result.colorData);
setColorSubmode(isPalette ? 'palette' : 'single');
renderColorPreview();
} else if (result.mode === 'coin' && result.isHeads !== undefined) {
flipCoinVisual(result.isHeads, false);
}
}
function cancelRollAnimation() {
if (rollTimer) {
clearTimeout(rollTimer);
rollTimer = null;
}
isRolling = false;
btnRoll.classList.remove('rolling');
primaryResultText.classList.remove('animating');
}
function setActiveTab(tabKey) {
if (!tabButtons[tabKey] || !modeViews[tabKey]) return;
if (tabKey === activeTab && !isRolling) return;
if (isRolling) {
cancelRollAnimation();
}
activeTab = tabKey;
Object.keys(tabButtons).forEach(key => {
const btn = tabButtons[key];
const isTarget = key === tabKey;
btn.classList.toggle('active', isTarget);
btn.setAttribute('aria-selected', isTarget ? 'true' : 'false');
});
Object.keys(modeViews).forEach(key => {
modeViews[key].classList.toggle('hidden', key !== tabKey);
});
// Render this tab's last result (or emptiness if not rolled yet)
renderTabResult(tabResults[tabKey]);
// Persist active tab and settings
saveSettingsToStorage();
}
Object.keys(tabButtons).forEach(key => {
tabButtons[key].addEventListener('click', () => setActiveTab(key));
});
// =========================================================================
// Mode 1: Numbers Logic (Clean: Min n to Max m)
// =========================================================================
function getNumbersConfig() {
let min = parseFloat(numMin.value);
let max = parseFloat(numMax.value);
if (isNaN(min)) min = 1;
if (isNaN(max)) max = 10;
if (min > max) [min, max] = [max, min];
let count = parseInt(numCount.value, 10);
if (isNaN(count) || count < 1) count = 1;
if (count > 100) count = 100;
const unique = checkUnique.checked;
const isDecimal = checkDecimals.checked;
const sortType = numSort.value;
return { min, max, count, unique, isDecimal, sortType };
}
function generateNumbersResult() {
const { min, max, count, unique, isDecimal, sortType } = getNumbersConfig();
if (isDecimal) {
const scaledMin = Math.round(min * 100);
const scaledMax = Math.round(max * 100);
const possibleDecimals = scaledMax - scaledMin + 1;
if (unique && count > possibleDecimals) {
showToast(`Range only contains ${possibleDecimals} unique decimals!`);
return null;
}
let results = [];
if (unique) {
if (count === 1) {
results = [cryptoRandomInt(scaledMin, scaledMax) / 100];
} else if (possibleDecimals <= 2000) {
const pool = [];
for (let i = scaledMin; i <= scaledMax; i++) pool.push(i);
for (let i = 0; i < count; i++) {
const j = cryptoRandomInt(i, pool.length - 1);
const temp = pool[i];
pool[i] = pool[j];
pool[j] = temp;
results.push(pool[i] / 100);
}
} else {
const seen = new Set();
while (seen.size < count) {
seen.add(cryptoRandomInt(scaledMin, scaledMax));
}
results = Array.from(seen).map(n => n / 100);
}
} else {
for (let i = 0; i < count; i++) {
results.push(cryptoRandomInt(scaledMin, scaledMax) / 100);
}
}
if (sortType === 'asc') results.sort((a, b) => a - b);
if (sortType === 'desc') results.sort((a, b) => b - a);
const displayStr = results.map(n => n.toFixed(2)).join(', ');
return {
primary: displayStr,
raw: displayStr,
breakdown: results.length > 1 ? `Count: ${results.length} • Min: ${Math.min(...results).toFixed(2)} • Max: ${Math.max(...results).toFixed(2)} • Sum: ${results.reduce((a, b) => a + b, 0).toFixed(2)}` : null,
detailTitle: `${(scaledMin / 100).toFixed(2)} to ${(scaledMax / 100).toFixed(2)}`,
mode: 'numbers'
};
}
const intMin = Math.round(min);
const intMax = Math.round(max);
const possibleCount = intMax - intMin + 1;
if (unique && count > possibleCount) {
showToast(`Range only contains ${possibleCount} unique integers!`);
return null;
}
let results = [];
if (unique) {
if (count === 1) {
results = [cryptoRandomInt(intMin, intMax)];
} else if (possibleCount <= 2000) {
const pool = [];
for (let i = intMin; i <= intMax; i++) pool.push(i);
for (let i = 0; i < count; i++) {
const j = cryptoRandomInt(i, pool.length - 1);
const temp = pool[i];
pool[i] = pool[j];
pool[j] = temp;
results.push(pool[i]);
}
} else {
const seen = new Set();
while (seen.size < count) {
seen.add(cryptoRandomInt(intMin, intMax));
}
results = Array.from(seen);
}
} else {
for (let i = 0; i < count; i++) {
results.push(cryptoRandomInt(intMin, intMax));
}
}
if (sortType === 'asc') results.sort((a, b) => a - b);
if (sortType === 'desc') results.sort((a, b) => b - a);
const displayStr = results.join(', ');
return {
primary: results.length === 1 ? String(results[0]) : results.join(', '),
raw: displayStr,
breakdown: results.length > 1 ? `Count: ${results.length} • Min: ${Math.min(...results)} • Max: ${Math.max(...results)} • Sum: ${results.reduce((a, b) => a + b, 0)}` : null,
detailTitle: `${intMin} to ${intMax}`,
mode: 'numbers'
};
}
// =========================================================================
// Mode 2: List / Phrases Logic (Clean without sample clutter)
// =========================================================================
function getListItems() {
const text = listInput.value;
if (!text.trim()) return [];
let items = [];
if (text.includes('\n')) {
items = text.split('\n')
.map(line => line.trim())
.filter(line => line.length > 0);
} else if (text.includes(',')) {
items = text.split(',')
.map(item => item.trim())
.filter(item => item.length > 0);
} else {
items = [text.trim()];
}
return items;
}
function updateListCounter() {
const items = getListItems();
listItemsCount.textContent = `${items.length} ${items.length === 1 ? 'item' : 'items'}`;
}
listInput.addEventListener('input', () => {
updateListCounter();
saveSettingsToStorage();
});
btnListShuffle.addEventListener('click', () => {
const items = getListItems();
if (items.length <= 1) {
showToast('Enter at least 2 items to shuffle');
return;
}
const shuffled = cryptoShuffle(items);
listInput.value = shuffled.join('\n');
saveSettingsToStorage();
showToast('List shuffled randomly');
});
btnListClear.addEventListener('click', () => {
listInput.value = '';
updateListCounter();
saveSettingsToStorage();
showToast('List cleared');
});
function generateListResult(isFinal = true) {
const items = getListItems();
if (items.length === 0) {
if (isFinal) showToast('Please enter at least 1 item in the list!');
return null;
}
let pickCount = parseInt(listPickCount.value, 10);
if (isNaN(pickCount) || pickCount < 1) pickCount = 1;
if (pickCount > items.length) {
pickCount = items.length;
}
const shuffled = cryptoShuffle(items);
const picked = shuffled.slice(0, pickCount);
// If remove chosen is enabled and this is the final resolution, remove picked items from listInput
if (isFinal && checkListRemove.checked) {
const remaining = [...items];
for (const item of picked) {
const idx = remaining.indexOf(item);
if (idx !== -1) {
remaining.splice(idx, 1);
}
}
const separator = (!listInput.value.includes('\n') && listInput.value.includes(',')) ? ', ' : '\n';
listInput.value = remaining.join(separator);
updateListCounter();
saveSettingsToStorage();
}
const primary = picked.length === 1 ? picked[0] : picked.join(', ');
return {
primary: primary,
raw: picked.join(', '),
breakdown: picked.length > 1 ? `Picked ${picked.length} of ${items.length} items` : `Picked 1 of ${items.length} items`,
detailTitle: '',
mode: 'list'
};
}
// =========================================================================
// Mode 3: Color Studio Logic
// =========================================================================
function hslToRgb(h, s, l) {
h /= 360; s /= 100; l /= 100;
let r, g, b;
if (s === 0) {
r = g = b = l;
} else {
const hue2rgb = (p, q, t) => {
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1/6) return p + (q - p) * 6 * t;
if (t < 1/2) return q;
if (t < 2/3) return p + (q - p) * (2/3 - t) * 6;
return p;
};
const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
const p = 2 * l - q;
r = hue2rgb(p, q, h + 1/3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1/3);
}
return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
}
function rgbToHex(r, g, b) {
return '#' + [r, g, b].map(x => {
const hex = x.toString(16);
return hex.length === 1 ? '0' + hex : hex;
}).join('').toUpperCase();
}
function getLuminance(r, g, b) {
const a = [r, g, b].map(v => {
v /= 255;
return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
});
return a[0] * 0.2126 + a[1] * 0.7152 + a[2] * 0.0722;
}
function createColorObject(h, s, l) {
const [r, g, b] = hslToRgb(h, s, l);
const hex = rgbToHex(r, g, b);
const luminance = getLuminance(r, g, b);
const textColor = luminance > 0.4 ? '#0d1117' : '#ffffff';
return {
hex,
rgb: `rgb(${r}, ${g}, ${b})`,
hsl: `hsl(${Math.round(h)}, ${Math.round(s)}%, ${Math.round(l)}%)`,
textColor,
r, g, b, h, s, l
};
}
function generateRandomColor() {
const h = cryptoRandomFloat() * 360;
const s = 65 + cryptoRandomFloat() * 35;
const l = 40 + cryptoRandomFloat() * 30;
return createColorObject(h, s, l);
}
function generateColorPalette(type) {
const baseH = cryptoRandomFloat() * 360;
const colors = [];
if (type === 'pastel') {
for (let i = 0; i < 5; i++) {
const h = (baseH + i * 45) % 360;
colors.push(createColorObject(h, 60 + cryptoRandomFloat() * 15, 75 + cryptoRandomFloat() * 10));
}
} else if (type === 'monochrome') {
for (let i = 0; i < 5; i++) {
const l = 20 + i * 15;
colors.push(createColorObject(baseH, 70, l));
}
} else if (type === 'complementary') {
const compH = (baseH + 180) % 360;
colors.push(createColorObject(baseH, 80, 50));
colors.push(createColorObject(baseH, 60, 65));
colors.push(createColorObject((baseH + 30) % 360, 70, 55));
colors.push(createColorObject(compH, 80, 50));
colors.push(createColorObject((compH + 25) % 360, 70, 60));
} else if (type === 'triadic') {
const h2 = (baseH + 120) % 360;
const h3 = (baseH + 240) % 360;
colors.push(createColorObject(baseH, 75, 52));
colors.push(createColorObject(baseH, 60, 70));
colors.push(createColorObject(h2, 75, 52));
colors.push(createColorObject(h3, 75, 52));
colors.push(createColorObject(h3, 60, 70));
} else {
// Random mix
for (let i = 0; i < 5; i++) {
colors.push(generateRandomColor());
}
}
return colors;
}
function setColorSubmode(mode) {
activeColorMode = mode;
if (mode === 'palette') {
btnColorPalette.classList.add('active');
btnColorSingle.classList.remove('active');
paletteTypeWrapper.classList.remove('hidden');
} else {
btnColorSingle.classList.add('active');
btnColorPalette.classList.remove('active');
paletteTypeWrapper.classList.add('hidden');
}
renderColorPreview();
}
btnColorSingle.addEventListener('click', () => {
if (activeColorMode === 'single') return;
setColorSubmode('single');
saveSettingsToStorage();
if (activeTab === 'colors') {
executeRoll();
}
});
btnColorPalette.addEventListener('click', () => {
if (activeColorMode === 'palette') return;
setColorSubmode('palette');
saveSettingsToStorage();
if (activeTab === 'colors') {
executeRoll();
}
});
selectPaletteType.addEventListener('change', () => {
activePaletteType = selectPaletteType.value;
saveSettingsToStorage();
if (activeTab === 'colors' && activeColorMode === 'palette') {
executeRoll();
}
});
function renderColorPreview() {
if (!currentColorData) return;
colorPreviewContainer.innerHTML = '';
if (activeColorMode === 'single') {
const c = Array.isArray(currentColorData) ? currentColorData[0] : currentColorData;
const card = document.createElement('div');
card.className = 'single-color-card';
card.style.backgroundColor = c.hex;
card.style.color = c.textColor;
card.title = 'Click to copy HEX code';
card.innerHTML = `
<span class="color-hex-main">${c.hex}</span>
<div class="color-values-row">
<span class="color-code-pill">${c.rgb}</span>
<span class="color-code-pill">${c.hsl}</span>
</div>
`;
card.addEventListener('click', () => {
copyTextToClipboard(c.hex, `Copied ${c.hex}`);
});
colorPreviewContainer.appendChild(card);
// Sync ambient background glow with generated color
if (glowOrb1) glowOrb1.style.background = `radial-gradient(circle, ${c.hex} 0%, transparent 70%)`;
} else {
const colors = Array.isArray(currentColorData) ? currentColorData : generateColorPalette(activePaletteType);
currentColorData = colors;
const grid = document.createElement('div');
grid.className = 'palette-grid';
colors.forEach(col => {
const swatch = document.createElement('div');
swatch.className = 'palette-swatch';
swatch.style.backgroundColor = col.hex;
swatch.style.color = col.textColor;
swatch.title = `Click to copy ${col.hex}`;
swatch.innerHTML = `
<span class="palette-swatch-hex">${col.hex}</span>
`;
swatch.addEventListener('click', (e) => {
e.stopPropagation();
copyTextToClipboard(col.hex, `Copied ${col.hex}`);
});
grid.appendChild(swatch);
});
colorPreviewContainer.appendChild(grid);
}
}
function generateColorResult(isRollAction = true) {
if (activeColorMode === 'single') {
const color = generateRandomColor();
currentColorData = color;
renderColorPreview();
return {
primary: color.hex,
raw: `${color.hex}, ${color.rgb}, ${color.hsl}`,
breakdown: `${color.rgb}, ${color.hsl}`,
detailTitle: 'Single Color',
mode: 'color',
colorData: color
};
} else {
const palette = generateColorPalette(activePaletteType);
currentColorData = palette;
renderColorPreview();
const hexList = palette.map(c => c.hex).join(', ');
return {
primary: hexList,
raw: hexList,
breakdown: `5-Color Palette (${activePaletteType.toUpperCase()})`,
detailTitle: `Color Palette (${activePaletteType})`,
mode: 'color',
colorData: palette
};
}
}
// =========================================================================
// Mode 4: Dice Logic
// =========================================================================
function setDiceSides(sides) {
activeDiceSides = sides;
document.querySelectorAll('.dice-type-btn').forEach(b => {
const s = parseInt(b.getAttribute('data-sides'), 10);
b.classList.toggle('active', s === sides);
});
}
document.querySelectorAll('.dice-type-btn').forEach(btn => {
btn.addEventListener('click', () => {
const sides = parseInt(btn.getAttribute('data-sides'), 10) || 6;
setDiceSides(sides);
saveSettingsToStorage();
});
});
function generateDiceResult() {
let count = parseInt(diceCount.value, 10);
if (isNaN(count) || count < 1) count = 1;
if (count > 12) count = 12;
let mod = parseInt(diceModifier.value, 10);
if (isNaN(mod)) mod = 0;
const rolls = [];
for (let i = 0; i < count; i++) {
rolls.push(cryptoRandomInt(1, activeDiceSides));
}
const sum = rolls.reduce((a, b) => a + b, 0);
const total = sum + mod;
const modStr = mod > 0 ? ` + ${mod}` : (mod < 0 ? ` - ${Math.abs(mod)}` : '');
const breakdownStr = count > 1 || mod !== 0
? `Rolls: [${rolls.join(', ')}]${modStr} = Total: ${total}`
: `Single D${activeDiceSides}`;
return {
primary: String(total),
raw: `${total} (${count}d${activeDiceSides}${modStr})`,
breakdown: breakdownStr,
detailTitle: `${count}d${activeDiceSides}${modStr}`,
mode: 'dice'
};
}
// =========================================================================
// Mode 5: Coin Flip Logic
// =========================================================================
if (coinWrapper) {
coinWrapper.addEventListener('click', () => {
executeRoll();
});
}
function flipCoinVisual(isHeads, animated = true) {
if (!coinDisc || !coinWrapper) return;
if (!animated) {
coinRotationY = isHeads ? 0 : 180;
coinDisc.style.transition = 'none';
coinDisc.style.transform = `rotateY(${coinRotationY}deg)`;
return;
}
const currentFacingHeads = (Math.round(coinRotationY / 180) % 2) === 0;
let extra = 1800;
if (isHeads) {
extra += currentFacingHeads ? 0 : 180;
} else {
extra += currentFacingHeads ? 180 : 0;
}
coinRotationY += extra;
coinDisc.style.transition = 'transform 0.65s cubic-bezier(0.18, 0.85, 0.3, 1.15)';
coinDisc.style.transform = `rotateY(${coinRotationY}deg)`;
coinWrapper.classList.remove('coin-tossing');
void coinWrapper.offsetWidth;
coinWrapper.classList.add('coin-tossing');
}
function generateCoinResult() {
const isHeads = cryptoRandomFloat() < 0.5;
const label = isHeads ? 'Heads' : 'Tails';
return {
primary: label,
raw: label,
breakdown: '',
detailTitle: '',
mode: 'coin',
isHeads: isHeads
};
}
// =========================================================================
// Core Roll Engine & The 6-Tick Animated Deceleration
// =========================================================================
function getCandidateResult(tabKey = activeTab, isFinal = true) {
switch (tabKey) {
case 'numbers': return generateNumbersResult();
case 'list': return generateListResult(isFinal);
case 'colors': return generateColorResult(true);
case 'dice': return generateDiceResult();
case 'coin': return generateCoinResult();
default: return generateNumbersResult();
}
}
function executeRoll() {
if (isRolling) return;
const rollTab = activeTab;
// Verify validity before starting animation without side effects
const initialCheck = getCandidateResult(rollTab, false);
if (!initialCheck) return;
isRolling = true;
btnRoll.classList.add('rolling');
if (!isAnimated) {
// Instant generation (Animated OFF)
try {
const finalResult = getCandidateResult(rollTab, true);
if (rollTab === 'coin' && finalResult.isHeads !== undefined) {
flipCoinVisual(finalResult.isHeads, false);
}
displayFinalResult(finalResult, rollTab);
} catch (err) {
console.error("Roll execution error:", err);
} finally {
isRolling = false;
btnRoll.classList.remove('rolling');
}
return;
}
// =====================================================================
// ANIMATED MODE: Exactly 6 rapid intermediate random ticks, then 7th final
// =====================================================================
const intermediateDelays = [45, 60, 80, 105, 135, 175]; // Easing deceleration
let tick = 0;
let targetCoinResult = null;
if (rollTab === 'coin') {
targetCoinResult = generateCoinResult();
flipCoinVisual(targetCoinResult.isHeads, true);
}
function runNextTick() {
// If user switched away or roll was cancelled, stop immediately
if (!isRolling || activeTab !== rollTab) {
cancelRollAnimation();
return;
}
if (tick < 6) {
// Ticks 1 to 6: Intermediate random values (non-final)
if (targetCoinResult) {
primaryResultText.textContent = 'Flipping...';
primaryResultText.classList.add('animating');
playTickSound();
} else {
const intermediate = getCandidateResult(rollTab, false);
if (intermediate) {
adjustPrimaryFontSize(intermediate.primary);
primaryResultText.textContent = intermediate.primary;
primaryResultText.classList.add('animating');
playTickSound();
}
}
const delay = intermediateDelays[tick];
tick++;
rollTimer = setTimeout(runNextTick, delay);
} else {
// Tick 7: Final Chosen Value Lock-in!
try {
const finalResult = targetCoinResult || getCandidateResult(rollTab, true);
displayFinalResult(finalResult, rollTab);
} catch (err) {
console.error("Roll execution error:", err);
} finally {
isRolling = false;
rollTimer = null;
btnRoll.classList.remove('rolling');
}
}
}