// 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 '
' + '' + '' + e.tag + '' + '' + (logPaIndex(e) >= 0 ? '' : '') + '' + '' + '
'; } return '
' + '' + e.text + '' + '
' + '' + e.tag + '' + '' + '
' + '
'; }).join(''); // Auto-focus the edit input if we just entered edit mode if(logEditIdx >= 0){ var inp = document.getElementById('logEditInput'); if(inp){ inp.focus(); inp.setSelectionRange(inp.value.length, inp.value.length); } } } // Show toggle when log has enough entries to overflow if(toggle){ toggle.style.display = G.log.length > 5 ? '' : 'none'; } } function logEditStart(idx){ logEditIdx = idx; renderLog(); } function logEditCancel(){ logEditIdx = -1; renderLog(); } function logEditSave(){ if(logEditIdx < 0 || logEditIdx >= G.log.length) return; var inp = document.getElementById('logEditInput'); if(!inp) return; var newText = inp.value.trim(); if(newText){ G.log[logEditIdx].text = newText; } logEditIdx = -1; renderLog(); saveToStorage(); } // The scorecard plate appearance a log line records, or -1 function logPaIndex(entry){ if(!entry || !entry.paId) return -1; for(var i = 0; i < G.pas.length; i++) if(G.pas[i].id === entry.paId) return i; return -1; } // "Edit play": the result belongs on the scorecard, where stats follow it function logEditPlay(idx){ var pi = logPaIndex(G.log[idx]); logEditIdx = -1; renderLog(); if(pi >= 0) openPaEditor(pi); } // Deleting a result line asks whether the play itself should go too function logEditDelete(idx){ if(idx < 0 || idx >= G.log.length) return; var pi = logPaIndex(G.log[idx]); if(pi < 0){ deleteLogLine(idx); return; } var pa = G.pas[pi]; showConfirm({ title: 'Remove the play too?', message: 'This line records ' + curNameForPa(pa) + ': ' + paLabel(pa.res) + ' (' + (pa.half === 'top' ? 'T' : 'B') + pa.inn + '). Remove that plate appearance from the scorecard and stats as well?', confirmLabel: 'Remove play', cancelLabel: 'Just the log line', tone: 'warn' }).then(function(removePlay){ var id = pa.id; deleteLogLine(idx); if(!removePlay) return; var at = -1; G.pas.forEach(function(q, i){ if(q.id === id) at = i; }); if(at < 0) return; saveState(); removePa(at, 'Log edit'); renderAll(); saveToStorage(); }); } function deleteLogLine(idx){ if(idx < 0 || idx >= G.log.length) return; // Undo snapshots that already contained this entry now span one fewer var len = G.log.length; HISTORY = HISTORY.map(function(raw){ var snap = JSON.parse(raw); var n = snap.G.logLen; if(n === undefined || idx < len - n) return raw; snap.G.logLen = n - 1; return JSON.stringify(snap); }); G.log.splice(idx, 1); logEditIdx = -1; renderLog(); saveToStorage(); } var logExpanded = false; function toggleLog(){ logExpanded = !logExpanded; var el = document.getElementById('logInner'); var toggle = document.getElementById('logToggle'); if(logExpanded){ el.classList.add('expanded'); if(toggle) toggle.textContent = '▲ Collapse log'; } else { el.classList.remove('expanded'); if(toggle) toggle.textContent = '▼ Show full log'; } } // Log filter event delegation (function(){ // Inning dropdown document.addEventListener('change', function(e){ if(e.target.id === 'logFilterInn'){ logFilter.inn = e.target.value; renderLog(); } }); // Category pill buttons document.addEventListener('click', function(e){ if(e.target.classList && e.target.classList.contains('log-fpill')){ var cat = e.target.dataset.filter; // Toggle: if already active, clear; otherwise set logFilter.cat = (logFilter.cat === cat) ? '' : cat; // Update pill active states var pills = document.querySelectorAll('.log-fpill'); pills.forEach(function(p){ p.classList.toggle('active', p.dataset.filter === logFilter.cat); }); renderLog(); } }); // Log edit input: Enter to save, Escape to cancel document.addEventListener('keydown', function(e){ if(e.target.id === 'logEditInput'){ if(e.key === 'Enter'){ e.preventDefault(); logEditSave(); } else if(e.key === 'Escape'){ e.preventDefault(); logEditCancel(); } } }); })(); // ── Haptic feedback ── function haptic(ms){ try { if(navigator.vibrate) navigator.vibrate(ms || 10); } catch(e){} } function badges(h){ var b = ''; var items = [ { key:'s', cls:'hb1', label:'1B' }, { key:'d', cls:'hb2', label:'2B' }, { key:'t', cls:'hb3', label:'3B' }, { key:'hr', cls:'hbhr', label:'HR' }, { key:'bb', cls:'hbbb', label:'BB' }, { key:'hbp', cls:'hbhbp', label:'HBP' }, { key:'kl', cls:'hbkl', label:'Ⓚ'}, { key:'ks', cls:'hbks', label:'K' }, { key:'fo', cls:'hbfo', label:'F' }, { key:'go', cls:'hbgo', label:'G' }, { key:'sb', cls:'hbsb', label:'SB' }, { key:'cs', cls:'hbcs', label:'CS' }, { key:'err', cls:'hberr', label:'E' }, { key:'sf', cls:'hbsf', label:'SF' }, { key:'sac', cls:'hbsac', label:'SAC' }, { key:'fc', cls:'hbfc', label:'FC' }, { key:'ibb', cls:'hbibb', label:'IBB' }, { key:'wp', cls:'hbwp', label:'WP' }, { key:'r', cls:'hbr', label:'R' }, { key:'rbi', cls:'hbrbi', label:'RBI' } ]; items.forEach(function(it){ if(h[it.key] > 0){ b += '' + (h[it.key] > 1 ? h[it.key] : '') + it.label + ''; } }); return b; } function playerOpts(side, selectedName, includeBlank) { var roster = ROSTERS[side]; var html = includeBlank ? '' : ''; roster.forEach(function(p){ var label = (p.jersey ? '#'+p.jersey+' ' : '') + p.name + ' ('+p.pos+')'; html += ''; }); if(!roster.length) html += ''; return html; } function onPlayerSelect(side, slotIdx, val) { G.lineup[side][slotIdx].name = val; // auto-fill position from roster if blank var match = ROSTERS[side].filter(function(p){ return p.name===val; })[0]; if(match && G.lineup[side][slotIdx].pos==='—') { G.lineup[side][slotIdx].pos = match.pos; } renderLineup(side); } function startSub(side,i){ G.lineup[side][i].pending=true; renderLineup(side); var el=document.getElementById(side+'_si_'+i)||document.getElementById(side+'_ss_'+i); if(el) el.focus(); } function cancelSub(side,i){ G.lineup[side][i].pending=false; renderLineup(side); } function confirmSub(side,i,subType){ saveState(); var st = subType || 'ph'; // default to pinch hitter // support both roster dropdown and free-text input var selEl = document.getElementById(side+'_ss_'+i); var inpEl = document.getElementById(side+'_si_'+i); var nm = selEl ? (selEl.value||'').trim() : (inpEl ? (inpEl.value||'').trim() : ''); if(!nm){ if(selEl) selEl.focus(); else if(inpEl) inpEl.focus(); return; } var pos=(document.getElementById(side+'_sp_'+i)||{}).value||'—'; // auto-fill position from roster if still blank if(pos==='—'){ var match=ROSTERS[side].filter(function(p){return p.name===nm;})[0]; if(match) pos=match.pos; } // For pinch runners, set position to PR if(st==='pr') pos='PR'; var prev=curName(side,i); G.lineup[side][i].subs.push({name:nm,pos:pos,inning:G.inning,half:G.half,hits:mkHits(),subType:st}); G.lineup[side][i].pending=false; var label = st==='pr' ? 'PR' : 'PH'; addLog(nm+' ('+label+') replaces '+prev+' (spot '+(i+1)+')','Sub','t-sub'); // If pinch runner, update the base they're on (replace the old runner name) if(st==='pr'){ for(var bi=0;bi<3;bi++){ if(G.bases[bi] && G.bases[bi] === prev){ G.bases[bi] = nm; break; } } renderBases(); } renderLineup(side); renderAtBatBar(); } function renderLineup(side){ scheduleScorecardRender(); var panel=document.getElementById(side+'Lineup'); var ab=side==='home'?G.homeBatter:G.awayBatter; var hasRoster = ROSTERS[side].length > 0; var isLoading = ROSTER_LOADING[side]; var html=''; for(var i=0;i<9;i++){ var sl=G.lineup[side][i]; var hasSubs=sl.subs.length>0; var isActive=(i===ab); html+='
'; html+='
'; html+=''+(i+1)+''; html+=''; html+=''; if(hasRoster && !hasSubs){ html+=''; } else if(isLoading && !hasSubs){ html+=''; } else { html+=''; } var hb=badges(sl.hits); if(hb) html+='
'+hb+'
'; if(!hasSubs&&!sl.pending){ html+=''; } html+='
'; for(var s=0;s'; html+=''; html+=''; var subBadges = sub.hits ? badges(sub.hits) : ''; if(isLast){ if(subBadges) html+='
'+subBadges+'
'; html+=''; if(!sl.pending){ html+=''; } } else { if(subBadges) html+='
'+subBadges+'
'; } html+='
'; } if(sl.pending){ html+='
↳ Sub in:'; html+=''; if(hasRoster){ html+=''; } else { html+=''; } html+=''; html+=''; html+=''; html+='
'; } 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 = ''; for(var i = 1; i <= n; i++){ var hasData = (G.batterLog.away['T' + i] && G.batterLog.away['T' + i].length > 0) || (G.batterLog.home['B' + i] && G.batterLog.home['B' + i].length > 0); var dotHint = hasData ? '' : ''; hdr += '' + i + dotHint + ''; } hdr += ''; hdr += 'RHE'; // Body rows var body = ''; ['away','home'].forEach(function(side){ var tName = team(side); var logo = TEAM_LOGOS[tName] ? '' : ''; var c = '' + logo + (sels[side] ? '' : esc(tName)) + ''; for(var i = 0; i < n; i++){ var v = G.scores[side][i]; var a = (G.inning - 1) === i ? 'active-inn' : ''; c += '' + (v === null ? '' : v) + ''; } c += ''; c += '' + G.rhe[side][0] + ''; c += '' + G.rhe[side][1] + ''; c += '' + G.rhe[side][2] + ''; c += ''; body += c; }); body += ''; tbl.innerHTML = hdr + body; var slots = tbl.querySelectorAll('.team-sel-slot'); for(var k = 0; k < slots.length; k++){ var sel = sels[slots[k].getAttribute('data-side')]; slots[k].appendChild(sel); sizeTeamSelect(sel); } } function renderInn(){ document.getElementById('innNum').textContent = G.inning; var b = document.getElementById('halfPill'); if(G.half === 'top'){ b.textContent = 'Top'; b.className = 'half-pill half-top'; } else { b.textContent = 'Bot'; b.className = 'half-pill half-bot'; } } function renderCount(){ for(var i = 0; i < 4; i++){ document.getElementById('b' + i).className = 'dot ball' + (i < G.balls ? ' on' : ''); } for(var i = 0; i < 2; i++){ document.getElementById('s' + i).className = 'dot strike' + (i < G.strikes ? ' on' : ''); } document.getElementById('f0').className = 'dot foul' + (G.fouls > 0 && G.strikes >= 2 ? ' on' : ''); document.getElementById('foulNote').textContent = G.fouls > 0 ? G.fouls + ' foul' + (G.fouls > 1 ? 's' : '') + ' this at-bat' : ''; renderABSTally(); renderAtBatBar(); } function renderABSTally(){ var el = document.getElementById('absTally'); if(!el) return; if(!G.abs) { el.innerHTML = ''; return; } var parts = []; ['away','home'].forEach(function(side){ var a = G.abs[side]; if(!a || a.challenged === 0) return; var tName = team(side); var won = a.overturned; var lost = a.challenged - a.overturned; parts.push(tName + ': ' + won + '✓ / ' + lost + '✕'); }); el.innerHTML = parts.length > 0 ? 'ABS: ' + parts.join(' · ') : ''; } function renderOuts(){ for(var i = 0; i < 3; i++){ document.getElementById('o' + i).className = 'dot out' + (i < G.outs ? ' on' : ''); } } function renderBases(){ syncPaBases(); scheduleScorecardRender(); var el = document.getElementById('infield'); if(el) el.innerHTML = infieldSVG(); renderFieldToggle(); } // ── Bases card view: the infield (default), or the home team's whole park ── // The choice is remembered on this device. Parks come from js/fields.js. var FIELD_VIEW_KEY = 'baseball_scorecard_field_view'; var _fieldView = 'infield'; try { if(localStorage.getItem(FIELD_VIEW_KEY) === 'full') _fieldView = 'full'; } catch(e){} function homeField(){ return (typeof FIELD_WALLS !== 'undefined' && FIELD_WALLS[team('home')]) || null; } function setFieldView(v){ _fieldView = v === 'full' ? 'full' : 'infield'; try { localStorage.setItem(FIELD_VIEW_KEY, _fieldView); } catch(e){} renderBases(); } function renderFieldToggle(){ var el = document.getElementById('fieldToggle'); if(!el) return; if(!homeField()){ el.innerHTML = ''; return; } // no home team yet: infield only el.innerHTML = [['infield', 'Infield'], ['full', 'Full field']].map(function(o){ return ''; }).join(''); } // ── Infield drawing (Bases card) ── // To scale in feet: home at (0,0), 90 ft base paths, mound at 60 ft 6 in, infield // dirt arc 95 ft around the rubber. Runners sit on the bases with name tags; each // base is a button that adds or removes a runner (toggleBase). var IF_BASES = [[63.64, 63.64], [0, 127.28], [-63.64, 63.64]]; // 1B, 2B, 3B var IF_VB = [-128, -176, 256, 210]; // feet, SVG coords (y down) var IF_PX = 260; // typical drawn width in CSS px (sizes the labels) function ifP(x, y){ return Math.round(x * 10) / 10 + ',' + Math.round(-y * 10) / 10; } // Wall pulled in toward home plate by the warning track's width function fieldTrackLine(wall, t){ var out = []; for(var i = 0; i < wall.length - 1; i++){ for(var j = 0; j < 8; j++){ var x = wall[i][0] + (wall[i + 1][0] - wall[i][0]) * j / 8, y = wall[i][1] + (wall[i + 1][1] - wall[i][1]) * j / 8; var L = Math.sqrt(x * x + y * y) || 1; out.push([x * (L - t) / L, y * (L - t) / L]); } } var e = wall[wall.length - 1], Le = Math.sqrt(e[0] * e[0] + e[1] * e[1]) || 1; out.push([e[0] * (Le - t) / Le, e[1] * (Le - t) / Le]); return out; } function infieldSVG(){ var F = _fieldView === 'full' ? homeField() : null; var VB = IF_VB; if(F){ var xs = F.w.map(function(p){ return p[0]; }), ys = F.w.map(function(p){ return p[1]; }); var minX = Math.min.apply(null, xs) - 14, maxX = Math.max.apply(null, xs) + 14, maxY = Math.max.apply(null, ys) + 14; VB = [Math.round(minX), -Math.round(maxY), Math.round(maxX - minX), Math.round(maxY + 30)]; } var k = VB[2] / IF_PX; // feet per CSS px, to size labels in px var lpX = -280, rpX = 280; // infield view: foul lines run off the drawing var pts = function(list){ return list.map(function(p){ return ifP(p[0], p[1]); }).join(' '); }; var s = ''; if(F){ var fair = [[0, 0]].concat(F.w); s += ''; s += ''; s += ''; s += ''; } else { s += ''; s += ''; s += ''; } s += ''; s += ''; s += ''; s += ''; if(F){ var lp = F.w[0], rp = F.w[F.w.length - 1]; s += ''; s += ''; s += ''; F.s.forEach(function(sg){ // MLB's posted distances, just inside the wall var a = sg[0] * Math.PI / 180, d = sg[1] - 14 * k; s += '' + sg[1] + ''; }); } else { s += ''; s += ''; } var b = F ? Math.max(7, 3.2 * k) : 7; // home plate: point toward the catcher, flat edge toward the pitcher s += ''; IF_BASES.forEach(function(q, i){ var occ = baseOcc(i), name = occ && typeof G.bases[i] === 'string' && G.bases[i] !== '?' ? shortName(G.bases[i]) : ''; var label = ['First', 'Second', 'Third'][i] + ' base: ' + (occ ? (name || 'runner') + ' on. Tap to clear' : 'empty. Tap to put a runner on'); s += ''; s += ''; s += ''; if(occ){ var r = 11 * k; s += ''; if(name){ var t = 11 * k, tw = (name.length * 0.56 * t) + 10 * k, th = t * 1.6; var ly = i === 1 ? -q[1] - r - 3 * k - th : -q[1] + r + 3 * k; var lx = Math.max(IF_VB[0] + 2, Math.min(IF_VB[0] + IF_VB[2] - tw - 2, q[0] - tw / 2)); s += ''; s += '' + esc(name) + ''; } } s += ''; }); return s + ''; } // Taps / Enter / Space on a base toggle a runner (bound once; the SVG re-renders) function setupInfieldDelegation(){ var el = document.getElementById('infield'); if(!el || el._bound) return; el._bound = true; function hit(e){ var g = e.target.closest && e.target.closest('.if-base'); if(!g) return false; var b = +g.dataset.base; toggleBase(b); var again = el.querySelector('.if-base[data-base="' + b + '"]'); if(again && e.type === 'keydown') again.focus(); return true; } el.addEventListener('click', hit); el.addEventListener('keydown', function(e){ if((e.key === 'Enter' || e.key === ' ') && hit(e)) e.preventDefault(); }); } function setActivePitcher(side, idx){ saveState(); G.pitchers[side].forEach(function(p, i){ p.active = (i === idx); }); var name = G.pitchers[side][idx].name || 'P' + (idx + 1); addLog(name + ' pitching for ' + team(side), 'P', 't-info'); renderPitchers(side); renderAtBatBar(); } function pitcherOpts(side, selectedName) { var pitchers = ROSTERS[side].filter(function(p){ return p.pos==='P' || p.pos==='SP' || p.pos==='RP'; }); if(!pitchers.length) return null; // no roster loaded — fall back to text input var html = ''; pitchers.forEach(function(p){ var label = (p.jersey ? '#'+p.jersey+' ' : '') + p.name; html += ''; }); return html; } function renderPitchers(side){ var panel=document.getElementById(side+'PitcherPanel'); var pp=G.pitchers[side]; var tName=team(side); var logo=TEAM_LOGOS[tName]?'':''; var html='
'+logo+''+tName+'tap row to set active
'; pp.forEach(function(p,i){ var a=p.active; var opts = pitcherOpts(side, p.name); html+='
'; html+=''; if(opts !== null){ html+=''; } else { html+=''; } html+=''+p.pitches+''; html+='
'+pitchingLine(p)+'
'; html+='
'; html+='
'; }); html+='
+Add pitcher
'; 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 = ''; 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); }