-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCadet_Randomizer.html
More file actions
1084 lines (947 loc) · 40.1 KB
/
Copy pathCadet_Randomizer.html
File metadata and controls
1084 lines (947 loc) · 40.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Cadet Randomizer</title>
<style>
:root{
--bg:#0B0E14;
--bg-2:#10141D;
--panel:#161B26;
--panel-2:#1C2231;
--line:#262E3E;
--line-soft:#1E2534;
--gold:#C8A34E;
--gold-hi:#EDD08A;
--gold-dim:#8A7133;
--text:#E7EAF0;
--muted:#8B93A5;
--muted-2:#5E6779;
--shadow:0 18px 50px rgba(0,0,0,.55);
}
*{box-sizing:border-box}
html,body{height:100%}
body{
margin:0;
background:
radial-gradient(1100px 700px at 50% -12%, #1A2233 0%, rgba(26,34,51,0) 62%),
linear-gradient(180deg, var(--bg-2) 0%, var(--bg) 55%, #080A0F 100%);
color:var(--text);
font-family:system-ui,-apple-system,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;
-webkit-font-smoothing:antialiased;
min-height:100%;
display:flex;
flex-direction:column;
align-items:center;
}
.shell{
width:100%;max-width:1080px;min-height:100vh;padding:18px 22px 20px;
display:flex;flex-direction:column;gap:15px;
}
/* ---------- header ---------- */
header{display:flex;align-items:flex-end;justify-content:space-between;gap:20px;flex-wrap:wrap}
.brand{display:flex;flex-direction:column;gap:5px;align-items:stretch}
.brand h1{
margin:0;font-size:clamp(26px,3.1vw,38px);font-weight:800;letter-spacing:.26em;
text-transform:uppercase;white-space:nowrap;
background:linear-gradient(180deg,#FFF6DF 0%,var(--gold) 78%);
-webkit-background-clip:text;background-clip:text;color:transparent;
}
.brand .rule{height:2px;width:100%;background:linear-gradient(90deg,var(--gold),rgba(200,163,78,0))}
.brand p{margin:2px 0 0;font-size:12px;color:var(--muted-2);letter-spacing:.09em;text-transform:uppercase}
.file-chip{
display:flex;align-items:center;gap:12px;padding:9px 9px 9px 14px;
background:var(--panel);border:1px solid var(--line);border-radius:11px;font-size:12.5px;color:var(--muted);
max-width:100%;
}
.file-chip .fname{color:var(--text);font-weight:600;max-width:290px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.file-chip .sub{color:var(--muted-2);font-size:11px}
/* ---------- controls ---------- */
.controls{
display:flex;align-items:center;gap:14px;flex-wrap:wrap;
background:linear-gradient(180deg,var(--panel) 0%,#131824 100%);
border:1px solid var(--line);border-radius:14px;padding:14px 16px;box-shadow:var(--shadow);
}
.ctl{display:flex;flex-direction:column;gap:6px}
.ctl > label{font-size:10.5px;letter-spacing:.15em;text-transform:uppercase;color:var(--muted-2);font-weight:700}
select{
appearance:none;background:var(--panel-2);color:var(--text);
border:1px solid var(--line);border-radius:9px;padding:10px 38px 10px 13px;
font-size:14px;font-weight:600;font-family:inherit;min-width:246px;cursor:pointer;
background-image:linear-gradient(45deg,transparent 50%,var(--gold) 50%),linear-gradient(135deg,var(--gold) 50%,transparent 50%);
background-position:calc(100% - 19px) calc(50% + 1px),calc(100% - 14px) calc(50% + 1px);
background-size:5px 5px,5px 5px;background-repeat:no-repeat;
}
select:focus{outline:none;border-color:var(--gold-dim)}
select:disabled{opacity:.45;cursor:default}
.seg{display:flex;background:var(--panel-2);border:1px solid var(--line);border-radius:9px;padding:3px;gap:3px}
.seg button{
background:transparent;border:0;color:var(--muted);font-family:inherit;font-size:12.5px;font-weight:700;
letter-spacing:.08em;text-transform:uppercase;padding:8px 15px;border-radius:6px;cursor:pointer;transition:.16s;
}
.seg button:hover:not(.on){color:var(--text)}
.seg button.on{background:linear-gradient(180deg,#2C3448,#232A3B);color:var(--gold-hi);box-shadow:inset 0 0 0 1px rgba(200,163,78,.3)}
.btn{
background:var(--panel-2);color:var(--text);border:1px solid var(--line);border-radius:9px;
padding:10px 15px;font-family:inherit;font-size:12.5px;font-weight:600;cursor:pointer;transition:.16s;white-space:nowrap;
}
.btn:hover{border-color:var(--gold-dim);color:var(--gold-hi)}
.spacer{flex:1 1 auto;min-width:0}
.count{font-size:12px;color:var(--muted-2);letter-spacing:.04em;white-space:nowrap}
.count b{color:var(--gold);font-weight:700}
/* ---------- stage ---------- */
.stage{
position:relative;width:100%;flex:1 1 auto;min-height:300px;
background:radial-gradient(70% 90% at 50% 42%,#161C2A 0%,#0C1017 74%);
border:1px solid var(--line-soft);border-radius:18px;overflow:hidden;box-shadow:var(--shadow);
}
/* split-flap sizes the stage to the board, so there is no dead space around the tiles */
.stage.snug{flex:0 0 auto;min-height:0}
.stage canvas{display:block;width:100%;height:100%}
.stage .empty{
position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;
gap:14px;text-align:center;padding:30px;pointer-events:none;
}
.stage .empty .big{font-size:15px;color:var(--muted);font-weight:600;letter-spacing:.03em}
.stage .empty .small{font-size:12.5px;color:var(--muted-2);max-width:430px;line-height:1.65}
.stage .empty .btn{pointer-events:auto}
.hidden{display:none !important}
/* ---------- action row ---------- */
.action{display:flex;align-items:center;gap:22px;flex-wrap:wrap;justify-content:center}
.go{
position:relative;border:0;cursor:pointer;font-family:inherit;
padding:16px 58px;border-radius:12px;font-size:16px;font-weight:800;letter-spacing:.22em;text-transform:uppercase;
color:#1A1305;background:linear-gradient(180deg,var(--gold-hi) 0%,var(--gold) 52%,#9C7C2E 100%);
box-shadow:0 12px 30px rgba(200,163,78,.24),inset 0 1px 0 rgba(255,255,255,.5);
transition:transform .12s,box-shadow .18s,filter .18s;
}
.go:hover:not(:disabled){transform:translateY(-1px);box-shadow:0 16px 38px rgba(200,163,78,.34),inset 0 1px 0 rgba(255,255,255,.55)}
.go:active:not(:disabled){transform:translateY(1px)}
.go:disabled{filter:grayscale(.85) brightness(.62);cursor:default;box-shadow:none}
.hint{font-size:11.5px;color:var(--muted-2);letter-spacing:.06em}
.hint kbd{
background:var(--panel-2);border:1px solid var(--line);border-bottom-width:2px;border-radius:5px;
padding:2px 7px;font-family:inherit;font-size:10.5px;color:var(--muted);
}
/* ---------- winner ---------- */
.winner{
min-height:76px;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:6px;
opacity:0;transform:translateY(9px);transition:opacity .45s,transform .45s;
}
.winner.show{opacity:1;transform:none}
.winner .cap{font-size:10.5px;letter-spacing:.3em;text-transform:uppercase;color:var(--gold-dim);font-weight:700}
.winner .name{
font-size:clamp(28px,5.4vw,48px);font-weight:800;letter-spacing:.03em;line-height:1.08;text-align:center;
background:linear-gradient(180deg,#FFFCF3 0%,var(--gold-hi) 55%,var(--gold) 100%);
-webkit-background-clip:text;background-clip:text;color:transparent;
text-shadow:0 0 46px rgba(200,163,78,.28);
}
.winner .meta{font-size:12.5px;color:var(--muted-2);letter-spacing:.14em;text-transform:uppercase}
/* ---------- drop overlay ---------- */
.drop{
position:fixed;inset:0;z-index:50;display:none;align-items:center;justify-content:center;
background:rgba(8,10,15,.86);backdrop-filter:blur(3px);
}
.drop.on{display:flex}
.drop .box{
border:2px dashed var(--gold-dim);border-radius:18px;padding:56px 76px;text-align:center;
color:var(--gold-hi);font-size:16px;font-weight:700;letter-spacing:.14em;text-transform:uppercase;
}
.err{
background:rgba(180,60,60,.1);border:1px solid rgba(200,80,80,.32);color:#F0B3B3;
border-radius:10px;padding:11px 15px;font-size:13px;line-height:1.55;
}
footer{font-size:11px;color:#454C5C;text-align:center;letter-spacing:.05em;line-height:1.8}
:focus-visible{outline:2px solid var(--gold);outline-offset:2px;border-radius:4px}
</style>
</head>
<body>
<div class="shell">
<header>
<div class="brand">
<h1>Cadet Randomizer</h1>
<div class="rule"></div>
<p>AI105 · Section Cold-Call</p>
</div>
<div class="file-chip" id="fileChip">
<div>
<div class="fname" id="fileName">No roster loaded</div>
<div class="sub" id="fileSub">Drop an .xlsx anywhere on this page</div>
</div>
<button class="btn" id="loadBtn">Load roster…</button>
</div>
</header>
<div id="errBox" class="err hidden"></div>
<div class="controls">
<div class="ctl">
<label for="sectionSel">Section</label>
<select id="sectionSel" disabled><option>— no roster loaded —</option></select>
</div>
<div class="ctl">
<label>Visual</label>
<div class="seg" id="modeSeg">
<button data-mode="flap" class="on">Split‑Flap</button>
<button data-mode="wheel">Spinning Wheel</button>
</div>
</div>
<div class="spacer"></div>
<div class="count" id="countLbl"></div>
</div>
<div class="stage" id="stage">
<canvas id="cv"></canvas>
<div class="empty" id="emptyState">
<div class="big">No roster loaded</div>
<div class="small">Load your roster workbook — any <b>.xlsx</b> with the same Roster tab layout. Nothing leaves this machine; the file is read entirely in the browser.</div>
<button class="btn" id="loadBtn2">Choose Excel file…</button>
</div>
</div>
<div class="action">
<button class="go" id="goBtn" disabled>Randomize</button>
<div class="hint">Press <kbd>Space</kbd> to draw</div>
</div>
<div class="winner" id="winner">
<div class="cap">Selected</div>
<div class="name" id="winName"></div>
<div class="meta" id="winMeta"></div>
</div>
<footer>
Reads rows 3–21 of each <i>Roster</i> tab · runs fully offline · no data is uploaded
</footer>
</div>
<div class="drop" id="dropOverlay"><div class="box">Drop the roster workbook</div></div>
<input type="file" id="fileInput" accept=".xlsx,.xlsm" style="display:none">
<script>
"use strict";
/* =====================================================================
1. XLSX READER — zero dependencies
A .xlsx is a ZIP of XML. We walk the ZIP central directory by hand and
inflate entries with the built-in DecompressionStream, then parse the
XML with DOMParser.
===================================================================== */
const SIG_EOCD = 0x06054b50;
const SIG_CDIR = 0x02014b50;
const SIG_LOCAL = 0x04034b50;
async function unzip(buf){
const u8 = new Uint8Array(buf), dv = new DataView(buf);
let eocd = -1;
const floor = Math.max(0, u8.length - 66000);
for(let i = u8.length - 22; i >= floor; i--){
if(dv.getUint32(i, true) === SIG_EOCD){ eocd = i; break; }
}
if(eocd < 0) throw new Error("This does not look like an .xlsx file (no ZIP directory found).");
const count = dv.getUint16(eocd + 10, true);
const cdOff = dv.getUint32(eocd + 16, true);
if(count === 0xFFFF || cdOff === 0xFFFFFFFF)
throw new Error("ZIP64 workbooks are not supported. Re-save the file from Excel.");
const entries = {};
let p = cdOff;
for(let i = 0; i < count; i++){
if(dv.getUint32(p, true) !== SIG_CDIR) throw new Error("The workbook's ZIP directory is corrupt.");
const method = dv.getUint16(p + 10, true);
const compSize = dv.getUint32(p + 20, true);
const nameLen = dv.getUint16(p + 28, true);
const extraLen = dv.getUint16(p + 30, true);
const cmtLen = dv.getUint16(p + 32, true);
const localOff = dv.getUint32(p + 42, true);
const name = new TextDecoder().decode(u8.subarray(p + 46, p + 46 + nameLen));
entries[name] = { method, compSize, localOff };
p += 46 + nameLen + extraLen + cmtLen;
}
return {
has: n => Object.prototype.hasOwnProperty.call(entries, n),
async text(n){
const e = entries[n];
if(!e) throw new Error("Missing part in workbook: " + n);
if(dv.getUint32(e.localOff, true) !== SIG_LOCAL) throw new Error("Corrupt ZIP entry: " + n);
// the local header's name/extra lengths can differ from the central ones
const nameLen = dv.getUint16(e.localOff + 26, true);
const extraLen = dv.getUint16(e.localOff + 28, true);
const start = e.localOff + 30 + nameLen + extraLen;
const data = u8.subarray(start, start + e.compSize);
if(e.method === 0) return new TextDecoder().decode(data);
if(e.method !== 8) throw new Error("Unsupported ZIP compression in workbook (method " + e.method + ").");
const stream = new Blob([data]).stream().pipeThrough(new DecompressionStream("deflate-raw"));
return await new Response(stream).text();
}
};
}
const XML = new DOMParser();
function parseXML(s, what){
const doc = XML.parseFromString(s, "application/xml");
if(doc.getElementsByTagName("parsererror").length) throw new Error("Could not read the workbook's " + what + ".");
return doc;
}
const tag = (node, name) => Array.from(node.getElementsByTagName("*")).filter(el => el.localName === name);
const colOf = ref => (ref.match(/^[A-Z]+/) || ["A"])[0];
const rowOf = ref => parseInt((ref.match(/\d+$/) || ["0"])[0], 10);
const FIRST_DATA_ROW = 3; // row 1 = SECTION:, row 2 = column headers
const LAST_DATA_ROW = 21; // row 22 begins the attendance-summary table
async function readWorkbook(file){
const zip = await unzip(await file.arrayBuffer());
const wb = parseXML(await zip.text("xl/workbook.xml"), "workbook");
const rels = parseXML(await zip.text("xl/_rels/workbook.xml.rels"), "relationships");
const relMap = {};
for(const r of tag(rels, "Relationship")) relMap[r.getAttribute("Id")] = r.getAttribute("Target");
// shared string table
const shared = [];
if(zip.has("xl/sharedStrings.xml")){
const sst = parseXML(await zip.text("xl/sharedStrings.xml"), "shared strings");
for(const si of tag(sst, "si")){
let s = "";
for(const t of tag(si, "t")){
if(t.parentNode && t.parentNode.localName === "rPh") continue; // phonetic guides
s += t.textContent || "";
}
shared.push(s);
}
}
const sections = [];
for(const sh of tag(wb, "sheet")){
const rid = sh.getAttributeNS("http://schemas.openxmlformats.org/officeDocument/2006/relationships", "id")
|| sh.getAttribute("r:id");
let target = relMap[rid];
if(!target) continue;
target = target.replace(/^\/?xl\//, "").replace(/^\//, "");
const path = "xl/" + target;
if(!zip.has(path)) continue;
const sheetName = sh.getAttribute("name") || "";
const ws = parseXML(await zip.text(path), "sheet “" + sheetName + "”");
// pull the cells we care about into a { "A3": "<last name>", ... } map
const cells = {};
for(const c of tag(ws, "c")){
const ref = c.getAttribute("r"); if(!ref) continue;
const r = rowOf(ref);
if(r > LAST_DATA_ROW) continue;
const t = c.getAttribute("t");
let val = null;
if(t === "inlineStr"){
val = tag(c, "t").map(n => n.textContent || "").join("");
}else{
const v = tag(c, "v")[0];
if(!v) continue;
val = (t === "s") ? (shared[parseInt(v.textContent, 10)] ?? "") : (v.textContent || "");
}
if(val != null) cells[colOf(ref) + r] = String(val).trim();
}
const label = (cells["A1"] || "").toUpperCase().startsWith("SECTION") ? (cells["B1"] || "") : "";
const cadets = [];
for(let r = FIRST_DATA_ROW; r <= LAST_DATA_ROW; r++){
const last = cells["A" + r] || "", first = cells["B" + r] || "";
if(!last && !first) continue; // blank row
if(/^last name$/i.test(last)) break; // hit the next table's header
cadets.push({ last, first, mi: cells["C" + r] || "", co: cells["F" + r] || "" });
}
if(/roster/i.test(sheetName) || cadets.length) sections.push({ sheet: sheetName, label, cadets });
}
if(!sections.length) throw new Error("No Roster tabs were found in that workbook.");
return { fileName: file.name, savedAt: Date.now(), sections };
}
/* =====================================================================
2. APP STATE
===================================================================== */
const $ = id => document.getElementById(id);
const stage = $("stage"), cv = $("cv"), ctx = cv.getContext("2d");
const app = {
book: null,
sectionIdx: 0,
mode: "flap",
spinning: false,
winner: null,
W: 0, H: 0
};
const roster = () => (app.book && app.book.sections[app.sectionIdx]) ? app.book.sections[app.sectionIdx].cadets : [];
const sectionMeta = () => {
const s = app.book && app.book.sections[app.sectionIdx];
if(!s) return "";
return s.label ? s.label : s.sheet.replace(/_?roster$/i, "");
};
const STORE_KEY = "cadet-randomizer-v1";
function saveCache(book){ try{ localStorage.setItem(STORE_KEY, JSON.stringify(book)); }catch(e){} }
function loadCache(){
try{
const raw = localStorage.getItem(STORE_KEY);
if(!raw) return null;
const b = JSON.parse(raw);
return (b && Array.isArray(b.sections) && b.sections.length) ? b : null;
}catch(e){ return null; }
}
/* =====================================================================
3. CANVAS PLUMBING
===================================================================== */
function resize(){
const r = stage.getBoundingClientRect();
const dpr = Math.min(window.devicePixelRatio || 1, 2);
app.W = r.width; app.H = r.height;
cv.width = Math.round(r.width * dpr);
cv.height = Math.round(r.height * dpr);
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
if(app.mode === "flap") flap.layout();
draw(performance.now());
}
// The wheel wants every pixel of leftover height; the split-flap board wants only as
// much as the tiles need, so the page still fits on one screen.
function applyStageSizing(){
const names = roster();
if(app.mode === "flap" && names.length){
flap.setCols(names);
stage.classList.add("snug");
stage.style.height = Math.round(flap.stageHeightFor(stage.getBoundingClientRect().width)) + "px";
}else{
stage.classList.remove("snug");
stage.style.height = "";
}
resize();
}
window.addEventListener("resize", applyStageSizing);
function roundRect(c, x, y, w, h, r){
r = Math.min(r, w / 2, h / 2);
c.beginPath();
c.moveTo(x + r, y);
c.arcTo(x + w, y, x + w, y + h, r);
c.arcTo(x + w, y + h, x, y + h, r);
c.arcTo(x, y + h, x, y, r);
c.arcTo(x, y, x + w, y, r);
c.closePath();
}
function fitText(c, text, maxW){
if(c.measureText(text).width <= maxW) return text;
let s = text;
while(s.length > 1 && c.measureText(s + "…").width > maxW) s = s.slice(0, -1);
return s + "…";
}
const easeOutQuart = t => 1 - Math.pow(1 - t, 4);
const TAU = Math.PI * 2;
const norm = a => ((a % TAU) + TAU) % TAU;
// respect the OS "reduce motion" setting: same outcome, much shorter build-up
const reduceMotion = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
const MOTION = reduceMotion ? 0.22 : 1;
/* =====================================================================
4. CONFETTI
===================================================================== */
const confetti = {
bits: [],
burst(x, y, count){
const colors = ["#EDD08A","#C8A34E","#FFFFFF","#8FA6C4","#E8B4B8","#9CC2A8"];
for(let i = 0; i < (count || 220); i++){
const a = Math.random() * TAU, sp = 4 + Math.random() * 16;
this.bits.push({
x: x + (Math.random() - .5) * 60,
y,
vx: Math.cos(a) * sp,
vy: Math.sin(a) * sp - 7.5,
w: 4 + Math.random() * 7,
h: 7 + Math.random() * 11,
rot: Math.random() * TAU,
vr: (Math.random() - .5) * .38,
col: colors[(Math.random() * colors.length) | 0],
life: 1
});
}
},
step(){
for(const b of this.bits){
b.vy += .30; b.vx *= .992; b.x += b.vx; b.y += b.vy; b.rot += b.vr;
if(b.y > app.H * .62) b.life -= .016;
}
this.bits = this.bits.filter(b => b.life > 0 && b.y < app.H + 60);
},
draw(c){
for(const b of this.bits){
c.save();
c.globalAlpha = Math.max(0, Math.min(1, b.life));
c.translate(b.x, b.y); c.rotate(b.rot);
c.fillStyle = b.col;
c.fillRect(-b.w / 2, -b.h / 2, b.w, b.h * Math.abs(Math.cos(b.rot * 1.6)));
c.restore();
}
},
clear(){ this.bits.length = 0; }
};
/* =====================================================================
5. VISUAL A — SPINNING WHEEL
===================================================================== */
const wheel = {
angle: -Math.PI / 2,
from: 0, to: 0, t0: 0, dur: 5200,
active: false,
kick: 0, lastTick: 0,
glow: 0,
segColor(i){
const hue = (i * 137.508) % 360; // golden angle → no two neighbours alike
return "hsl(" + hue.toFixed(1) + ",26%," + (i % 2 ? 21 : 27) + "%)";
},
start(winnerIdx, n){
const seg = TAU / n;
// put the middle of the winning wedge under the pointer (12 o'clock = -PI/2),
// nudged off-centre a little so it doesn't land dead centre every time
const jitter = (Math.random() - .5) * seg * .66;
let want = -Math.PI / 2 - (winnerIdx + .5) * seg + jitter;
const cur = this.angle;
want = cur + norm(want - cur) + TAU * (reduceMotion ? 1 : 5 + Math.floor(Math.random() * 3));
this.from = cur; this.to = want; this.t0 = performance.now();
this.dur = (5000 + Math.random() * 900) * MOTION;
this.active = true; this.glow = 0;
this.lastTick = Math.floor(norm(-Math.PI / 2 - cur) / seg);
},
step(now, n){
if(!this.active) return false;
const t = Math.min(1, (now - this.t0) / this.dur);
this.angle = this.from + (this.to - this.from) * easeOutQuart(t);
const seg = TAU / n;
const idx = Math.floor(norm(-Math.PI / 2 - this.angle) / seg);
if(idx !== this.lastTick){ this.kick = 1; this.lastTick = idx; }
this.kick *= .84;
if(t >= 1){ this.active = false; this.angle = this.to; return true; }
return false;
},
draw(c, now, names, winnerIdx){
const cx = app.W / 2, cy = app.H / 2 + 6;
const R = Math.min(app.W, app.H) / 2 - 42;
const n = names.length;
if(n === 0 || R <= 20) return;
const seg = TAU / n;
const hubR = Math.max(30, R * .17);
if(!this.active && winnerIdx != null) this.glow = Math.min(1, this.glow + .05);
// outer bezel
c.save();
c.beginPath(); c.arc(cx, cy, R + 13, 0, TAU);
const bez = c.createLinearGradient(cx - R, cy - R, cx + R, cy + R);
bez.addColorStop(0, "#3E4759"); bez.addColorStop(.42, "#1A1F2B");
bez.addColorStop(.62, "#4A5468"); bez.addColorStop(1, "#161A24");
c.fillStyle = bez; c.shadowColor = "rgba(0,0,0,.6)"; c.shadowBlur = 28; c.shadowOffsetY = 10;
c.fill(); c.restore();
// wedges
for(let i = 0; i < n; i++){
const a0 = this.angle + i * seg, a1 = a0 + seg;
const win = (!this.active && winnerIdx === i);
c.beginPath(); c.moveTo(cx, cy); c.arc(cx, cy, R, a0, a1); c.closePath();
c.fillStyle = this.segColor(i);
c.fill();
if(win){
const pulse = (.78 + .22 * Math.sin(now / 300)) * this.glow;
const g = c.createRadialGradient(cx, cy, hubR * .5, cx, cy, R);
g.addColorStop(0, "rgba(255,244,214," + (pulse * .95).toFixed(3) + ")");
g.addColorStop(1, "rgba(200,163,78," + pulse.toFixed(3) + ")");
c.fillStyle = g; c.fill();
}
c.strokeStyle = "rgba(200,163,78,.30)"; c.lineWidth = 1.4; c.stroke();
}
// labels
const fs = Math.max(10, Math.min(21, 300 / Math.max(6, n) + 5));
c.save(); c.translate(cx, cy);
c.font = "700 " + fs.toFixed(0) + "px system-ui,-apple-system,'Segoe UI',Roboto,sans-serif";
c.textBaseline = "middle";
for(let i = 0; i < n; i++){
const mid = this.angle + (i + .5) * seg;
const win = (!this.active && winnerIdx === i);
c.save(); c.rotate(mid);
c.fillStyle = win ? "#221904" : "rgba(240,243,248,.95)";
const label = fitText(c, (names[i].last || names[i].first).toUpperCase(), R - hubR - 26);
if(Math.cos(mid) < 0){
// this wedge points left, so flip the glyphs back upright and run them inward
c.rotate(Math.PI);
c.textAlign = "left";
c.fillText(label, -(R - 17), 0);
}else{
c.textAlign = "right";
c.fillText(label, R - 17, 0);
}
c.restore();
}
c.restore();
// rim highlight
c.beginPath(); c.arc(cx, cy, R, 0, TAU);
c.strokeStyle = "rgba(200,163,78,.75)"; c.lineWidth = 3; c.stroke();
// hub
c.beginPath(); c.arc(cx, cy, hubR, 0, TAU);
const hub = c.createRadialGradient(cx - hubR * .4, cy - hubR * .5, 2, cx, cy, hubR);
hub.addColorStop(0, "#2B3244"); hub.addColorStop(1, "#12161F");
c.fillStyle = hub; c.fill();
c.strokeStyle = "rgba(200,163,78,.85)"; c.lineWidth = 2.5; c.stroke();
c.fillStyle = "#C8A34E"; c.textAlign = "center"; c.textBaseline = "middle";
c.font = "800 " + Math.max(10, hubR * .34).toFixed(0) + "px system-ui,sans-serif";
c.fillText(fitText(c, sectionMeta(), hubR * 1.55), cx, cy);
// pointer (kicks back as each wedge goes by)
c.save();
c.translate(cx, cy - R - 16);
c.rotate(this.kick * .34);
c.beginPath(); c.moveTo(0, 34); c.lineTo(-14, -6); c.lineTo(14, -6); c.closePath();
const pg = c.createLinearGradient(0, -6, 0, 34);
pg.addColorStop(0, "#FFF3D4"); pg.addColorStop(1, "#B4903E");
c.fillStyle = pg; c.shadowColor = "rgba(0,0,0,.55)"; c.shadowBlur = 12; c.shadowOffsetY = 4;
c.fill();
c.shadowBlur = 0;
c.beginPath(); c.arc(0, -10, 9, 0, TAU); c.fillStyle = "#D9B863"; c.fill();
c.restore();
},
reset(){ this.active = false; this.glow = 0; this.kick = 0; }
};
/* =====================================================================
6. VISUAL B — SPLIT-FLAP BOARD
===================================================================== */
const ALPHABET = " ABCDEFGHIJKLMNOPQRSTUVWXYZ'-.";
const AIDX = {}; for(let i = 0; i < ALPHABET.length; i++) AIDX[ALPHABET[i]] = i;
function flapText(s){
return (s || "")
.normalize("NFD").replace(/[\u0300-\u036f]/g, "") // strip accents
.toUpperCase()
.split("").map(ch => (ch in AIDX ? ch : " ")).join("");
}
const flap = {
cols: 0, rows: 2,
tiles: [], // row-major: { cur, from, flips, frac, dur, t0 }
tw: 0, th: 0, gap: 6, rowGap: 22, ox: 0, oy: 0,
active: false,
PAD: 44, // breathing room above and below the board, in px
ensure(){
const need = this.cols * this.rows;
if(this.tiles.length !== need){
this.tiles = Array.from({ length: need }, () => ({ cur: 0, from: 0, flips: 0, frac: 0, dur: 0, t0: 0 }));
}
},
// how many columns the loaded section needs
setCols(names){
let w = 6;
for(const p of names) w = Math.max(w, flapText(p.last).trim().length, flapText(p.first).trim().length);
this.cols = Math.min(16, Math.max(7, w));
this.ensure();
},
// tile width is driven by the stage's width alone, capped so tiles never look bloated
tileWidthFor(stageW){
if(!this.cols) return 0;
return Math.min(78, (stageW - 56 - this.gap * (this.cols - 1)) / this.cols);
},
// the stage height that fits the board exactly, at full tile size
stageHeightFor(stageW){
return this.tileWidthFor(stageW) * 1.34 * this.rows + this.rowGap + this.PAD * 2;
},
layout(){
if(!this.cols) return;
let tw = this.tileWidthFor(app.W);
let th = tw * 1.34;
// only shrink if the stage is genuinely too short (it isn't when we sized it ourselves)
const availH = app.H - 24;
const totalH = th * this.rows + this.rowGap;
if(totalH > availH){ th = (availH - this.rowGap) / this.rows; tw = th / 1.34; }
this.tw = tw; this.th = th;
const boardW = tw * this.cols + this.gap * (this.cols - 1);
const boardH = th * this.rows + this.rowGap;
this.ox = (app.W - boardW) / 2;
this.oy = (app.H - boardH) / 2;
},
setStatic(rowsText){
this.ensure();
for(let r = 0; r < this.rows; r++){
const s = (rowsText[r] || "").padEnd(this.cols, " ").slice(0, this.cols);
for(let cIdx = 0; cIdx < this.cols; cIdx++){
const t = this.tiles[r * this.cols + cIdx];
t.cur = AIDX[s[cIdx]] ?? 0; t.frac = 0;
}
}
this.active = false;
},
// Each tile gets a fixed run time and a fixed number of flips; position is a pure
// function of elapsed time. That pins the board's total duration no matter what
// frame rate we get, and guarantees the last flip lands on the target glyph.
start(rowsText, now){
this.ensure();
const L = ALPHABET.length;
for(let r = 0; r < this.rows; r++){
const s = (rowsText[r] || "").padEnd(this.cols, " ").slice(0, this.cols);
for(let cIdx = 0; cIdx < this.cols; cIdx++){
const t = this.tiles[r * this.cols + cIdx];
// scatter the starting glyphs, otherwise every tile ticks in lockstep and the
// whole board just counts through the alphabet together
t.from = (t.cur + cIdx * 7 + r * 13 + ((Math.random() * L) | 0)) % L;
t.cur = t.from;
t.frac = 0;
const target = AIDX[s[cIdx]] ?? 0;
const dist = (target - t.from + L) % L;
// the padding MUST be whole alphabet cycles, or the tile lands on the wrong glyph
t.flips = dist + L * (1 + Math.floor(cIdx / 6));
// columns lock left→right, the first-name row trails the last-name row
t.dur = (1450 + cIdx * 95 + r * 340) * MOTION;
t.t0 = now;
}
}
this.active = true;
},
step(now){
if(!this.active) return false;
const L = ALPHABET.length;
let done = true;
for(const t of this.tiles){
const p = t.dur > 0 ? Math.min(1, Math.max(0, (now - t.t0) / t.dur)) : 1;
if(p < 1) done = false;
const pos = Math.sin(p * Math.PI / 2) * t.flips; // quick ramp, gentle landing
const whole = Math.min(t.flips, Math.floor(pos));
t.cur = (t.from + whole) % L;
t.frac = p >= 1 ? 0 : pos - whole; // 0 == settled, else mid-flip
}
if(done){ this.active = false; return true; }
return false;
},
face(c, ch, x, y, w, h, half, shade){
c.save();
c.beginPath();
if(half === "top") c.rect(x, y, w, h / 2 - .5);
else if(half === "bot") c.rect(x, y + h / 2 + .5, w, h / 2);
else c.rect(x, y, w, h);
c.clip();
roundRect(c, x, y, w, h, 5);
const g = c.createLinearGradient(0, y, 0, y + h);
g.addColorStop(0, "#20242F"); g.addColorStop(.49, "#171B24");
g.addColorStop(.51, "#12161E"); g.addColorStop(1, "#0D1017");
c.fillStyle = g; c.fill();
c.strokeStyle = "rgba(255,255,255,.05)"; c.lineWidth = 1; c.stroke();
c.fillStyle = "#EDE6D2";
c.font = "700 " + (h * .60).toFixed(0) + "px ui-monospace,'Cascadia Mono','SF Mono',Consolas,monospace";
c.textAlign = "center"; c.textBaseline = "middle";
c.fillText(ch, x + w / 2, y + h / 2 + h * .02);
if(shade > 0){ c.fillStyle = "rgba(0,0,0," + (shade * .55).toFixed(3) + ")"; c.fillRect(x, y, w, h); }
c.restore();
},
draw(c, now){
if(!this.cols) return;
const L = ALPHABET.length;
// board backing plate
const bw = this.tw * this.cols + this.gap * (this.cols - 1);
const bh = this.th * this.rows + this.rowGap;
c.save();
roundRect(c, this.ox - 16, this.oy - 16, bw + 32, bh + 32, 14);
c.fillStyle = "rgba(9,11,16,.72)";
c.shadowColor = "rgba(0,0,0,.55)"; c.shadowBlur = 26; c.shadowOffsetY = 10;
c.fill(); c.shadowBlur = 0;
c.strokeStyle = "rgba(200,163,78,.20)"; c.lineWidth = 1.4; c.stroke();
c.restore();
for(let r = 0; r < this.rows; r++){
for(let i = 0; i < this.cols; i++){
const t = this.tiles[r * this.cols + i];
const x = this.ox + i * (this.tw + this.gap);
const y = this.oy + r * (this.th + this.rowGap);
const cur = ALPHABET[t.cur];
const next = ALPHABET[(t.cur + 1) % L];
if(!(t.frac > 0)){
this.face(c, cur, x, y, this.tw, this.th, "full", 0);
}else{
const p = t.frac;
// what sits behind the falling leaf
this.face(c, next, x, y, this.tw, this.th, "top", 0);
this.face(c, cur, x, y, this.tw, this.th, "bot", 0);
c.save();
c.translate(0, y + this.th / 2);
if(p < .5){
c.scale(1, Math.cos(p * Math.PI)); // old top half falls
c.translate(0, -(y + this.th / 2));
this.face(c, cur, x, y, this.tw, this.th, "top", p * .9);
}else{
c.scale(1, -Math.cos(p * Math.PI)); // new bottom half lands
c.translate(0, -(y + this.th / 2));
this.face(c, next, x, y, this.tw, this.th, "bot", (1 - p) * 1.8);
}
c.restore();
}
// hinge
c.fillStyle = "rgba(0,0,0,.72)";
c.fillRect(x, y + this.th / 2 - 1, this.tw, 2);
}
}
c.fillStyle = "rgba(200,163,78,.55)";
c.font = "700 10px system-ui,sans-serif";
c.textAlign = "center"; c.textBaseline = "top";
c.letterSpacing && (c.letterSpacing = "3px");
c.fillText("SECTION " + sectionMeta().toUpperCase(), app.W / 2, this.oy + bh + 20);
c.letterSpacing && (c.letterSpacing = "0px");
},
reset(){ this.active = false; }
};
/* =====================================================================
7. RENDER LOOP
===================================================================== */
function draw(now){
ctx.clearRect(0, 0, app.W, app.H);
const names = roster();
const wIdx = app.winner;
if(names.length){
if(app.mode === "wheel") wheel.draw(ctx, now, names, wIdx);
else flap.draw(ctx, now);
}
confetti.draw(ctx);
}
function frame(now){
const names = roster();
if(names.length && app.spinning){
let done = false;
if(app.mode === "wheel") done = wheel.step(now, names.length);
else done = flap.step(now);
if(done) finish();
}
confetti.step();
draw(now);
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
/* =====================================================================
8. DRAW / SELECT
===================================================================== */
function pick(n){
if(window.crypto && crypto.getRandomValues){
const a = new Uint32Array(1);
crypto.getRandomValues(a);
return a[0] % n; // n <= 19; modulo bias is immeasurable here
}
return Math.floor(Math.random() * n);
}
function go(){
const names = roster();
if(app.spinning || !names.length) return;
app.spinning = true;
app.winner = null;
confetti.clear();
$("winner").classList.remove("show");
$("goBtn").disabled = true;
$("sectionSel").disabled = true;
const idx = pick(names.length);
app.pending = idx;
if(app.mode === "wheel"){
wheel.reset();
wheel.start(idx, names.length);
}else{
const p = names[idx];
flap.setCols(names);
flap.layout();
flap.start([flapText(p.last), flapText(p.first)], performance.now());
}
}
function finish(){
app.spinning = false;
app.winner = app.pending;
const p = roster()[app.winner];
$("goBtn").disabled = false;
$("sectionSel").disabled = false;
const full = [p.last, p.first ? (p.first + (p.mi ? " " + p.mi.replace(/\.$/, "") + "." : "")) : ""]
.filter(Boolean).join(", ");
$("winName").textContent = full;
$("winMeta").textContent = [sectionMeta(), p.co].filter(Boolean).join(" · ");
$("winner").classList.add("show");
if(app.mode === "wheel"){
confetti.burst(app.W / 2, app.H * .46);
}else{
// fire from both ends of the board so the plume frames the name instead of covering it
const half = (flap.tw * flap.cols + flap.gap * (flap.cols - 1)) / 2 + 26;
confetti.burst(app.W / 2 - half, app.H * .56, 120);
confetti.burst(app.W / 2 + half, app.H * .56, 120);
}
}
/* =====================================================================
9. UI WIRING
===================================================================== */
function showError(msg){
const b = $("errBox");
if(!msg){ b.classList.add("hidden"); b.textContent = ""; return; }
b.textContent = msg;
b.classList.remove("hidden");
}
function applyBook(book, fromCache){
app.book = book;
app.sectionIdx = 0;
app.winner = null;
wheel.reset(); flap.reset(); confetti.clear();
$("winner").classList.remove("show");
const sel = $("sectionSel");
sel.innerHTML = "";
book.sections.forEach((s, i) => {
const o = document.createElement("option");
o.value = i;
o.textContent = s.sheet + (s.label ? " — " + s.label : "") + " (" + s.cadets.length + ")";
if(!s.cadets.length) o.textContent += " — empty";
sel.appendChild(o);
});
sel.disabled = false;
// land on the first section that actually has cadets
const firstFull = book.sections.findIndex(s => s.cadets.length);
if(firstFull > 0){ app.sectionIdx = firstFull; sel.value = String(firstFull); }
$("fileName").textContent = book.fileName;
$("fileSub").textContent = (fromCache ? "Cached " : "Loaded ") +
new Date(book.savedAt).toLocaleDateString(undefined, { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" });
$("loadBtn").textContent = "Change…";
onSectionChange();
}
function onSectionChange(){
const names = roster();
app.winner = null;