-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
499 lines (458 loc) · 19 KB
/
app.js
File metadata and controls
499 lines (458 loc) · 19 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
// Data Model and Persistence
const STORAGE_KEY = 'ulc_state_v1';
/** @typedef {{id:string,name:string,gender:'M'|'W',position:'handler'|'cutter'|'both',pref:'O'|'D'|'either',available:boolean,pointsPlayed:number}} Player */
/** @typedef {{players: Player[], history: {timestamp:number, line:string[], context:'O'|'D', ratio:string}[], nextContext:'O'|'D', nextRatio:string, autoBase?: '4M-3W'|'3M-4W', score?: { us:number, them:number }, suppressNextScore?: boolean, halfSet?: boolean, ui?: { rosterCollapsed?: boolean, historyCollapsed?: boolean }}} AppState */
/** @type {AppState} */
let state = loadState();
function loadState() {
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (!raw) return { players: [], history: [], nextContext: 'O', nextRatio: 'auto' };
const parsed = JSON.parse(raw);
// Backfill defaults
parsed.players = (parsed.players || []).map(p => ({ available: true, pointsPlayed: 0, ...p }));
parsed.history = parsed.history || [];
parsed.nextContext = parsed.nextContext || 'O';
parsed.nextRatio = parsed.nextRatio || 'auto';
parsed.autoBase = parsed.autoBase || '4M-3W';
parsed.score = parsed.score || { us: 0, them: 0 };
parsed.suppressNextScore = parsed.suppressNextScore || false;
parsed.halfSet = parsed.halfSet || false;
parsed.ui = parsed.ui || { rosterCollapsed: false, historyCollapsed: false };
return parsed;
} catch (e) {
console.warn('Failed to load state, starting fresh', e);
return { players: [], history: [], nextContext: 'O', nextRatio: 'auto', autoBase: '4M-3W', score: { us: 0, them: 0 }, suppressNextScore: false, halfSet: false, ui: { rosterCollapsed: false, historyCollapsed: false } };
}
}
function saveState() {
localStorage.setItem(STORAGE_KEY, JSON.stringify(state));
}
// Utilities
const uid = () => Math.random().toString(36).slice(2, 9);
function byPointsAsc(a, b) { return a.pointsPlayed - b.pointsPlayed; }
function groupBy(arr, keyFn) {
return arr.reduce((acc, item) => {
const key = keyFn(item);
(acc[key] ||= []).push(item);
return acc;
}, {});
}
function compareByContextThenPoints(context) {
return (a, b) => {
const prefRank = (p) => p.pref === context ? 0 : (p.pref === 'either' ? 1 : 2);
const deltaPref = prefRank(a) - prefRank(b);
if (deltaPref !== 0) return deltaPref;
return a.pointsPlayed - b.pointsPlayed;
};
}
// Suggestion Algorithm
function parseRatio(ratio) {
if (ratio === 'auto') return 'auto';
const [m, w] = ratio.split('-');
const men = parseInt(m, 10);
const women = parseInt(w, 10);
return { men, women };
}
function flipRatio(r) { return r === '4M-3W' ? '3M-4W' : '4M-3W'; }
function nextAutoRatio(history, base) {
// Pattern: start with base at point 0, then flip for point 1, then every 2 points thereafter
// Sequence by point index n: base, flip, flip, base, base, flip, flip, ...
const n = history.length; // next point index
if (n === 0) return base;
const k = Math.ceil(n / 2); // 1 for n=1..2, 2 for n=3..4, 3 for n=5..6, ...
return (k % 2 === 1) ? flipRatio(base) : base;
}
/**
* Suggest a line of 7 players given state.nextContext and ratio.
* Preference: availability, fewest points played, matching pref and position balance.
*/
function suggestLine() {
const context = /** @type {'O'|'D'} */ (document.getElementById('contextSelect').value);
const ratioSel = document.getElementById('ratioSelect').value;
const ratio = ratioSel === 'auto' ? nextAutoRatio(state.history, state.autoBase || '4M-3W') : ratioSel;
const ratioParsed = parseRatio(ratio);
const available = state.players.filter(p => p.available);
const cmp = compareByContextThenPoints(context);
const men = available.filter(p => p.gender === 'M').sort(cmp);
const women = available.filter(p => p.gender === 'W').sort(cmp);
/** @type {Player[]} */
let chosen = [];
if (ratioParsed !== 'auto') {
const needMen = Math.min(ratioParsed.men, men.length);
const needWomen = Math.min(ratioParsed.women, women.length);
chosen.push(...men.slice(0, needMen));
chosen.push(...women.slice(0, needWomen));
}
// Fill remaining up to 7 with fewest points, matching context preference first
const remaining = 7 - chosen.length;
if (remaining > 0) {
const remainingPool = available
.filter(p => !chosen.some(c => c.id === p.id))
.sort(cmp);
chosen.push(...remainingPool.slice(0, remaining));
}
// If we over/under-filled gender due to availability, allow fewer than 7; UI will warn
renderLine(chosen, ratio);
}
// Rendering
function el(tag, attrs = {}, ...children) {
const e = document.createElement(tag);
for (const [k, v] of Object.entries(attrs)) {
if (k === 'class') e.className = v;
else if (k.startsWith('on') && typeof v === 'function') e.addEventListener(k.slice(2), v);
else if (v !== undefined && v !== null) e.setAttribute(k, String(v));
}
for (const child of children.flat()) {
if (child == null) continue;
e.append(child.nodeType ? child : document.createTextNode(String(child)));
}
return e;
}
function render() {
document.getElementById('contextSelect').value = state.nextContext;
document.getElementById('ratioSelect').value = state.nextRatio;
renderRoster();
renderLine([]);
renderHistory();
}
function renderRoster() {
const list = document.getElementById('rosterList');
list.innerHTML = '';
if (state.players.length === 0) {
list.append(el('div', { class: 'empty' }, 'No players yet. Add above.'));
return;
}
const sorted = [...state.players].sort((a, b) => a.name.localeCompare(b.name));
for (const p of sorted) {
const row = el('div', { class: 'row' },
el('div', {}, p.name,
' ', el('span', { class: `tag ${p.gender}` }, (p.gender === 'M' ? 'MM' : 'WM')),
' ', el('span', { class: 'tag' }, p.position),
' ', el('span', { class: 'tag' }, p.pref)
),
el('div', { class: 'muted' }, `Pts: ${p.pointsPlayed}`),
el('label', { class: 'availability' },
el('input', { type: 'checkbox', checked: p.available ? '' : null, oninput: () => { p.available = !p.available; saveState(); renderRoster(); } }),
'Available'
),
el('div', { class: 'actions' },
el('button', { onclick: () => editPlayer(p.id) }, 'Edit'),
el('button', { class: 'danger', onclick: () => deletePlayer(p.id) }, 'Delete')
)
);
list.append(row);
}
}
/** @param {Player[]} players */
function renderLine(players, usedRatio) {
const list = document.getElementById('lineList');
list.innerHTML = '';
const menCount = players.filter(p => p.gender === 'M').length;
const womenCount = players.filter(p => p.gender === 'W').length;
if (players.length === 0) list.append(el('div', { class: 'empty' }, 'No line yet. Click Suggest.'));
for (const p of players) {
const row = el('div', { class: 'row draggable' },
el('div', {}, p.name, ' ', el('span', { class: `tag ${p.gender}` }, (p.gender === 'M' ? 'MM' : 'WM'))),
el('div', { class: 'tags' }, el('span', { class: 'tag' }, p.position), el('span', { class: 'tag' }, p.pref)),
el('div', { class: 'actions' },
el('button', { onclick: () => replaceInLine(p.id) }, 'Replace'),
el('button', { class: 'danger', onclick: () => removeFromLine(p.id) }, 'Remove')
)
);
row.dataset.playerId = p.id;
list.append(row);
}
const info = el('div', { class: 'muted' }, `Total ${players.length}/7 • ${menCount}MM-${womenCount}WM` + (usedRatio ? ` • Target ${usedRatio.replace('M','MM').replace('W','WM')}` : ''));
list.prepend(info);
currentLine = players.map(p => p.id);
currentRatio = usedRatio || state.nextRatio;
}
function renderHistory() {
const list = document.getElementById('historyList');
list.innerHTML = '';
const scoreEl = document.getElementById('scoreDisplay');
if (scoreEl) scoreEl.textContent = `Us ${state.score?.us ?? 0} – ${state.score?.them ?? 0} Them`;
if (state.history.length === 0) {
list.append(el('div', { class: 'empty' }, 'No points recorded yet.'));
return;
}
const recent = [...state.history].slice(-12).reverse();
for (const h of recent) {
const names = h.line
.map(id => state.players.find(p => p.id === id)?.name || '—')
.join(', ');
list.append(el('div', { class: 'row ghost' },
el('div', {}, new Date(h.timestamp).toLocaleTimeString(), ' • ', h.context, ' • ', h.ratio),
el('div', { class: 'muted' }, names)
));
}
}
// Line editing state
let currentLine = [];
let currentRatio = state.nextRatio;
function replaceInLine(playerId) {
const dialog = document.getElementById('pickerDialog');
const list = document.getElementById('pickerList');
const gSel = document.getElementById('pickerGender');
const pSel = document.getElementById('pickerPosition');
gSel.value = 'any';
pSel.value = 'any';
function refresh() {
list.innerHTML = '';
const g = gSel.value;
const pos = pSel.value;
const pool = state.players.filter(p => p.available && !currentLine.includes(p.id) && p.id !== playerId);
const filtered = pool.filter(p => (g === 'any' || p.gender === g) && (pos === 'any' || p.position === pos || p.position === 'both'))
.sort(byPointsAsc);
if (filtered.length === 0) list.append(el('div', { class: 'empty' }, 'No matches'));
for (const p of filtered) {
const onPick = () => {
if (!playerId) {
if (currentLine.length >= 7) { alert('Line already has 7 players'); return; }
currentLine = [...currentLine, p.id];
} else {
currentLine = currentLine.map(id => id === playerId ? p.id : id);
}
renderLine(currentLine.map(id => state.players.find(s => s.id === id)).filter(Boolean), currentRatio);
dialog.close();
saveState();
};
const btn = el('button', { onclick: onPick }, `${p.name} (${p.pointsPlayed})`);
list.append(el('div', { class: 'row' }, btn));
}
}
gSel.oninput = refresh;
pSel.oninput = refresh;
refresh();
dialog.showModal();
}
function removeFromLine(playerId) {
currentLine = currentLine.filter(id => id !== playerId);
renderLine(currentLine.map(id => state.players.find(s => s.id === id)).filter(Boolean), currentRatio);
}
function confirmPlayed() {
if (currentLine.length === 0) return;
const context = /** @type {'O'|'D'} */ (document.getElementById('contextSelect').value);
const ratioSel = document.getElementById('ratioSelect').value;
const ratio = ratioSel === 'auto' ? currentRatio : ratioSel;
const isFirstPoint = state.history.length === 0;
for (const id of currentLine) {
const p = state.players.find(pl => pl.id === id);
if (p) p.pointsPlayed += 1;
}
state.history.push({ timestamp: Date.now(), line: [...currentLine], context, ratio });
// Score: D line -> Us +1, O line -> Them +1
state.score = state.score || { us: 0, them: 0 };
if (!isFirstPoint && !state.suppressNextScore) {
if (context === 'D') state.score.us += 1; else state.score.them += 1;
}
state.suppressNextScore = false; // reset after use
state.nextContext = context === 'O' ? 'D' : 'O';
state.nextRatio = ratioSel; // keep selection, even if auto
saveState();
render();
}
function undoLast() {
const last = state.history.pop();
if (!last) return renderHistory();
for (const id of last.line) {
const p = state.players.find(pl => pl.id === id);
if (p) p.pointsPlayed = Math.max(0, p.pointsPlayed - 1);
}
// Reverse score for the undone point
state.score = state.score || { us: 0, them: 0 };
if (last.context === 'D') state.score.us = Math.max(0, state.score.us - 1);
else state.score.them = Math.max(0, state.score.them - 1);
saveState();
render();
}
// Roster CRUD
function addPlayer(e) {
e.preventDefault();
const name = document.getElementById('playerName').value.trim();
const gender = document.getElementById('playerGender').value;
const position = document.getElementById('playerPosition').value;
const pref = document.getElementById('playerPref').value;
if (!name) return;
state.players.push({ id: uid(), name, gender, position, pref, available: true, pointsPlayed: 0 });
saveState();
e.target.reset();
renderRoster();
}
function editPlayer(id) {
const p = state.players.find(p => p.id === id);
if (!p) return;
const name = prompt('Name', p.name);
if (name == null) return; // cancel
const gender = prompt('Gender (M/W or MM/WM)', p.gender === 'M' ? 'MM' : 'WM');
const position = prompt('Position (handler/cutter/both)', p.position);
const pref = prompt('Pref (O/D/either)', p.pref);
p.name = name.trim() || p.name;
if (gender) {
const g = gender.toUpperCase();
if (g === 'MM') p.gender = 'M';
else if (g === 'WM') p.gender = 'W';
else if (g === 'M' || g === 'W') p.gender = g;
}
if (['handler', 'cutter', 'both'].includes(position)) p.position = position;
if (['O', 'D', 'either'].includes(pref)) p.pref = pref;
saveState();
renderRoster();
}
function deletePlayer(id) {
if (!confirm('Delete player?')) return;
state.players = state.players.filter(p => p.id !== id);
currentLine = currentLine.filter(pid => pid !== id);
saveState();
render();
}
// Import/Export
function exportTeam() {
const dataStr = 'data:text/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(state, null, 2));
const a = document.createElement('a');
a.href = dataStr;
a.download = 'ultimate_line_caller.json';
a.click();
}
function importTeam(file) {
const reader = new FileReader();
reader.onload = () => {
try {
const obj = JSON.parse(String(reader.result));
if (!obj || !Array.isArray(obj.players)) throw new Error('Invalid file');
state = loadState(); // ensure defaults
state.players = obj.players.map(p => ({ available: true, pointsPlayed: 0, ...p }));
state.history = obj.history || [];
state.nextContext = obj.nextContext || 'O';
state.nextRatio = obj.nextRatio || '4M-3W';
saveState();
render();
} catch (e) {
alert('Failed to import: ' + e.message);
}
};
reader.readAsText(file);
}
// Event bindings
window.addEventListener('DOMContentLoaded', () => {
document.getElementById('addPlayerForm').addEventListener('submit', addPlayer);
document.getElementById('exportBtn').addEventListener('click', exportTeam);
document.getElementById('importFile').addEventListener('change', (e) => {
const file = e.target.files?.[0];
if (file) importTeam(file);
e.target.value = '';
});
document.getElementById('suggestBtn').addEventListener('click', suggestLine);
const takeHalfBtn = document.getElementById('takeHalfBtn');
const halfDialogTitle = document.getElementById('halfDialogTitle');
const updateHalfButton = () => {
takeHalfBtn.textContent = state.halfSet ? 'End Game' : 'Take Half';
halfDialogTitle.textContent = state.halfSet ? 'Who scored the final point?' : 'Who took half?';
};
takeHalfBtn.addEventListener('click', () => {
document.getElementById('halfDialog').showModal();
});
document.getElementById('halfUsBtn').addEventListener('click', (e) => {
e.preventDefault();
state.score = state.score || { us: 0, them: 0 };
state.score.us += 1;
state.suppressNextScore = true;
if (!state.halfSet) state.halfSet = true; // after taking half, switch future to End Game
saveState();
renderHistory();
document.getElementById('halfDialog').close();
updateHalfButton();
});
document.getElementById('halfThemBtn').addEventListener('click', (e) => {
e.preventDefault();
state.score = state.score || { us: 0, them: 0 };
state.score.them += 1;
state.suppressNextScore = true;
if (!state.halfSet) state.halfSet = true;
saveState();
renderHistory();
document.getElementById('halfDialog').close();
updateHalfButton();
});
updateHalfButton();
document.getElementById('clearLineBtn').addEventListener('click', () => renderLine([]));
document.getElementById('confirmBtn').addEventListener('click', confirmPlayed);
document.getElementById('undoBtn').addEventListener('click', undoLast);
document.getElementById('clearHistoryBtn').addEventListener('click', () => {
if (!confirm('Start a new game? This clears history and resets score.')) return;
state.history = [];
state.score = { us: 0, them: 0 };
state.suppressNextScore = true;
state.halfSet = false; // reset End Game -> Take Half
saveState();
renderHistory();
// refresh half/end button label
const takeHalfBtn = document.getElementById('takeHalfBtn');
const halfDialogTitle = document.getElementById('halfDialogTitle');
if (takeHalfBtn && halfDialogTitle) {
takeHalfBtn.textContent = 'Take Half';
halfDialogTitle.textContent = 'Who took half?';
}
});
document.getElementById('addToLineBtn').addEventListener('click', () => replaceInLine('')); // opens picker
document.getElementById('contextSelect').addEventListener('input', (e) => { state.nextContext = e.target.value; saveState(); });
document.getElementById('ratioSelect').addEventListener('input', (e) => {
const val = e.target.value;
state.nextRatio = val;
if (val === '4M-3W' || val === '3M-4W') state.autoBase = val;
saveState();
});
// Roster collapsible
const rosterPanel = document.getElementById('rosterPanel');
const rosterToggleBtn = document.getElementById('rosterToggleBtn');
const applyCollapsed = () => {
rosterPanel.classList.toggle('collapsed', !!state.ui?.rosterCollapsed);
const expanded = !state.ui?.rosterCollapsed;
rosterToggleBtn.setAttribute('aria-expanded', String(expanded));
rosterToggleBtn.textContent = expanded ? 'Collapse' : 'Expand';
};
rosterToggleBtn.addEventListener('click', () => {
state.ui = state.ui || {};
// Default collapsed on small screens when first used
if (state.ui.rosterCollapsed == null) state.ui.rosterCollapsed = window.matchMedia('(max-width: 720px)').matches;
state.ui.rosterCollapsed = !state.ui.rosterCollapsed;
saveState();
applyCollapsed();
});
applyCollapsed();
// History collapsible
const historyPanel = document.getElementById('historyPanel');
const historyToggleBtn = document.getElementById('historyToggleBtn');
const applyHistoryCollapsed = () => {
historyPanel.classList.toggle('collapsed', !!state.ui?.historyCollapsed);
const expanded = !state.ui?.historyCollapsed;
historyToggleBtn.setAttribute('aria-expanded', String(expanded));
historyToggleBtn.textContent = expanded ? 'Collapse' : 'Expand';
};
historyToggleBtn.addEventListener('click', () => {
state.ui = state.ui || {};
state.ui.historyCollapsed = !state.ui.historyCollapsed;
saveState();
applyHistoryCollapsed();
});
applyHistoryCollapsed();
render();
// Build version: try Last-Modified of app.js
(async () => {
const el = document.getElementById('buildVersion');
if (!el) return;
try {
const res = await fetch(new URL('./app.js', location.href), { method: 'HEAD', cache: 'no-store' });
const lm = res.headers.get('last-modified');
if (lm) {
const dt = new Date(lm);
el.textContent = 'build version: ' + dt.toLocaleString();
return;
}
} catch (e) {
// ignore
}
el.textContent = 'build version: unknown';
})();
});