-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathteam.html
More file actions
765 lines (732 loc) · 39.6 KB
/
Copy pathteam.html
File metadata and controls
765 lines (732 loc) · 39.6 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
<!doctype html>
<html lang="en" data-mode="dark">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Cast — Team Builder</title>
<meta name="description" content="Turn a list of names into a deterministic set of SVG avatars — no code. Style the whole team, tweak individuals, and export as SVGs, a sprite, a group mark, or a snippet.">
<link rel="icon" type="image/svg+xml" href="favicon.svg">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@500;600;700&family=Instrument+Sans:wght@400;500;600&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
<style>
:root {
color-scheme: light dark;
--bg: #0F1220; --surface: #181C2C; --surface-2: #1F2438; --border: #2A2F45;
--text: #EDEEF4; --dim: #8B91A7; --acc1: #3ECFEA; --acc2: #A78BFA;
--font-display: 'Space Grotesk', sans-serif;
--font-body: 'Instrument Sans', sans-serif;
--font-mono: 'JetBrains Mono', monospace;
--shadow: 0 12px 40px rgba(5, 8, 20, 0.45);
}
html[data-mode="light"] {
--bg: #F4F4F7; --surface: #FFFFFF; --surface-2: #EEEFF4; --border: #E0E2EC;
--text: #15182A; --dim: #5E6478; --shadow: 0 10px 32px rgba(20, 24, 50, 0.10);
}
* { box-sizing: border-box; }
body {
margin: 0; background: var(--bg); color: var(--text);
font-family: var(--font-body); font-size: 16px; line-height: 1.55;
-webkit-font-smoothing: antialiased;
}
a { color: inherit; }
.mono { font-family: var(--font-mono); }
.nav { border-bottom: 1px solid var(--border); }
.nav-inner {
max-width: 1180px; margin: 0 auto; padding: 14px 28px;
display: flex; align-items: center; justify-content: space-between; gap: 20px;
}
.logo { display: flex; align-items: center; gap: 10px; text-decoration: none; }
.logo svg { width: 28px; height: 28px; display: block; border-radius: 8px; }
.logo-word { font-family: var(--font-display); font-weight: 700; font-size: 20px; letter-spacing: -0.04em; }
.nav-links { display: flex; gap: 20px; align-items: center; }
.nav-links a { text-decoration: none; font-size: 14.5px; font-weight: 500; color: var(--dim); }
.nav-links a:hover { color: var(--text); }
main { max-width: 1180px; margin: 0 auto; padding: 40px 28px 80px; }
h1 { font-family: var(--font-display); font-weight: 700; font-size: clamp(30px, 4vw, 44px); letter-spacing: -0.04em; margin: 0 0 10px; }
.lede { color: var(--dim); font-size: 17px; max-width: 46em; margin: 0 0 32px; }
.builder { display: grid; grid-template-columns: 320px 1fr; gap: 28px; align-items: start; }
@media (max-width: 880px) { .builder { grid-template-columns: 1fr; } }
.panel {
background: var(--surface); border: 1px solid var(--border); border-radius: 18px;
padding: 20px; box-shadow: var(--shadow); display: flex; flex-direction: column; gap: 18px;
position: sticky; top: 20px;
}
@media (max-width: 880px) { .panel { position: static; } }
.field { display: flex; flex-direction: column; gap: 6px; }
.field-label { font-family: var(--font-mono); font-size: 11px; font-weight: 500; letter-spacing: 0.1em; text-transform: uppercase; color: var(--dim); }
textarea, select {
font-family: var(--font-body); font-size: 14px; color: var(--text);
background: var(--surface-2); border: 1px solid var(--border); border-radius: 10px;
padding: 10px 12px; outline: none; width: 100%;
}
textarea { font-family: var(--font-mono); min-height: 160px; resize: vertical; line-height: 1.5; }
textarea:focus, select:focus { border-color: var(--acc1); }
select { appearance: none; -webkit-appearance: none; cursor: pointer; }
.grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
.panel-section { font-family: var(--font-mono); font-size: 11px; font-weight: 500; letter-spacing: 0.1em; text-transform: uppercase; color: var(--dim); margin: 4px 0 -4px; padding-top: 14px; border-top: 1px solid var(--border); }
.hint { margin: 2px 0 0; font-size: 12px; color: var(--dim); line-height: 1.45; }
.hint .mono { font-family: var(--font-mono); font-size: 11.5px; color: var(--text); }
.results { display: flex; flex-direction: column; gap: 20px; min-width: 0; }
.toolbar { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.count { font-family: var(--font-mono); font-size: 12px; color: var(--dim); margin-right: auto; }
.tb-size { display: inline-flex; align-items: center; gap: 7px; font-family: var(--font-mono); font-size: 11px; font-weight: 500; letter-spacing: 0.1em; text-transform: uppercase; color: var(--dim); }
.tb-size select { width: auto; padding: 8px 10px; font-size: 13px; }
.btn {
font-family: var(--font-display); font-weight: 600; font-size: 13.5px;
border-radius: 10px; padding: 9px 14px; cursor: pointer; border: 1px solid var(--border);
background: var(--surface-2); color: var(--text);
}
.btn:hover { border-color: var(--dim); }
.btn.primary { background: linear-gradient(135deg, var(--acc1), var(--acc2)); border: 0; color: #0b0f1a; }
.btn.mini { font-size: 12.5px; padding: 7px 12px; }
.check { display: flex; gap: 8px; align-items: center; font-size: 13.5px; color: var(--text); cursor: pointer; }
.check input { width: auto; cursor: pointer; }
.team-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(calc(var(--tile-size, 96px) + 36px), 1fr)); gap: 16px; }
.tile {
background: var(--surface); border: 1px solid var(--border); border-radius: 14px;
padding: 14px 10px; display: flex; flex-direction: column; align-items: center; gap: 8px;
cursor: pointer; transition: border-color 0.15s ease, transform 0.1s ease; position: relative;
}
.tile:hover { border-color: var(--acc1); transform: translateY(-2px); }
.tile svg { display: block; width: var(--tile-size, 96px); height: var(--tile-size, 96px); }
.tile .name { font-size: 12.5px; color: var(--text); text-align: center; word-break: break-word; line-height: 1.3; }
.tile.edited::after { content: ""; position: absolute; top: 9px; right: 9px; width: 7px; height: 7px; border-radius: 50%; background: var(--acc2); }
.tile.dragging { opacity: 0.4; }
.tile.drop-target { border-color: var(--acc1); border-style: dashed; }
.tile-x { position: absolute; top: 6px; left: 6px; width: 20px; height: 20px; border-radius: 50%; border: 0; cursor: pointer; background: var(--surface-2); color: var(--dim); font-size: 15px; line-height: 1; display: flex; align-items: center; justify-content: center; opacity: 0; transition: opacity 0.12s; }
.tile:hover .tile-x { opacity: 1; }
.tile-x:hover { background: #f43f5e; color: #fff; }
.grid-hint { font-size: 12px; color: var(--dim); margin: -6px 0 0; }
.empty { color: var(--dim); font-size: 14px; padding: 30px 0; }
.overlay { position: fixed; inset: 0; background: rgba(5, 8, 20, 0.55); display: none; align-items: center; justify-content: center; z-index: 60; padding: 20px; }
.overlay.show { display: flex; }
.editor { background: var(--surface); border: 1px solid var(--border); border-radius: 18px; padding: 22px; width: 440px; max-width: 100%; max-height: calc(100vh - 40px); box-shadow: var(--shadow); display: flex; flex-direction: column; gap: 16px; }
.editor h3 { font-family: var(--font-display); margin: 0; font-size: 18px; word-break: break-word; }
.editor-head { display: flex; align-items: center; gap: 14px; }
.editor-head .preview svg { width: 64px; height: 64px; display: block; }
.editor-body { overflow-y: auto; display: flex; flex-direction: column; gap: 14px; padding-right: 4px; }
.ov-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
.ov-note { margin: 2px 0 0; font-size: 12px; color: var(--dim); }
.ov-section { font-family: var(--font-mono); font-size: 11px; font-weight: 500; letter-spacing: 0.1em; text-transform: uppercase; color: var(--dim); margin: 6px 0 -4px; }
.editor-actions { display: flex; gap: 8px; justify-content: space-between; }
.toast { position: fixed; bottom: 28px; left: 50%; transform: translate(-50%, 16px); background: var(--text); color: var(--bg); font-family: var(--font-display); font-weight: 600; font-size: 14px; border-radius: 999px; padding: 10px 20px; opacity: 0; pointer-events: none; transition: opacity 0.2s, transform 0.2s; z-index: 100; }
.toast.show { opacity: 1; transform: translate(-50%, 0); }
</style>
</head>
<body>
<nav class="nav">
<div class="nav-inner">
<a class="logo" href="./index.html">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 96 96" aria-hidden="true">
<clipPath id="tc"><rect width="96" height="96" rx="26"></rect></clipPath>
<rect width="96" height="96" rx="26" fill="#181C2C"></rect>
<g clip-path="url(#tc)"><circle cx="48" cy="38" r="17" fill="#3ECFEA"></circle><ellipse cx="48" cy="84" rx="28" ry="22" fill="#A78BFA"></ellipse></g>
<circle cx="76" cy="76" r="9" fill="#34D399" stroke="#181C2C" stroke-width="5"></circle>
</svg>
<span class="logo-word">cast</span>
</a>
<div class="nav-links">
<a href="./index.html">Playground</a>
</div>
</div>
</nav>
<main>
<h1>Team Builder</h1>
<p class="lede">Paste a list of identifiers — names, emails, user IDs, anything — one per line, and get a deterministic avatar for each. Style the whole team, click any tile to customize that person, then export. No code required.</p>
<div class="builder">
<section class="panel" aria-label="Team options">
<div class="field">
<label class="field-label" for="names">Identifiers (one per line)</label>
<textarea id="names" spellcheck="false"></textarea>
<p class="hint">Avatar seeds on the first value. Add a label after a comma, pipe, or tab to show a name: <span class="mono">ada@corp.com, Ada Lovelace</span></p>
<div><button class="btn mini" id="csv-open" type="button">Import CSV…</button></div>
<input type="file" id="csv-file" accept=".csv,text/csv" hidden>
</div>
<div class="grid-2">
<div class="field">
<label class="field-label" for="style">Style</label>
<select id="style"></select>
</div>
<div class="field">
<label class="field-label" for="theme">Theme (palette)</label>
<select id="theme"></select>
</div>
<div class="field">
<label class="field-label" for="shape">Shape</label>
<select id="shape"></select>
</div>
<div class="field">
<label class="field-label" for="background">Background</label>
<select id="background"></select>
</div>
<div class="field">
<label class="field-label" for="animate">Animate</label>
<select id="animate"></select>
</div>
</div>
<p class="panel-section">Sprite & group exports</p>
<div class="grid-2">
<div class="field">
<label class="field-label" for="sprite-cols">Sprite columns</label>
<select id="sprite-cols"></select>
</div>
<div class="field">
<label class="field-label" for="sprite-cell">Sprite cell</label>
<select id="sprite-cell"></select>
</div>
<div class="field">
<label class="field-label" for="group-max">Group max</label>
<select id="group-max"></select>
</div>
</div>
</section>
<section class="results">
<div class="toolbar">
<span class="count" id="count"></span>
<label class="tb-size">Avatar size<select id="size"></select></label>
<button class="btn primary" id="dl-zip" type="button">Download SVGs (.zip)</button>
<button class="btn" id="dl-png" type="button">Download PNGs (.zip)</button>
<button class="btn" id="copy-sprite" type="button">Copy sprite</button>
<button class="btn" id="copy-group" type="button">Copy group mark</button>
<button class="btn" id="copy-code" type="button">Copy code</button>
<button class="btn" id="copy-link" type="button">Copy link</button>
</div>
<p class="grid-hint" id="grid-hint">Click a tile to customize · drag to reorder · hover to remove.</p>
<div class="team-grid" id="team-grid"></div>
</section>
</div>
</main>
<div class="overlay" id="overlay">
<div class="editor" role="dialog" aria-modal="true" aria-label="Customize member">
<div class="editor-head">
<div class="preview" id="editor-preview"></div>
<h3 id="editor-name"></h3>
</div>
<div class="editor-body">
<div class="field">
<label class="field-label" for="ov-style">Style</label>
<select id="ov-style"></select>
</div>
<div class="ov-grid">
<div class="field">
<label class="field-label" for="ov-expression">Expression</label>
<select id="ov-expression"></select>
</div>
<div class="field">
<label class="field-label" for="ov-status">Status</label>
<select id="ov-status"></select>
</div>
</div>
<p class="ov-section">Traits</p>
<p class="ov-note">Identity traits apply to the illustrated styles (portrait, studio, cartoon).</p>
<div class="ov-grid" id="ov-traits"></div>
</div>
<div class="editor-actions">
<button class="btn" id="ov-reset" type="button">Reset</button>
<button class="btn primary" id="ov-done" type="button">Done</button>
</div>
</div>
</div>
<div class="overlay" id="csv-overlay">
<div class="editor" role="dialog" aria-modal="true" aria-label="Import CSV" style="width: 380px;">
<h3>Import CSV</h3>
<p class="ov-note" id="csv-info"></p>
<label class="check"><input type="checkbox" id="csv-header" checked> First row is a header</label>
<div class="ov-grid">
<div class="field">
<label class="field-label" for="csv-seed">Seed column</label>
<select id="csv-seed"></select>
</div>
<div class="field">
<label class="field-label" for="csv-label">Label column</label>
<select id="csv-label"></select>
</div>
</div>
<div class="editor-actions">
<button class="btn" id="csv-cancel" type="button">Cancel</button>
<button class="btn primary" id="csv-import" type="button">Import</button>
</div>
</div>
</div>
<div class="toast" id="toast" role="status" aria-live="polite"></div>
<script type="module">
import {
createAvatar, createAvatars, createAvatarSprite, createAvatarGroup, avatarOptions,
} from './src/avatar.js';
const $ = (s) => document.querySelector(s);
const THEMES = {
default: undefined,
mono: { backgrounds: ['#E5E7EB', '#D1D5DB'], shapeColors: ['#111827', '#4B5563', '#9CA3AF'], clothingColors: ['#111827', '#374151'], inks: ['#111827'] },
sunset: { backgrounds: ['#FFE4D6', '#FFD6E0'], shapeColors: ['#F97316', '#F43F5E', '#FACC15'], clothingColors: ['#F97316', '#E11D48'] },
ocean: { backgrounds: ['#D8F3F7', '#DBEAFE'], shapeColors: ['#0EA5E9', '#22D3EE', '#6366F1'], clothingColors: ['#0EA5E9', '#0369A1'] },
forest: { backgrounds: ['#DCFCE7', '#ECFCCB'], shapeColors: ['#16A34A', '#65A30D', '#0D9488'], clothingColors: ['#15803D', '#3F6212'] },
accessible: 'accessible',
};
const SHAPES = { circle: '50%', squircle: '28%', rounded: '16', square: '0' };
const BACKGROUNDS = { auto: 'auto', transparent: 'transparent', gradient: 'gradient', dots: 'dots', rings: 'rings', grid: 'grid' };
const STYLES = avatarOptions.style.filter((s) => s !== 'face');
const EXPRESSIONS = ['auto', ...(avatarOptions.expression || [])];
const STATUSES = ['none', 'online', 'busy', 'away', 'offline'];
const ANIMATIONS = ['none', 'breathe', 'bounce', 'blink'];
const SIZES = ['64', '128', '256', '512'];
const CLOTHING = { auto: 'auto', blue: '#3B82F6', red: '#EF4444', green: '#22C55E', purple: '#8B5CF6', slate: '#64748B' };
const TRAIT_KEYS = [
'gender', 'skinTone', 'faceShape', 'hairStyle', 'hairColor', 'eyebrows',
'eyes', 'nose', 'mouth', 'facialHair', 'freckles', 'blush', 'headwear',
'earrings', 'accessories',
];
const LABELS = {
gender: 'Gender', skinTone: 'Skin tone', faceShape: 'Face shape', hairStyle: 'Hair style',
hairColor: 'Hair color', eyebrows: 'Eyebrows', eyes: 'Eyes', nose: 'Nose', mouth: 'Mouth',
facialHair: 'Facial hair', freckles: 'Freckles', blush: 'Blush', headwear: 'Headwear',
earrings: 'Earrings', accessories: 'Accessories', clothing: 'Clothing',
};
const state = {
names: ['Ada Lovelace', 'Grace Hopper', 'Alan Turing', 'Katherine Johnson', 'Lin Chen', 'Noor', 'Kai', 'June Park'],
style: 'portrait', theme: 'default', shape: 'circle', background: 'auto', animate: 'none',
overrides: {},
};
/* ---------- helpers ---------- */
function toast(msg) {
const el = $('#toast');
el.textContent = msg;
el.classList.add('show');
clearTimeout(toast._t);
toast._t = setTimeout(() => el.classList.remove('show'), 1700);
}
function copyText(text, msg) {
navigator.clipboard.writeText(text).then(() => toast(msg), () => toast('Copy failed'));
}
// Each line is "seed" or "seed <delimiter> label"; the avatar seeds on the
// first field, the caption shows the label. Delimiters: tab (spreadsheet
// paste), pipe, or comma — whichever appears first.
function parseInput() {
const list = [];
const seen = new Set();
let dropped = 0;
let blank = 0;
for (const raw of state.names) {
const line = raw.trim();
if (!line) { blank += 1; continue; }
const parts = line.split(/\t|\||,/);
const seed = parts[0].trim();
if (!seed) { blank += 1; continue; }
if (seen.has(seed)) { dropped += 1; continue; }
seen.add(seed);
list.push({ seed, label: (parts[1] || '').trim() || seed });
}
return { list, dropped, blank };
}
function members() { return parseInput().list; }
function memberSeeds() { return members().map((m) => m.seed); }
// The per-person delta only (no team-wide options) — used both to render
// and to express overrides as item objects for createAvatars/Sprite.
function overrideOptions(name) {
const ov = state.overrides[name];
if (!ov) return null;
const o = {};
if (ov.style) o.style = ov.style;
if (ov.expression && ov.expression !== 'auto') o.expression = ov.expression;
if (ov.status && ov.status !== 'none') o.status = ov.status;
if (ov.clothing && ov.clothing !== 'auto') o.clothing = CLOTHING[ov.clothing] ?? ov.clothing;
if (ov.traits) {
const t = {};
for (const k of TRAIT_KEYS) if (ov.traits[k] && ov.traits[k] !== 'auto') t[k] = ov.traits[k];
if (Object.keys(t).length) o.traits = t;
}
return Object.keys(o).length ? o : null;
}
function optsFor(name, size) {
const o = { style: state.style, radius: SHAPES[state.shape], background: BACKGROUNDS[state.background] ?? state.background };
if (size != null) o.size = size;
if (state.theme !== 'default' && THEMES[state.theme]) o.palette = THEMES[state.theme];
if (state.animate !== 'none') o.animate = state.animate;
const ov = overrideOptions(name);
if (ov) Object.assign(o, ov);
return o;
}
// Each roster entry as a seed string, or {seed, ...overrides} when customized.
function rosterItems() {
return members().map((m) => {
const ov = overrideOptions(m.seed);
return ov ? { seed: m.seed, ...ov } : m.seed;
});
}
function exportSize() { return parseInt($('#size').value, 10) || 256; }
function fileSafe(name) {
return name.replace(/[^a-z0-9@._-]+/gi, '_').replace(/^_+|_+$/g, '') || 'avatar';
}
function fillSelect(el, values, current) {
el.innerHTML = values.map((v) => `<option value="${v}">${v}</option>`).join('');
el.value = current;
}
/* ---------- zero-dependency ZIP (store / no compression) ---------- */
function crc32(bytes) {
let crc = 0xFFFFFFFF;
for (let i = 0; i < bytes.length; i += 1) {
let c = (crc ^ bytes[i]) & 0xFF;
for (let k = 0; k < 8; k += 1) c = c & 1 ? (c >>> 1) ^ 0xEDB88320 : c >>> 1;
crc = (crc >>> 8) ^ c;
}
return (crc ^ 0xFFFFFFFF) >>> 0;
}
function zipStore(files) {
const enc = new TextEncoder();
const chunks = [];
const central = [];
let offset = 0;
for (const f of files) {
const nameBytes = enc.encode(f.name);
const data = f.data;
const crc = crc32(data);
const lh = new Uint8Array(30 + nameBytes.length);
const dv = new DataView(lh.buffer);
dv.setUint32(0, 0x04034b50, true); dv.setUint16(4, 20, true);
dv.setUint32(14, crc, true); dv.setUint32(18, data.length, true); dv.setUint32(22, data.length, true);
dv.setUint16(26, nameBytes.length, true);
lh.set(nameBytes, 30);
chunks.push(lh, data);
const ch = new Uint8Array(46 + nameBytes.length);
const cv = new DataView(ch.buffer);
cv.setUint32(0, 0x02014b50, true); cv.setUint16(4, 20, true); cv.setUint16(6, 20, true);
cv.setUint32(16, crc, true); cv.setUint32(20, data.length, true); cv.setUint32(24, data.length, true);
cv.setUint16(28, nameBytes.length, true); cv.setUint32(42, offset, true);
ch.set(nameBytes, 46);
central.push(ch);
offset += lh.length + data.length;
}
const centralStart = offset;
let centralSize = 0;
for (const ch of central) { chunks.push(ch); centralSize += ch.length; }
const end = new Uint8Array(22);
const ev = new DataView(end.buffer);
ev.setUint32(0, 0x06054b50, true);
ev.setUint16(8, central.length, true); ev.setUint16(10, central.length, true);
ev.setUint32(12, centralSize, true); ev.setUint32(16, centralStart, true);
chunks.push(end);
let total = 0;
for (const c of chunks) total += c.length;
const out = new Uint8Array(total);
let p = 0;
for (const c of chunks) { out.set(c, p); p += c.length; }
return out;
}
function escapeHtml(s) {
return s.replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
}
/* ---------- CSV import ---------- */
function parseCSV(text) {
const rows = [];
let row = [];
let field = '';
let inQ = false;
for (let i = 0; i < text.length; i += 1) {
const c = text[i];
if (inQ) {
if (c === '"') {
if (text[i + 1] === '"') { field += '"'; i += 1; } else inQ = false;
} else field += c;
} else if (c === '"') inQ = true;
else if (c === ',') { row.push(field); field = ''; }
else if (c === '\n') { row.push(field); rows.push(row); row = []; field = ''; }
else if (c !== '\r') field += c;
}
if (field.length || row.length) { row.push(field); rows.push(row); }
return rows.filter((r) => r.some((c) => c.trim() !== ''));
}
let csvRows = [];
function openCsvModal(rows) {
csvRows = rows;
$('#csv-info').textContent = `${rows.length} row${rows.length === 1 ? '' : 's'} found. Choose which columns to use.`;
populateCsvCols();
$('#csv-overlay').classList.add('show');
}
function populateCsvCols() {
const hasHeader = $('#csv-header').checked;
const width = Math.max(...csvRows.map((r) => r.length));
const cols = [];
for (let i = 0; i < width; i += 1) {
cols.push(hasHeader && csvRows[0][i] ? csvRows[0][i].trim() : `Column ${i + 1}`);
}
$('#csv-seed').innerHTML = cols.map((c, i) => `<option value="${i}">${escapeHtml(c)}</option>`).join('');
$('#csv-label').innerHTML = `<option value="-1">(none)</option>` + cols.map((c, i) => `<option value="${i}">${escapeHtml(c)}</option>`).join('');
$('#csv-seed').value = '0';
$('#csv-label').value = cols.length > 1 ? '1' : '-1';
}
function importCsv() {
const hasHeader = $('#csv-header').checked;
const dataRows = hasHeader ? csvRows.slice(1) : csvRows;
const seedIdx = parseInt($('#csv-seed').value, 10);
const labelIdx = parseInt($('#csv-label').value, 10);
const lines = [];
for (const r of dataRows) {
const seed = (r[seedIdx] || '').trim();
if (!seed) continue;
const label = labelIdx >= 0 ? (r[labelIdx] || '').trim() : '';
lines.push(label && label !== seed ? `${seed} | ${label}` : seed);
}
if (!lines.length) return toast('No rows imported');
state.names = lines;
$('#names').value = lines.join('\n');
$('#csv-overlay').classList.remove('show');
render();
toast(`Imported ${lines.length} member${lines.length === 1 ? '' : 's'}`);
}
/* ---------- render ---------- */
function render() {
const grid = $('#team-grid');
const size = exportSize();
grid.style.setProperty('--tile-size', size + 'px');
const { list, dropped, blank } = parseInput();
const notes = [];
if (dropped) notes.push(`${dropped} duplicate${dropped === 1 ? '' : 's'} skipped`);
if (blank) notes.push(`${blank} blank line${blank === 1 ? '' : 's'} skipped`);
const base = list.length ? `${list.length} member${list.length === 1 ? '' : 's'}` : '';
$('#count').textContent = [base, ...notes].filter(Boolean).join(' · ');
$('#grid-hint').style.display = list.length ? '' : 'none';
if (!list.length) {
grid.innerHTML = '<p class="empty">Add some identifiers to build your team.</p>';
} else {
grid.innerHTML = list.map((m) => {
const edited = state.overrides[m.seed] ? ' edited' : '';
return `<div class="tile${edited}" draggable="true" data-seed="${encodeURIComponent(m.seed)}" title="Customize ${escapeHtml(m.label)}"><button class="tile-x" type="button" aria-label="Remove ${escapeHtml(m.label)}" title="Remove">×</button>${createAvatar(m.seed, optsFor(m.seed, size))}<span class="name">${escapeHtml(m.label)}</span></div>`;
}).join('');
grid.querySelectorAll('.tile').forEach((tile) => {
const seed = decodeURIComponent(tile.dataset.seed);
tile.addEventListener('click', (e) => { if (!e.target.closest('.tile-x')) openEditor(seed); });
tile.querySelector('.tile-x').addEventListener('click', (e) => { e.stopPropagation(); removeMember(seed); });
tile.addEventListener('dragstart', () => { dragSeed = seed; tile.classList.add('dragging'); });
tile.addEventListener('dragend', () => { dragSeed = null; grid.querySelectorAll('.tile').forEach((t) => t.classList.remove('dragging', 'drop-target')); });
tile.addEventListener('dragover', (e) => { e.preventDefault(); if (seed !== dragSeed) tile.classList.add('drop-target'); });
tile.addEventListener('dragleave', () => tile.classList.remove('drop-target'));
tile.addEventListener('drop', (e) => { e.preventDefault(); reorder(dragSeed, seed); });
});
}
updateHash();
}
let dragSeed = null;
function setMembers(list) {
state.names = list.map((m) => (m.label && m.label !== m.seed ? `${m.seed} | ${m.label}` : m.seed));
$('#names').value = state.names.join('\n');
render();
}
function removeMember(seed) {
delete state.overrides[seed];
setMembers(members().filter((m) => m.seed !== seed));
}
function reorder(fromSeed, toSeed) {
if (!fromSeed || fromSeed === toSeed) return;
const list = members();
const from = list.findIndex((m) => m.seed === fromSeed);
const to = list.findIndex((m) => m.seed === toSeed);
if (from < 0 || to < 0) return;
const [moved] = list.splice(from, 1);
list.splice(to, 0, moved);
setMembers(list);
}
/* ---------- per-person editor ---------- */
let editing = null;
function openEditor(name) {
editing = name;
const ov = state.overrides[name] || {};
const m = members().find((x) => x.seed === name);
$('#editor-name').textContent = m ? m.label : name;
fillSelect($('#ov-style'), ['(team default)', ...STYLES], ov.style || '(team default)');
fillSelect($('#ov-expression'), EXPRESSIONS, ov.expression || 'auto');
fillSelect($('#ov-status'), STATUSES, ov.status || 'none');
buildTraitFields(ov);
refreshEditorPreview();
$('#overlay').classList.add('show');
}
function buildTraitFields(ov) {
const traits = ov.traits || {};
const fields = [
...TRAIT_KEYS.map((k) => ({ key: k, values: ['auto', ...(avatarOptions[k] || [])], current: traits[k] || 'auto' })),
{ key: 'clothing', values: Object.keys(CLOTHING), current: ov.clothing || 'auto' },
];
$('#ov-traits').innerHTML = fields.map((f) => `
<div class="field">
<label class="field-label" for="ovt-${f.key}">${LABELS[f.key]}</label>
<select id="ovt-${f.key}">${f.values.map((v) => `<option value="${v}"${v === f.current ? ' selected' : ''}>${v}</option>`).join('')}</select>
</div>`).join('');
}
function refreshEditorPreview() {
if (editing) $('#editor-preview').innerHTML = createAvatar(editing, optsFor(editing, 64));
}
function applyEditor() {
if (!editing) return;
const ov = {};
const style = $('#ov-style').value;
if (style && style !== '(team default)') ov.style = style;
if ($('#ov-expression').value !== 'auto') ov.expression = $('#ov-expression').value;
if ($('#ov-status').value !== 'none') ov.status = $('#ov-status').value;
const clothing = $('#ovt-clothing');
if (clothing && clothing.value !== 'auto') ov.clothing = clothing.value;
const traits = {};
for (const k of TRAIT_KEYS) {
const el = $('#ovt-' + k);
if (el && el.value !== 'auto') traits[k] = el.value;
}
if (Object.keys(traits).length) ov.traits = traits;
if (Object.keys(ov).length) state.overrides[editing] = ov;
else delete state.overrides[editing];
refreshEditorPreview();
}
function closeEditor() { $('#overlay').classList.remove('show'); editing = null; render(); }
/* ---------- exports ---------- */
function teamOptions() {
const o = { style: state.style, radius: SHAPES[state.shape], background: BACKGROUNDS[state.background] ?? state.background };
if (state.theme !== 'default' && THEMES[state.theme]) o.palette = THEMES[state.theme];
if (state.animate !== 'none') o.animate = state.animate;
return o;
}
function uniqueFileNamer() {
const used = {};
return (name, ext) => {
let base = fileSafe(name);
used[base] = (used[base] || 0) + 1;
if (used[base] > 1) base += '-' + used[base];
return `${base}.${ext}`;
};
}
function downloadBlob(bytes, filename) {
const blob = new Blob([bytes], { type: 'application/zip' });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = filename;
a.click();
URL.revokeObjectURL(a.href);
}
function downloadZip() {
const list = members();
if (!list.length) return toast('Nothing to export');
const enc = new TextEncoder();
const size = exportSize();
const named = uniqueFileNamer();
const files = list.map((m) => ({ name: named(m.label, 'svg'), data: enc.encode(createAvatar(m.seed, optsFor(m.seed, size))) }));
downloadBlob(zipStore(files), 'cast-team-svg.zip');
toast(`${files.length} SVGs zipped`);
}
function svgToPngBytes(svg, size) {
return new Promise((resolve, reject) => {
const url = URL.createObjectURL(new Blob([svg], { type: 'image/svg+xml' }));
const img = new Image();
img.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = size; canvas.height = size;
canvas.getContext('2d').drawImage(img, 0, 0, size, size);
URL.revokeObjectURL(url);
canvas.toBlob((b) => {
if (!b) return reject(new Error('PNG encode failed'));
b.arrayBuffer().then((ab) => resolve(new Uint8Array(ab)), reject);
}, 'image/png');
};
img.onerror = () => { URL.revokeObjectURL(url); reject(new Error('SVG load failed')); };
img.src = url;
});
}
async function downloadPng() {
const list = members();
if (!list.length) return toast('Nothing to export');
const size = exportSize();
toast(`Rendering ${list.length} PNGs…`);
const named = uniqueFileNamer();
try {
const files = [];
for (const m of list) {
const svg = createAvatar(m.seed, optsFor(m.seed, size));
files.push({ name: named(m.label, 'png'), data: await svgToPngBytes(svg, size) });
}
downloadBlob(zipStore(files), 'cast-team-png.zip');
toast(`${files.length} PNGs zipped`);
} catch (e) {
console.error(e);
toast('PNG export failed');
}
}
function codeSnippet() {
const opts = teamOptions();
const shared = { style: opts.style, ...(opts.palette ? { palette: opts.palette } : {}), radius: opts.radius, background: opts.background, ...(opts.animate ? { animate: opts.animate } : {}) };
const teamLiteral = JSON.stringify(rosterItems(), null, 2);
return `import { createAvatars } from 'cast-avatar';\n\nconst team = ${teamLiteral};\nconst avatars = createAvatars(team, ${JSON.stringify(shared, null, 2)});`;
}
/* ---------- share via URL + local persistence ---------- */
const STORE_KEY = 'cast-team-v1';
function snapshot() {
return { names: state.names, style: state.style, theme: state.theme, shape: state.shape, background: state.background, animate: state.animate, overrides: state.overrides };
}
function updateHash() {
const snap = snapshot();
location.hash = 't=' + encodeURIComponent(btoa(unescape(encodeURIComponent(JSON.stringify(snap)))));
// Remember the last team locally so it survives a reload without a link.
try { localStorage.setItem(STORE_KEY, JSON.stringify(snap)); } catch (e) { /* storage unavailable */ }
}
function restoreHash() {
const m = location.hash.match(/t=(.+)/);
if (!m) return;
try {
const saved = JSON.parse(decodeURIComponent(escape(atob(decodeURIComponent(m[1])))));
Object.assign(state, saved);
} catch (e) { console.warn('Could not restore team', e); }
}
function restoreLocal() {
try {
const raw = localStorage.getItem(STORE_KEY);
if (raw) Object.assign(state, JSON.parse(raw));
} catch (e) { /* storage unavailable or corrupt */ }
}
/* ---------- wire up ---------- */
function init() {
// An explicit share link wins; otherwise fall back to the last local team.
if (/t=/.test(location.hash)) restoreHash();
else restoreLocal();
$('#names').value = state.names.join('\n');
fillSelect($('#style'), STYLES, state.style);
fillSelect($('#theme'), Object.keys(THEMES), state.theme);
fillSelect($('#shape'), Object.keys(SHAPES), state.shape);
fillSelect($('#background'), Object.keys(BACKGROUNDS), state.background);
fillSelect($('#animate'), ANIMATIONS, state.animate);
fillSelect($('#size'), SIZES, '128');
fillSelect($('#sprite-cols'), ['2', '4', '6', '8'], '8');
fillSelect($('#sprite-cell'), ['48', '64', '96', '128'], '64');
fillSelect($('#group-max'), ['2', '3', '4'], '4');
$('#names').addEventListener('input', (e) => { state.names = e.target.value.split('\n'); render(); });
['style', 'theme', 'shape', 'background', 'animate'].forEach((key) => {
$('#' + key).addEventListener('change', (e) => { state[key] = e.target.value; render(); });
});
$('#size').addEventListener('change', render);
['ov-style', 'ov-expression', 'ov-status'].forEach((id) => $('#' + id).addEventListener('change', applyEditor));
$('#ov-traits').addEventListener('change', applyEditor);
$('#ov-reset').addEventListener('click', () => { if (editing) { delete state.overrides[editing]; openEditor(editing); } });
$('#ov-done').addEventListener('click', closeEditor);
$('#overlay').addEventListener('click', (e) => { if (e.target === $('#overlay')) closeEditor(); });
$('#csv-open').addEventListener('click', () => $('#csv-file').click());
$('#csv-file').addEventListener('change', (e) => {
const file = e.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = () => {
const rows = parseCSV(String(reader.result));
if (!rows.length) return toast('Empty or unreadable CSV');
openCsvModal(rows);
};
reader.readAsText(file);
e.target.value = '';
});
$('#csv-header').addEventListener('change', populateCsvCols);
$('#csv-import').addEventListener('click', importCsv);
$('#csv-cancel').addEventListener('click', () => $('#csv-overlay').classList.remove('show'));
$('#csv-overlay').addEventListener('click', (e) => { if (e.target === $('#csv-overlay')) $('#csv-overlay').classList.remove('show'); });
$('#dl-zip').addEventListener('click', downloadZip);
$('#dl-png').addEventListener('click', downloadPng);
$('#copy-sprite').addEventListener('click', () => copyText(createAvatarSprite(rosterItems(), { ...teamOptions(), columns: parseInt($('#sprite-cols').value, 10), cell: parseInt($('#sprite-cell').value, 10), gap: 8 }), 'Sprite SVG copied'));
$('#copy-group').addEventListener('click', () => copyText(createAvatarGroup(rosterItems(), { ...teamOptions(), max: parseInt($('#group-max').value, 10) }), 'Group mark copied'));
$('#copy-code').addEventListener('click', () => copyText(codeSnippet(), 'Code copied'));
$('#copy-link').addEventListener('click', () => { updateHash(); copyText(location.href, 'Link copied'); });
render();
}
init();
</script>
</body>
</html>