// Rendering the live game: score strip, at-bat bar, play log, lineups, count, outs, infield, pitchers and the pitching-line editor.
// Loaded as a plain script; files share one global scope (see index.html for the order).
function renderAll(){
renderScore();
renderInn();
renderCount();
renderOuts();
renderBases();
renderLineup('home');
renderLineup('away');
renderPitchers('home');
renderPitchers('away');
renderLog();
renderOutPanel();
renderAtBatBar();
restoreNotes();
// Sync hitWithErr toggle UI
var heb = document.getElementById('hitErrToggle');
if(heb) heb.className = 'hit-err-toggle' + (hitWithErr ? ' on' : '');
var heh = document.getElementById('hitErrHint');
if(heh) heh.textContent = hitWithErr ? 'Next hit will also charge an E to fielding team' : '';
}
// ── Coalesced log rendering ──
// Multiple addLog() calls in a single play (e.g. "Ball 4", "Walk", "Run scores")
// would otherwise each trigger a full innerHTML rebuild. Batch them into one
// render per animation frame, which keeps the hot pitch path cheap on mobile.
var _logRenderScheduled = false;
function scheduleLogRender(){
if(_logRenderScheduled) return;
_logRenderScheduled = true;
// rAF coalesces N calls in the current tick into one render next frame.
// Fallback to setTimeout(0) for very old environments, though modern iOS
// Safari and desktop browsers all have rAF.
var schedule = window.requestAnimationFrame || function(cb){ return setTimeout(cb, 0); };
schedule(function(){
_logRenderScheduled = false;
renderLog();
});
}
var logFilter = { inn: '', cat: '' };
var logEditIdx = -1;
// index into G.log currently being edited, -1 = none
function renderLog(){
// If a frame-scheduled render was pending, this sync call satisfies it.
_logRenderScheduled = false;
var el = document.getElementById('logInner');
var toggle = document.getElementById('logToggle');
var filtersEl = document.getElementById('logFilters');
if(!G.log.length){
el.innerHTML = '
No plays logged yet
';
if(toggle) toggle.style.display = 'none';
if(filtersEl) filtersEl.style.display = 'none';
return;
}
// Show filter bar
if(filtersEl) filtersEl.style.display = '';
// Update inning dropdown options
var innSelect = document.getElementById('logFilterInn');
if(innSelect){
var innings = {};
G.log.forEach(function(e){ if(e.inn) innings[e.inn] = true; });
var innKeys = Object.keys(innings).sort(function(a, b){
var na = parseInt(a.substring(1)), nb = parseInt(b.substring(1));
if(na !== nb) return na - nb;
return a < b ? -1 : 1; // T before B
});
var curVal = innSelect.value;
innSelect.innerHTML = '' + innKeys.map(function(k){
return '';
}).join('');
}
// Build filtered list with original indices
var filtered = [];
G.log.forEach(function(e, i){
if(logFilter.inn && e.inn !== logFilter.inn) return;
if(logFilter.cat && e.cat !== logFilter.cat) return;
filtered.push({ entry: e, idx: i });
});
if(filtered.length === 0){
el.innerHTML = '
No matching plays
';
} else {
el.innerHTML = filtered.map(function(f){
var e = f.entry;
var i = f.idx;
if(i === logEditIdx){
// Inline edit mode
return '
';
}
html+='';
}
panel.innerHTML=html;
}
function setAtBat(side, i){
saveState();
if(side === 'home') G.homeBatter = i;
else G.awayBatter = i;
addLog(curName(side, i) + ' up to bat', 'AB', 't-info');
renderLineup(side);
renderAtBatBar();
}
// Team pickers live in the box score's team cells. The table is rebuilt on every
// render, so park them first and put them back after (they keep their value).
function teamSelects(){ return { away: document.getElementById('teamAway'), home: document.getElementById('teamHome') }; }
// A native select is as wide as its longest option; size it to the chosen team instead
function sizeTeamSelect(sel){
var c = sizeTeamSelect.c = sizeTeamSelect.c || document.createElement('canvas');
var ctx = c.getContext && c.getContext('2d');
if(!ctx || !window.getComputedStyle) return;
var cs = getComputedStyle(sel), opt = sel.options[sel.selectedIndex];
ctx.font = cs.fontWeight + ' ' + cs.fontSize + ' ' + cs.fontFamily;
sel.style.width = Math.ceil(ctx.measureText(opt ? opt.text : '').width + 22) + 'px';
}
function renderScore(){
scheduleScorecardRender();
var n = G.totalInnings;
var tbl = document.getElementById('scoreTable');
var sels = teamSelects(), holder = document.getElementById('teamSelHolder');
['away', 'home'].forEach(function(s){ if(sels[s] && holder && tbl.contains(sels[s])) holder.appendChild(sels[s]); });
// Header row — clicking sets the inning AND shows the batter popover
var hdr = '
';
var chk = staffOutsCheck(side);
if(chk) html+='
⚠ Innings pitched add up to '+fmtIP(chk.credited)+', but this team has recorded '+fmtIP(chk.expected)+'. Tap a pitching line to fix it.
';
panel.innerHTML=html;
}
// Innings pitched in baseball notation: 17 outs → "5.2"
// Outs the fielding side has actually recorded (3 per completed half it
// fielded, plus the current half's outs) vs. the outs credited to its
// pitchers. Returns null when they agree or the game is over (final halves
// can end early, so they're not checked).
function staffOutsCheck(side){
if(G.log.some(function(l){ return l.tag === 'Final'; })) return null;
var completed = side === 'home'
? (G.half === 'bot' ? G.inning : G.inning - 1) // home fields the top halves
: G.inning - 1; // away fields the bottoms
var expected = completed * 3 + (fielding() === side ? G.outs : 0);
var credited = G.pitchers[side].reduce(function(n, p){ return n + (p.outs || 0); }, 0);
return expected === credited ? null : { expected: expected, credited: credited };
}
function fmtIP(outs){ return Math.floor(outs / 3) + '.' + (outs % 3); }
function pitchStrikes(p){ return Math.max(0, p.pitches - (p.balls || 0)); }
// "5.2 IP · 4 H · 2 R · 1 ER · 1 BB · 7 K · 1 HR · 88-57"
function pitchingLine(p){
if(!p.pitches && !p.outs) return '';
var parts = [fmtIP(p.outs) + ' IP', p.h + ' H', p.r + ' R', p.er + ' ER', p.bb + ' BB', p.k + ' K'];
if(p.hr > 0) parts.push(p.hr + ' HR');
parts.push('' + p.pitches + '-' + pitchStrikes(p) + '');
return parts.join(' · ');
}
// ── Pitching line editor ──
// Hand corrections for a pitcher's line (e.g. plays recorded before the app
// tracked IP/H per pitcher, or the official scorer changing a call).
var PLE_FIELDS = [
{k:'outs', label:'IP'}, {k:'h', label:'H'}, {k:'r', label:'R'}, {k:'er', label:'ER'},
{k:'bb', label:'BB'}, {k:'k', label:'K'}, {k:'hr', label:'HR'}
];
var _pleState = null;
// {side, idx}
// "5.1" → 16 outs; null if it isn't baseball IP notation
function parseIP(str){
var m = /^\s*(\d+)(?:\.([012]))?\s*$/.exec(str || '');
return m ? parseInt(m[1], 10) * 3 + (m[2] ? parseInt(m[2], 10) : 0) : null;
}
function openPitchLineEditor(side, idx){
var p = G.pitchers[side][idx];
if(!p) return;
closePitchLineEditor();
_pleState = { side: side, idx: idx };
var ov = document.createElement('div');
ov.className = 'rp-overlay';
ov.id = 'pleOverlay';
ov.addEventListener('click', function(e){ if(e.target === ov) closePitchLineEditor(); });
var chk = staffOutsCheck(side);
var html = '
';
PLE_FIELDS.forEach(function(f){
var v = f.k === 'outs' ? fmtIP(p.outs || 0) : (p[f.k] || 0);
html += '';
});
html += '
';
html += '
IP uses baseball notation: 5.1 = 5⅓ innings, 5.2 = 5⅔.'
+ (chk ? ' This team has recorded ' + fmtIP(chk.expected) + ' innings of outs so far; its pitchers are credited with ' + fmtIP(chk.credited) + '.' : '')
+ ' Pitch counts are changed with − / + on the row.
';
html += '
'
+ '
';
html += '
';
ov.innerHTML = html;
document.body.appendChild(ov);
var first = document.getElementById('ple_outs');
if(first){ first.focus(); first.select(); }
}
function closePitchLineEditor(){
_pleState = null;
var ov = document.getElementById('pleOverlay');
if(ov) ov.remove();
}
function savePitchLineEditor(){
if(!_pleState) return;
var side = _pleState.side, p = G.pitchers[side][_pleState.idx];
var vals = {}, bad = null;
PLE_FIELDS.forEach(function(f){
var inp = document.getElementById('ple_' + f.k);
inp.classList.remove('bad');
var v = f.k === 'outs' ? parseIP(inp.value) : (/^\s*\d+\s*$/.test(inp.value) ? parseInt(inp.value, 10) : null);
if(v === null){ inp.classList.add('bad'); bad = bad || inp; }
vals[f.k] = v;
});
if(bad){
bad.focus();
kbFlash(bad.id === 'ple_outs' ? 'IP like 5, 5.1 or 5.2' : 'Whole numbers only', '#BA7517');
return;
}
if(vals.er > vals.r){
var er = document.getElementById('ple_er');
er.classList.add('bad');
er.focus();
kbFlash('ER can\'t be more than R', '#BA7517');
return;
}
var changes = [];
PLE_FIELDS.forEach(function(f){
var old = p[f.k] || 0;
if(vals[f.k] !== old){
changes.push(f.label + ' ' + (f.k === 'outs' ? fmtIP(old) + '→' + fmtIP(vals[f.k]) : old + '→' + vals[f.k]));
}
});
closePitchLineEditor();
if(!changes.length) return;
saveState();
PLE_FIELDS.forEach(function(f){ p[f.k] = vals[f.k]; });
addLog('Pitching line edited: ' + (p.name || 'Pitcher') + ' — ' + changes.join(', '), 'Edit', 't-info');
renderPitchers(side);
saveToStorage();
}
function adj(side, i, d){
G.pitchers[side][i].pitches = Math.max(0, G.pitchers[side][i].pitches + d);
var n = G.pitchers[side][i].pitches;
var el = document.getElementById(side + 'pc' + i);
if(el){
el.textContent = n;
el.className = 'pc' + pitchCountClass(n);
}
schedulePitchLines();
}
function addPitcher(side){
var p = mkPitcher();
p.active = false;
G.pitchers[side].push(p);
renderPitchers(side);
}