Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
42f897b7df |
No files matched your search
@@ -1,17 +0,0 @@
|
||||
name: Tests
|
||||
|
||||
on:
|
||||
push:
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- run: npm test
|
||||
@@ -1 +1,3 @@
|
||||
node_modules/
|
||||
coverage/
|
||||
*.log
|
||||
@@ -1,132 +1,26 @@
|
||||
# Baseball Scorecard
|
||||
# baseballscorecard
|
||||
|
||||
A live baseball scorecard for the browser, built for scoring MLB games pitch by pitch at the
|
||||
ballpark or on TV. It installs to an iPad or phone home screen and works offline.
|
||||
|
||||
**Live:** https://kburchtree.cloud/baseballscorecard/
|
||||
|
||||
## What it does
|
||||
|
||||
- **Score every pitch and play:** balls, strikes and fouls; hits, outs (F8, 6-3, double plays,
|
||||
fielder's choices, errors, sacrifices); walks, HBP, catcher's interference and strikeouts looking or swinging;
|
||||
steals, caught stealing, wild pitches, passed balls, balks, and runners put out on the bases.
|
||||
- **Bases card:** the infield for tracking runners, or the home team's whole park (the real outfield
|
||||
wall, warning track and distances for all 30 parks), remembered per device.
|
||||
- **ABS challenges**, including overturns that change the outcome of an at-bat.
|
||||
- **Scorecard grid:** batters by innings, with a diamond for every plate appearance (result,
|
||||
bases reached, out number). Tap a cell to correct it.
|
||||
- **Full stat lines:** batting (AB, R, H, RBI, BB, K, SB) and pitching (IP, H, R, ER, BB, K, HR,
|
||||
pitches-strikes), runners in scoring position, and left on base. Runs are charged to the
|
||||
pitcher who allowed the runner.
|
||||
- **MLB integration (MLB Stats API):** load today's games and lineups; **Check vs MLB** compares
|
||||
your scorecard with MLB's official play-by-play (plays, pitching lines, runs, errors and the count of the at-bat in progress) and fixes differences with a tap; **Catch up**
|
||||
fills in plays you missed and moves the game to MLB's current batter and count.
|
||||
**Follow MLB live** keeps the game caught up on its own while you watch (checks every ~20 s,
|
||||
never moves your count backward, pauses for open dialogs, stops at the final out, one device at a time).
|
||||
- **Season stats** across every saved game, filtered by team, games attended, and game type.
|
||||
- **Postseason series** at the top of My Games: saved playoff games grouped by round and teams,
|
||||
with the series score (e.g. "Yankees lead 2–1"), each game a tap away, and gaps marked
|
||||
"not scored".
|
||||
- **Sharing and saving:** a share-ready final image, a PDF scorecard, My Games, game files,
|
||||
backups of every game with a reminder (on a synced device, games in the cloud count as backed
|
||||
up), and offline use (service worker).
|
||||
- **Sync across devices** (Firebase): sign in once per device and My Games, season stats and
|
||||
backups are the same everywhere. Each device still saves locally first and works offline.
|
||||
|
||||
## Running it locally
|
||||
|
||||
There is no build step. Serve the folder with any static server:
|
||||
|
||||
```sh
|
||||
python3 -m http.server 8000
|
||||
# open http://localhost:8000/
|
||||
```
|
||||
|
||||
Pushing to `main` deploys to GitHub Pages.
|
||||
|
||||
## Code layout
|
||||
|
||||
`index.html` holds the markup; `css/app.css` the styles. The JavaScript is split by feature into
|
||||
plain scripts that share one global scope and load in this order:
|
||||
|
||||
| File | What's in it |
|
||||
| --- | --- |
|
||||
| `js/data.js` | Positions, MLB teams and ids, logos, ballparks and stadium photos, postseason rounds |
|
||||
| `js/fields.js` | Each park's outfield wall, warning track and distance signs for the Bases card's Full field view (generated by the stadium editor) |
|
||||
| `js/game.js` | Game state and schema migrations, undo, plate-appearance records, run charging, pitch and play-log basics |
|
||||
| `js/scoring.js` | Scoring actions: pitches, hits, outs, baserunning, ABS, innings, walk-offs |
|
||||
| `js/render.js` | Score strip, at-bat bar, play log, lineups, count, outs, infield, pitchers, pitching-line editor |
|
||||
| `js/scorecard.js` | The scorecard grid, its cell editor, the inning popover |
|
||||
| `js/mlb.js` | Today's games and lineups, Check vs MLB, catch-up |
|
||||
| `js/storage.js` | Autosave, My Games, game info, file export/import, reset, backups |
|
||||
| `js/reports.js` | PDF box score, Share final image, season stats, team pickers, stadium photo |
|
||||
| `js/firebase-config.js` | Firebase project settings for sync (public by design) |
|
||||
| `js/sync.js` | Sync: sign-in, uploading changed games, applying other devices' changes, conflict copies |
|
||||
| `js/follow.js` | Follow MLB live: periodic catch-up while watching, the header pill |
|
||||
| `js/ui.js` | Dialogs, keyboard shortcuts, event delegation, wake lock, startup (loads last) |
|
||||
|
||||
Code that runs while a file loads may only use things defined in the same or an earlier file.
|
||||
`sw.js` lists every file to cache for offline use; add new files there and bump `CACHE`.
|
||||
|
||||
When a saved game's shape changes, add the default to `migrateGame` (in `js/game.js`) so older
|
||||
games and backups keep loading.
|
||||
|
||||
## Sync (Firebase)
|
||||
|
||||
Games are stored at `users/{uid}/games/{gameId}` in Firestore, one document per game (the saved
|
||||
game as JSON plus a summary). `firestore.rules` lets each user read and write only their own
|
||||
games and accepts an update only if it's newer than the stored one; deletions are stored as
|
||||
`{ deleted: true }`. When an older edit loses, the app keeps it in My Games as a copy (left out
|
||||
of season stats).
|
||||
|
||||
Setup: create a Firebase project with Firestore and Email/Password sign-in (turn off public
|
||||
sign-ups and add the account in the console), paste `firestore.rules` into Firestore → Rules,
|
||||
add the site's domain to Authentication → Authorized domains, and put the web app's
|
||||
`firebaseConfig` in `js/firebase-config.js`. The Firebase compat libraries are bundled in
|
||||
`js/vendor/firebase` (Apache 2.0) and load only on signed-in devices.
|
||||
A single-file baseball scorecard web app. The entire app — markup, styles, and
|
||||
logic — lives in [`index.html`](index.html); just open it in a browser.
|
||||
|
||||
## Tests
|
||||
|
||||
The game-logic and schema-migration code is covered by a small
|
||||
[Vitest](https://vitest.dev/) suite. The tests load the real `index.html` into a
|
||||
[jsdom](https://github.com/jsdom/jsdom) window (see
|
||||
`test/helpers/loadApp.js`), so they exercise the shipped code directly with no
|
||||
build step or refactor required.
|
||||
|
||||
```sh
|
||||
npm install
|
||||
npm test
|
||||
npm install # one-time
|
||||
npm test # run the suite once
|
||||
npm run test:watch
|
||||
```
|
||||
|
||||
The tests load the real `index.html` and scripts into jsdom, with MLB data served from
|
||||
`tests/fixtures` (no network):
|
||||
Current coverage focuses on the highest-risk pure logic:
|
||||
|
||||
- `tests/mlb-games.test.js` catches up all four ALDS Game 1s of Oct 3, 2026 from an empty
|
||||
scorecard and checks the result against MLB: zero Check vs MLB differences (errors included), team RISP and
|
||||
left on base, the score, and every batter's and pitcher's line. ALDS Game 2 (Yankees–Rays,
|
||||
Oct 5, saved mid-game) checks that every kind of error is counted.
|
||||
- `tests/scoring.test.js` covers the hand-scoring rules (ABS overturns, reaching on an error,
|
||||
double plays, catcher's interference, outs on the bases, counts kept on runner outs, RISP, innings pitched,
|
||||
inherited runners, Undo, the cell editor, and loading older saved games).
|
||||
|
||||
- `tests/sync.test.js` runs two simulated devices against an in-memory Firebase: games
|
||||
appearing on the other device, following a game being scored elsewhere, deletions,
|
||||
offline changes uploading later, the newer-wins-plus-copy conflict rule, and the backup
|
||||
reminder standing down for games already in the cloud.
|
||||
- `tests/follow.test.js` covers Follow MLB: catching up, downloading only when MLB has an update,
|
||||
the count moving forward only, waiting for dialogs, Undo, finished games, another device following.
|
||||
- `tests/series.test.js` covers the postseason series view (grouping, series score, clinching,
|
||||
games not scored) and `tests/reports.test.js` the postseason logos.
|
||||
|
||||
The tests also run on every push (GitHub Actions).
|
||||
|
||||
## Credits
|
||||
|
||||
- Game data, lineups and team logos: [MLB Stats API](https://statsapi.mlb.com) and mlbstatic.com.
|
||||
- Stadium photos: each ballpark's lead photo on Wikipedia / Wikimedia Commons, credited in the
|
||||
app with the photographer and license.
|
||||
- Outfield walls: [GeomMLBStadiums](https://github.com/bdilday/GeomMLBStadiums) (MIT, Ben Dilday),
|
||||
adjusted by hand against satellite imagery; Truist Park from OpenStreetMap (© OpenStreetMap
|
||||
contributors, ODbL). Edited with a local tool and exported to `js/fields.js`.
|
||||
|
||||
## Scorebook redesign
|
||||
|
||||
The interface now includes a full matchup scoreboard, dedicated Live scoring / Scorecard / Lineups / Game notes views, and a compact game layout on phones. Use the **Line score** button on phones to expand the inning table after choosing both teams. Scoring, MLB follow, saved-game formats, sync, and backups use the existing game model.
|
||||
|
||||
The view tabs support Left / Right / Home / End, and the out indicators support Enter or Space. Print/PDF includes both teams and game notes regardless of the selected view. The service worker cache includes the new interface assets.
|
||||
|
||||
Run `npm test` for the 80 offline regression tests. Open `index.html` for a local visual preview, or serve this directory for full offline installation and network features. Browser-local saved games belong to their original site: use **More → Back up all games** and **More → Restore from backup** when moving to a different origin.
|
||||
- **Scoring rules** (`test/game-logic.test.js`): base-running advancement,
|
||||
forced advances on walks, run/RBI crediting, substitution-aware stats, and
|
||||
game-end / walk-off detection.
|
||||
- **Schema migrations** (`test/migrate.test.js`): `migrateGame()`, the single
|
||||
source of truth for loading older saved/imported games.
|
||||
|
Before Width: | Height: | Size: 20 KiB |
|
Before Width: | Height: | Size: 50 KiB |
|
Before Width: | Height: | Size: 57 KiB |
|
Before Width: | Height: | Size: 49 KiB |
|
Before Width: | Height: | Size: 57 KiB |
|
Before Width: | Height: | Size: 97 KiB |
@@ -1,894 +0,0 @@
|
||||
/* ── Reset & base ── */
|
||||
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: var(--bg); color: var(--text); font-size: 14px;
|
||||
padding-top: env(safe-area-inset-top);
|
||||
padding-bottom: env(safe-area-inset-bottom);
|
||||
padding-left: env(safe-area-inset-left);
|
||||
padding-right: env(safe-area-inset-right);
|
||||
}
|
||||
:root {
|
||||
--green:#1D9E75; --gl:#E1F5EE; --gc:#9FE1CB;
|
||||
--amber:#BA7517; --al:#FAEEDA; --ac:#FAC775;
|
||||
--red:#E24B4A; --rl:#FCEBEB;
|
||||
--blue:#185FA5; --bl:#E6F1FB;
|
||||
--purple:#534AB7; --pl:#EEEDFE;
|
||||
--teal:#0F6E56;
|
||||
--coral:#993C1D; --cl:#FAECE7;
|
||||
--border:#d6d4cc; --surface:#fff; --bg:#f5f4f0; --muted:#888780; --text:#1a1a1a;
|
||||
--radius:8px;
|
||||
--header-bg:#f0efe8;
|
||||
--out-color:#5f5e5a;
|
||||
--disabled:#ccc;
|
||||
--flyout-bg:#F1EFE8; --flyout-text:#5F5E5A; --flyout-border:#D3D1C7;
|
||||
--groundout-bg:#EAF3DE; --groundout-text:#3B6D11; --groundout-border:#C0DD97;
|
||||
--field-grass:#6aa86b; --field-foul:#5e9a60; --field-dirt:#c99b6c; --field-chalk:#ffffff; --field-wall:#24452a;
|
||||
}
|
||||
|
||||
@media(prefers-color-scheme: dark){
|
||||
:root {
|
||||
--green:#2BC48E; --gl:#0f2e22; --gc:#1a5c3f;
|
||||
--amber:#D4921F; --al:#2e2210; --ac:#6b4a15;
|
||||
--red:#F06060; --rl:#3a1a1a;
|
||||
--blue:#4A9FE5; --bl:#12253a;
|
||||
--purple:#7B73E0; --pl:#1e1c3a;
|
||||
--teal:#18B88A;
|
||||
--coral:#D06030; --cl:#2e1810;
|
||||
--border:#3a3a3a; --surface:#1e1e1e; --bg:#121212; --muted:#8a8a8a; --text:#e0e0e0;
|
||||
--header-bg:#252525;
|
||||
--out-color:#777;
|
||||
--disabled:#444;
|
||||
--flyout-bg:#252525; --flyout-text:#aaa; --flyout-border:#444;
|
||||
--groundout-bg:#1a2e18; --groundout-text:#6bbb40; --groundout-border:#2e5520;
|
||||
--field-grass:#33703d; --field-foul:#2c6034; --field-dirt:#8c6a4c; --field-chalk:#e8efe7; --field-wall:#0e1f12;
|
||||
}
|
||||
body { background:var(--bg); color:var(--text); }
|
||||
}
|
||||
|
||||
/* ── Layout ── */
|
||||
.app { max-width: 960px; margin: 0 auto; padding: 14px; }
|
||||
|
||||
/* Laptop / desktop: two columns. The scorecard, pitchers and play log stay in
|
||||
view on the right while scoring on the left. Narrower screens and print keep
|
||||
the single column, in the same order. */
|
||||
@media screen and (min-width: 1300px) {
|
||||
.app { max-width: 1800px; display: grid; grid-template-columns: minmax(700px, 1fr) minmax(520px, 740px); gap: 0 16px; align-items: start; }
|
||||
.col-main, .col-side { min-width: 0; }
|
||||
.col-side { position: sticky; top: 14px; max-height: calc(100vh - 28px); overflow-y: auto; overscroll-behavior: contain; }
|
||||
.col-side .log-inner { max-height: 40vh; }
|
||||
.col-side .log-inner.expanded { max-height: none; }
|
||||
}
|
||||
.header { display:flex; flex-direction:column; align-items:stretch; margin-bottom:12px; gap:8px; }
|
||||
/* Team pickers in the box score: look like the team name, with a small chevron */
|
||||
.team-cell { display:inline-flex; align-items:center; gap:5px; max-width:100%; vertical-align:middle; }
|
||||
.team-sel { -webkit-appearance:none; appearance:none; border:0; border-radius:6px; margin:0; font:inherit; font-weight:600; color:var(--text); cursor:pointer;
|
||||
padding:3px 16px 3px 3px; max-width:100%; text-overflow:ellipsis;
|
||||
background:transparent url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 10 6'%3E%3Cpath d='M1 1l4 4 4-4' fill='none' stroke='%23888' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E") no-repeat right 3px center / 9px 6px; }
|
||||
.team-sel:hover { background-color:var(--header-bg); }
|
||||
.team-sel:focus-visible { outline:2px solid var(--blue); outline-offset:1px; }
|
||||
.hdr-btns { display:flex; gap:8px; align-items:center; }
|
||||
.hdr-spacer { flex:1; }
|
||||
.reset-btn { padding:6px 14px; border:1px solid var(--border); border-radius:var(--radius); background:transparent; color:var(--muted); font-size:13px; cursor:pointer; }
|
||||
.add-inn-cell { width:28px; padding:0 2px!important; }
|
||||
.add-inn { width:22px; height:22px; border:1px dashed var(--border); border-radius:5px; background:transparent; color:var(--muted); font-size:14px; line-height:1; cursor:pointer; }
|
||||
.add-inn:hover { border-color:var(--blue); color:var(--blue); background:var(--bl); }
|
||||
#undoBtn:not(:disabled) { border-color:var(--amber); color:var(--amber); }
|
||||
#undoBtn:not(:disabled):hover { background:var(--al); }
|
||||
.pdf-btn { padding:6px 16px; border:none; border-radius:var(--radius); background:var(--blue); color:#fff; font-size:13px; font-weight:600; cursor:pointer; }
|
||||
.pdf-btn:hover { background:#1150a0; }
|
||||
.today-btn { padding:6px 14px; border:1.5px solid var(--green); border-radius:var(--radius); background:transparent; color:var(--green); font-size:13px; font-weight:600; cursor:pointer; }
|
||||
.today-btn:hover { background:var(--gl); }
|
||||
.today-btn:disabled { border-color:var(--disabled); color:var(--muted); cursor:wait; }
|
||||
|
||||
/* save/load dropdown menu */
|
||||
.save-menu-wrap { position:relative; }
|
||||
.save-menu { display:none; position:absolute; top:100%; right:0; margin-top:4px; background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); box-shadow:0 4px 16px rgba(0,0,0,.12); min-width:220px; z-index:50; overflow:hidden; }
|
||||
.save-menu.open { display:block; }
|
||||
.save-menu-item { display:block; width:100%; padding:9px 14px; font-size:13px; border:none; background:transparent; color:var(--text); cursor:pointer; text-align:left; font-family:inherit; }
|
||||
.save-menu-item:hover { background:var(--header-bg); }
|
||||
.save-menu-item + .save-menu-item { border-top:1px solid var(--border); }
|
||||
.save-menu-sep { height:4px; background:var(--header-bg); border-top:1px solid var(--border); }
|
||||
.save-menu-sep + .save-menu-item { border-top:1px solid var(--border); }
|
||||
.save-menu-danger { color:var(--red); }
|
||||
.save-menu-key { float:right; font-size:11px; color:var(--muted); border:1px solid var(--border); border-radius:4px; padding:0 5px; }
|
||||
.save-menu-hint { display:block; font-size:11px; color:var(--muted); margin-top:2px; }
|
||||
.save-menu-hint:empty { display:none; }
|
||||
.backup-nudge { display:flex; align-items:center; gap:8px; flex-wrap:wrap; background:var(--al); border:1px solid var(--ac); border-radius:var(--radius); padding:8px 10px 8px 12px; margin-bottom:10px; font-size:13px; color:var(--text); }
|
||||
.backup-nudge[hidden] { display:none; }
|
||||
.bn-text { flex:1; min-width:160px; }
|
||||
.bn-go { padding:6px 12px; font:inherit; font-size:13px; font-weight:600; border:none; border-radius:6px; background:var(--amber); color:#fff; cursor:pointer; }
|
||||
.bn-x { padding:4px 8px; font-size:16px; line-height:1; border:none; background:transparent; color:var(--muted); cursor:pointer; }
|
||||
|
||||
/* ── Game manager modal ── */
|
||||
.gm-overlay { position:fixed; inset:0; background:rgba(0,0,0,.4); z-index:200; display:flex; align-items:center; justify-content:center; padding:16px; }
|
||||
.gm-modal { background:var(--surface); border:1px solid var(--border); border-radius:12px; max-width:520px; width:100%; max-height:80vh; display:flex; flex-direction:column; box-shadow:0 8px 32px rgba(0,0,0,.2); }
|
||||
.gm-hdr { padding:14px 16px; border-bottom:1px solid var(--border); display:flex; justify-content:space-between; align-items:center; flex-shrink:0; }
|
||||
.gm-hdr h3 { font-size:15px; font-weight:700; color:var(--text); margin:0; }
|
||||
.gm-close { border:none; background:none; font-size:20px; cursor:pointer; color:var(--muted); line-height:1; padding:0 4px; }
|
||||
.gm-body { padding:0; overflow-y:auto; flex:1; }
|
||||
.gm-actions { padding:10px 16px; border-bottom:1px solid var(--border); display:flex; gap:8px; flex-wrap:wrap; flex-shrink:0; }
|
||||
.gm-save-btn { padding:7px 14px; font-size:12px; font-weight:600; border:none; border-radius:6px; background:var(--blue); color:#fff; cursor:pointer; }
|
||||
.gm-save-btn:hover { background:#1150a0; }
|
||||
.gm-new-btn { padding:7px 14px; font-size:12px; font-weight:600; border:1.5px solid var(--green); border-radius:6px; background:transparent; color:var(--green); cursor:pointer; }
|
||||
.gm-new-btn:hover { background:var(--gl); }
|
||||
.gm-card { display:flex; align-items:center; gap:10px; padding:10px 16px; border-bottom:1px solid var(--border); transition:background .1s; }
|
||||
.gm-card:last-child { border-bottom:none; }
|
||||
.gm-card:hover { background:var(--header-bg); }
|
||||
.gm-card.gm-active { background:var(--bl); }
|
||||
.gm-card-info { flex:1; min-width:0; }
|
||||
.gm-card-teams { font-size:13px; font-weight:600; color:var(--text); display:flex; align-items:center; gap:6px; }
|
||||
.gm-card-logo { width:18px; height:18px; object-fit:contain; }
|
||||
.gm-card-score { font-size:13px; font-weight:700; color:var(--text); margin-left:4px; }
|
||||
.gm-card-meta { font-size:11px; color:var(--muted); margin-top:2px; }
|
||||
.gm-card-active-badge { font-size:10px; font-weight:700; padding:2px 6px; border-radius:4px; background:var(--blue); color:#fff; flex-shrink:0; }
|
||||
.gm-card-btns { display:flex; gap:4px; flex-shrink:0; }
|
||||
.gm-card-btn { padding:4px 10px; font-size:11px; font-weight:600; border:1px solid var(--border); border-radius:5px; background:transparent; cursor:pointer; color:var(--muted); }
|
||||
.gm-card-btn:hover { background:var(--header-bg); }
|
||||
.gm-card-btn.gm-load { border-color:var(--blue); color:var(--blue); }
|
||||
.gm-card-btn.gm-load:hover { background:var(--bl); }
|
||||
.gm-card-btn.gm-del { border-color:var(--red); color:var(--red); }
|
||||
.gm-card-btn.gm-del:hover { background:var(--rl); }
|
||||
/* Postseason series (top of My Games) */
|
||||
.ps-series-wrap { padding:10px 16px 4px; border-bottom:1px solid var(--border); }
|
||||
.ps-series-title { font-size:11px; font-weight:700; letter-spacing:.06em; text-transform:uppercase; color:var(--muted); margin-bottom:6px; }
|
||||
.ps-series { border:1px solid var(--border); border-radius:8px; padding:8px 10px; margin-bottom:8px; }
|
||||
.ps-series-hdr { display:flex; align-items:center; gap:8px; flex-wrap:wrap; font-size:13px; font-weight:600; color:var(--text); }
|
||||
.ps-series-logo { width:34px; height:24px; object-fit:contain; background:#fff; border-radius:4px; padding:1px; }
|
||||
.ps-series-round { font-weight:700; }
|
||||
.ps-series-teams { display:inline-flex; align-items:center; gap:4px; margin-left:auto; }
|
||||
.ps-series-vs { color:var(--muted); font-weight:400; font-size:11px; }
|
||||
.ps-series-status { font-size:12px; font-weight:700; color:var(--blue); margin:4px 0 6px; }
|
||||
.ps-series-games { display:flex; flex-wrap:wrap; gap:4px; }
|
||||
.ps-game { padding:3px 8px; font-size:11px; font-weight:600; border:1px solid var(--border); border-radius:5px; background:transparent; color:var(--text); cursor:pointer; font-family:inherit; }
|
||||
button.ps-game:hover { background:var(--header-bg); }
|
||||
.ps-game-active { border-color:var(--blue); background:var(--bl); color:var(--blue); cursor:default; }
|
||||
.ps-game-missing { color:var(--muted); border-style:dashed; cursor:default; }
|
||||
.gm-empty { padding:24px 16px; text-align:center; color:var(--muted); font-size:13px; }
|
||||
|
||||
/* baserunner action picker */
|
||||
.br-picker-inner { margin-top:6px; padding:6px 0; }
|
||||
.br-picker-title { font-size:11px; color:var(--muted); font-weight:600; margin-bottom:4px; }
|
||||
.br-picker-btns { display:flex; gap:5px; flex-wrap:wrap; }
|
||||
.br-pick { padding:5px 10px; font-size:12px; font-weight:600; border:1.5px solid var(--border); border-radius:6px; background:transparent; cursor:pointer; color:var(--text); }
|
||||
.br-pick:hover { background:var(--header-bg); }
|
||||
.ro-fielders { width:100%; max-width:260px; padding:5px 8px; font:inherit; font-size:12px; border:1.5px solid var(--border); border-radius:6px; background:var(--surface); color:var(--text); }
|
||||
.br-pick-cancel { padding:5px 10px; font-size:12px; border:1px solid var(--border); border-radius:6px; background:transparent; cursor:pointer; color:var(--muted); }
|
||||
|
||||
/* ── Runner placement picker (post-hit) ── */
|
||||
.rp-overlay { position:fixed; inset:0; background:rgba(0,0,0,.4); z-index:200; display:flex; align-items:center; justify-content:center; padding:16px; }
|
||||
.rp-modal { background:var(--surface); border:1px solid var(--border); border-radius:12px; max-width:400px; width:100%; box-shadow:0 8px 32px rgba(0,0,0,.2); overflow:hidden; }
|
||||
.rp-hdr { padding:12px 16px; border-bottom:1px solid var(--border); display:flex; justify-content:space-between; align-items:center; }
|
||||
.rp-hdr h3 { font-size:14px; font-weight:700; color:var(--text); margin:0; }
|
||||
.rp-hdr-sub { font-size:11px; color:var(--muted); font-weight:400; }
|
||||
.rp-body { padding:10px 16px 14px; }
|
||||
.rp-runner { margin-bottom:10px; padding:8px 10px; border:1px solid var(--border); border-radius:8px; background:var(--header-bg); }
|
||||
.rp-runner:last-child { margin-bottom:0; }
|
||||
.rp-runner-name { font-size:12px; font-weight:600; color:var(--text); margin-bottom:6px; display:flex; align-items:center; gap:6px; }
|
||||
.rp-runner-from { font-size:11px; color:var(--muted); font-weight:400; }
|
||||
.rp-opts { display:flex; gap:5px; flex-wrap:wrap; }
|
||||
.rp-opt { padding:6px 12px; font-size:12px; font-weight:600; border:1.5px solid var(--border); border-radius:6px; background:var(--surface); cursor:pointer; color:var(--text); transition:border-color .1s, background .1s; }
|
||||
.rp-opt:hover { background:var(--header-bg); }
|
||||
.rp-opt.sel { border-color:var(--blue); background:var(--bl); color:var(--blue); }
|
||||
.rp-opt.sel-score { border-color:var(--green); background:var(--gl); color:var(--green); }
|
||||
.rp-opt.sel-out { border-color:var(--red); background:var(--rl); color:var(--red); }
|
||||
.rp-batter { margin-top:10px; padding:8px 10px; border:1px solid var(--border); border-radius:8px; background:var(--bl); font-size:12px; color:var(--blue); font-weight:600; }
|
||||
.rp-confirm { width:100%; margin-top:12px; padding:9px; font-size:13px; font-weight:600; border:none; border-radius:8px; background:var(--blue); color:#fff; cursor:pointer; }
|
||||
.rp-confirm:hover { background:#1150a0; }
|
||||
.rp-confirm:disabled { background:var(--disabled); cursor:not-allowed; }
|
||||
.rp-skip { width:100%; margin-top:6px; padding:7px; font-size:12px; font-weight:500; border:1px solid var(--border); border-radius:8px; background:transparent; color:var(--muted); cursor:pointer; }
|
||||
.rp-skip:hover { background:var(--header-bg); }
|
||||
.rp-diamond-wrap { display:flex; justify-content:center; margin:8px 0 4px; }
|
||||
|
||||
/* games modal */
|
||||
.games-overlay { position:fixed; inset:0; background:rgba(0,0,0,.4); z-index:200; display:flex; align-items:center; justify-content:center; padding:16px; }
|
||||
.games-modal { background:var(--surface); border:1px solid var(--border); border-radius:12px; max-width:480px; width:100%; max-height:80vh; overflow-y:auto; box-shadow:0 8px 32px rgba(0,0,0,.2); }
|
||||
.games-modal-hdr { padding:14px 16px; border-bottom:1px solid var(--border); display:flex; justify-content:space-between; align-items:center; }
|
||||
.games-modal-hdr h3 { font-size:15px; font-weight:700; color:var(--text); margin:0; }
|
||||
.games-modal-close { border:none; background:none; font-size:20px; cursor:pointer; color:var(--muted); line-height:1; padding:0 4px; }
|
||||
.games-modal-body { padding:8px 0; }
|
||||
.game-card { display:flex; align-items:center; gap:10px; padding:10px 16px; cursor:pointer; border-bottom:1px solid var(--border); transition:background .1s; }
|
||||
.game-card:last-child { border-bottom:none; }
|
||||
.game-card:hover { background:var(--header-bg); }
|
||||
.game-card-teams { flex:1; }
|
||||
.game-card-away, .game-card-home { display:flex; align-items:center; gap:6px; font-size:13px; font-weight:600; color:var(--text); }
|
||||
.game-card-away { margin-bottom:2px; }
|
||||
.game-card-at { font-size:10px; color:var(--muted); margin-left:22px; }
|
||||
.game-card-logo { width:20px; height:20px; object-fit:contain; }
|
||||
.game-card-time { font-size:12px; color:var(--muted); text-align:right; min-width:60px; flex-shrink:0; }
|
||||
.game-card-status { font-size:11px; padding:2px 6px; border-radius:4px; font-weight:600; flex-shrink:0; }
|
||||
.game-card-status.live { background:var(--rl); color:var(--red); }
|
||||
.game-card-status.final { background:var(--header-bg); color:var(--muted); }
|
||||
.game-card-status.pre { background:var(--gl); color:var(--green); }
|
||||
.games-empty { padding:24px 16px; text-align:center; color:var(--muted); font-size:14px; }
|
||||
.games-loading { padding:24px 16px; text-align:center; color:var(--muted); font-size:14px; }
|
||||
|
||||
/* ── Score strip ── */
|
||||
.score-strip { background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); overflow-x:auto; margin-bottom:10px; }
|
||||
.score-table { width:100%; border-collapse:collapse; min-width:440px; }
|
||||
.score-table th, .score-table td { padding:6px 8px; text-align:center; font-size:13px; border-right:1px solid var(--border); }
|
||||
.score-table th:last-child, .score-table td:last-child { border-right:none; }
|
||||
.score-table thead th { background:var(--header-bg); font-weight:600; font-size:11px; color:var(--muted); }
|
||||
.team-label { text-align:left!important; font-weight:600; padding-left:12px!important; min-width:80px; }
|
||||
.total-cell { font-weight:600; background:var(--header-bg); }
|
||||
.inning-cell { cursor:pointer; min-width:30px; }
|
||||
.inning-cell:hover { background:var(--header-bg); }
|
||||
.inning-cell .score-edit { width:28px; padding:2px; font-size:13px; text-align:center; border:1.5px solid var(--blue); border-radius:4px; background:var(--surface); color:var(--text); font-family:inherit; font-weight:600; outline:none; -moz-appearance:textfield; }
|
||||
.inning-cell .score-edit::-webkit-outer-spin-button,
|
||||
.inning-cell .score-edit::-webkit-inner-spin-button { -webkit-appearance:none; margin:0; }
|
||||
.active-inn { background:var(--bl)!important; color:var(--blue); font-weight:600; }
|
||||
.score-table tr { border-top:1px solid var(--border); }
|
||||
|
||||
/* ── Game state cards ── */
|
||||
.game-state { display:grid; grid-template-columns:1fr 1fr 1fr; gap:10px; margin-bottom:10px; }
|
||||
@media(max-width:520px){ .game-state{ grid-template-columns:1fr 1fr; } }
|
||||
.card { background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); padding:10px 12px; }
|
||||
.label { font-size:10px; color:var(--muted); text-transform:uppercase; letter-spacing:.05em; margin-bottom:6px; }
|
||||
|
||||
/* indicators */
|
||||
.dot-row { display:flex; gap:5px; align-items:center; flex-wrap:wrap; }
|
||||
.dot { width:20px; height:20px; border-radius:50%; border:1.5px solid var(--border); cursor:pointer; flex-shrink:0; }
|
||||
.dot.ball.on { background:var(--green); border-color:var(--green); }
|
||||
.dot.strike.on { background:var(--red); border-color:var(--red); }
|
||||
.dot.foul.on { background:var(--purple); border-color:var(--purple); }
|
||||
.dot.out.on { background:var(--out-color); border-color:var(--out-color); }
|
||||
.dlabel { font-size:12px; color:var(--muted); margin-right:2px; }
|
||||
.btns { display:flex; gap:4px; margin-top:6px; flex-wrap:wrap; }
|
||||
.btn { padding:3px 9px; font-size:12px; border:1px solid var(--border); border-radius:6px; background:transparent; cursor:pointer; color:var(--text); }
|
||||
.btn:hover { background:var(--header-bg); }
|
||||
.btn.ball { border-color:var(--green); color:var(--green); }
|
||||
.btn.strike { border-color:var(--red); color:var(--red); }
|
||||
.btn.foul { border-color:var(--purple); color:var(--purple); }
|
||||
/* Primary count buttons — ball/strike/foul are tapped constantly during a
|
||||
game, so they get a bigger tap target and more visual weight. */
|
||||
.btn.big { padding:10px 16px; font-size:15px; font-weight:700; border-width:1.5px; flex:1; min-width:64px; }
|
||||
.btn.big:active { transform:scale(.97); }
|
||||
.btn.big.ball { background:var(--gl); }
|
||||
.btn.big.strike { background:var(--rl); }
|
||||
.btn.big.foul { background:var(--pl); }
|
||||
@media(prefers-color-scheme: dark){
|
||||
.btn.big.ball { background:rgba(43,196,142,.12); }
|
||||
.btn.big.strike { background:rgba(240,96,96,.12); }
|
||||
.btn.big.foul { background:rgba(123,115,224,.12); }
|
||||
}
|
||||
|
||||
/* inning ctrl */
|
||||
.inn-ctrl { display:flex; align-items:center; gap:8px; }
|
||||
.inn-num { font-size:24px; font-weight:600; cursor:pointer; user-select:none; border-radius:4px; padding:0 4px; transition:background .1s; }
|
||||
.inn-num:hover { background:var(--header-bg); }
|
||||
.inn-num:active { background:var(--bl); }
|
||||
.half-pill { font-size:11px; padding:2px 8px; border-radius:20px; font-weight:600; }
|
||||
.half-top { background:var(--bl); color:var(--blue); }
|
||||
.half-bot { background:var(--al); color:var(--amber); }
|
||||
.arr { width:26px; height:26px; border:1px solid var(--border); border-radius:6px; background:transparent; cursor:pointer; font-size:15px; color:var(--muted); display:flex; align-items:center; justify-content:center; }
|
||||
.arr:hover { background:var(--header-bg); }
|
||||
.half-tog { font-size:12px; padding:3px 8px; border:1px solid var(--border); border-radius:6px; background:transparent; cursor:pointer; color:var(--muted); margin-top:4px; }
|
||||
.half-tog:hover { background:var(--header-bg); }
|
||||
.foul-note { font-size:11px; color:var(--muted); margin-top:3px; font-style:italic; }
|
||||
|
||||
/* bases */
|
||||
.bases-wrap { display:flex; justify-content:center; padding:4px 0; }
|
||||
.bases-field { display:flex; flex-direction:column; gap:8px; }
|
||||
.bases-label { display:flex; align-items:center; gap:8px; }
|
||||
.field-toggle { margin-left:auto; display:inline-flex; border:1px solid var(--border); border-radius:6px; overflow:hidden; text-transform:none; letter-spacing:0; }
|
||||
.field-toggle:empty { display:none; }
|
||||
.field-toggle button { border:0; background:transparent; color:var(--muted); font:inherit; font-size:11px; font-weight:600; padding:2px 8px; cursor:pointer; }
|
||||
.field-toggle button.on { background:var(--blue); color:#fff; }
|
||||
.infield { line-height:0; }
|
||||
.infield svg { display:block; width:100%; max-width:280px; height:auto; margin:0 auto; border-radius:6px; }
|
||||
.if-base { cursor:pointer; outline:none; }
|
||||
.if-base:focus-visible rect { stroke:var(--blue); stroke-width:2; }
|
||||
.stadium-slot { margin-top:12px; }
|
||||
.stadium-slot:empty { display:none; }
|
||||
.stadium-photo { margin:0; display:flex; flex-direction:column; gap:3px; min-width:0; }
|
||||
.stadium-photo img { display:block; width:100%; aspect-ratio:16/7; object-fit:cover; border-radius:6px; background:var(--header-bg); }
|
||||
.stadium-photo figcaption { display:flex; justify-content:space-between; align-items:baseline; gap:8px; min-width:0; }
|
||||
.stadium-name { font-size:11px; font-weight:600; color:var(--text); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
|
||||
.stadium-credit { font-size:9px; color:var(--muted); text-decoration:none; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
|
||||
.stadium-credit:hover { text-decoration:underline; }
|
||||
.stadium-photo-off img { display:none; }
|
||||
.runner-labels { display:none; }
|
||||
.runner-labels { margin-top:2px; font-size:10px; color:var(--muted); line-height:1.4; text-align:center; }
|
||||
.runner-labels span { display:inline-block; margin:0 3px; }
|
||||
.runner-labels .rlabel-on { color:var(--amber); font-weight:600; }
|
||||
|
||||
/* action row */
|
||||
.action-row { display:grid; grid-template-columns:1fr 1fr; gap:10px; margin-bottom:10px; }
|
||||
@media(max-width:480px){ .action-row{ grid-template-columns:1fr; } }
|
||||
.hit-btns { display:grid; grid-template-columns:repeat(6,1fr); gap:6px; margin-top:6px; }
|
||||
.hit-btn { padding:8px 4px; font-size:13px; font-weight:600; border-radius:8px; cursor:pointer; text-align:center; border:1.5px solid; }
|
||||
.hit-btn:active { opacity:.75; }
|
||||
.h1b { background:var(--gl); color:var(--teal); border-color:var(--gc); }
|
||||
.h2b { background:var(--bl); color:var(--blue); border-color:#B5D4F4; }
|
||||
.h3b { background:var(--pl); color:var(--purple); border-color:#CECBF6; }
|
||||
.hhr { background:var(--rl); color:var(--red); border-color:#F7C1C1; }
|
||||
.hhbp { background:#FAEEDA; color:#BA7517; border-color:#FAC775; }
|
||||
.hibb { background:var(--gl); color:var(--teal); border-color:var(--gc); }
|
||||
.hlabel { font-size:10px; font-weight:400; display:block; color:inherit; opacity:.75; margin-top:1px; }
|
||||
.hit-err-toggle { font-size:12px; padding:3px 10px; border:1.5px solid var(--border); border-radius:6px; background:transparent; cursor:pointer; color:var(--muted); font-weight:600; }
|
||||
.hit-err-toggle.on { border-color:#BA7517; color:#BA7517; background:#FAEEDA; }
|
||||
.hit-err-hint { font-size:11px; color:var(--muted); font-style:italic; }
|
||||
.ko-btns { display:grid; grid-template-columns:1fr 1fr; gap:6px; margin-top:6px; }
|
||||
.ko-btn { padding:8px 6px; font-size:13px; font-weight:600; border-radius:8px; cursor:pointer; text-align:center; border:1.5px solid; }
|
||||
.ko-btn:active { opacity:.75; }
|
||||
.kol { background:var(--cl); color:var(--coral); border-color:#F5C4B3; }
|
||||
.kos { background:var(--rl); color:var(--red); border-color:#F7C1C1; }
|
||||
.kolabel { font-size:10px; font-weight:400; display:block; color:inherit; opacity:.75; margin-top:1px; }
|
||||
|
||||
/* ── Out recording ── */
|
||||
.out-card { background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); padding:10px 12px; margin-bottom:10px; }
|
||||
.out-type-row { display:grid; grid-template-columns:1fr 1fr 1fr 1fr; gap:8px; margin-top:6px; }
|
||||
.out-type-btn { padding:9px 6px; font-size:13px; font-weight:600; border-radius:8px; cursor:pointer; text-align:center; border:1.5px solid; transition:box-shadow .1s; }
|
||||
.out-type-btn:active { opacity:.75; }
|
||||
.otf { background:var(--flyout-bg); color:var(--flyout-text); border-color:var(--flyout-border); }
|
||||
.otg { background:var(--groundout-bg); color:var(--groundout-text); border-color:var(--groundout-border); }
|
||||
.ote { background:#FAEEDA; color:#BA7517; border-color:#FAC775; }
|
||||
.otfc { background:var(--pl); color:var(--purple); border-color:#CECBF6; }
|
||||
.out-type-btn.sel { box-shadow:inset 0 0 0 2px currentColor; }
|
||||
.fielder-grid { display:grid; grid-template-columns:repeat(5,1fr); gap:5px; margin-top:8px; }
|
||||
.fld-btn { position:relative; padding:5px 2px; font-size:11px; border:1px solid var(--border); border-radius:6px; background:transparent; cursor:pointer; text-align:center; color:var(--muted); line-height:1.3; }
|
||||
.fld-seq { position:absolute; top:2px; right:2px; min-width:12px; height:12px; padding:0 2px; border-radius:7px; font-size:8px; font-weight:700; line-height:12px; text-align:center; background:var(--blue); color:var(--surface); }
|
||||
.fld-btn:hover { background:var(--header-bg); }
|
||||
.fld-btn.sel { background:var(--bl); border-color:var(--blue); color:var(--blue); font-weight:700; }
|
||||
.fld-btn.sel-err { background:#FAEEDA; border-color:#FAC775; color:#BA7517; font-weight:700; }
|
||||
.fld-num { font-size:14px; font-weight:700; display:block; }
|
||||
.fld-pos-name { font-size:9px; display:block; opacity:.8; }
|
||||
.rec-out-btn { width:100%; margin-top:8px; padding:7px; font-size:13px; font-weight:600; border:none; border-radius:8px; background:var(--blue); color:#fff; cursor:pointer; }
|
||||
.rec-out-btn:hover { background:#1150a0; }
|
||||
.rec-out-btn.rec-err-btn { background:#BA7517; }
|
||||
.rec-out-btn.rec-err-btn:hover { background:#9a6010; }
|
||||
.rec-out-btn:disabled { background:var(--disabled); cursor:not-allowed; }
|
||||
.multi-out-btn { padding:5px 12px; font-size:12px; font-weight:700; border:1.5px solid var(--border); border-radius:6px; background:transparent; cursor:pointer; color:var(--muted); text-align:center; line-height:1; }
|
||||
.multi-out-btn.sel { border-color:#534AB7; color:#534AB7; background:#EEEDFE; }
|
||||
.out-hint { font-size:11px; color:var(--muted); margin-top:4px; text-align:center; }
|
||||
.hberr { background:#FAEEDA; color:#BA7517; }
|
||||
.hbsf { background:#E6F1FB; color:#185FA5; }
|
||||
.hbsac { background:#EEEDFE; color:#534AB7; }
|
||||
|
||||
/* sacrifice toggle buttons */
|
||||
.sac-toggle-row { display:flex; gap:6px; align-items:center; margin-top:6px; }
|
||||
.sac-toggle { padding:4px 10px; font-size:12px; font-weight:700; border:1.5px solid var(--border); border-radius:6px; background:transparent; cursor:pointer; color:var(--muted); text-align:center; line-height:1.2; }
|
||||
.sac-toggle.sel-sf { border-color:#185FA5; color:#185FA5; background:#E6F1FB; }
|
||||
.sac-toggle.sel-sac { border-color:#534AB7; color:#534AB7; background:#EEEDFE; }
|
||||
.sac-hint { font-size:11px; color:var(--muted); font-style:italic; }
|
||||
|
||||
/* inning popover */
|
||||
.inn-popover { position:absolute; z-index:100; background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); box-shadow:0 4px 16px rgba(0,0,0,.12); padding:8px 12px; min-width:140px; max-width:220px; font-size:12px; }
|
||||
.inn-popover-title { font-weight:600; font-size:11px; color:var(--muted); text-transform:uppercase; letter-spacing:.04em; margin-bottom:4px; }
|
||||
.inn-popover-half { margin-bottom:6px; }
|
||||
.inn-popover-half:last-child { margin-bottom:0; }
|
||||
.inn-popover-batter { padding:1px 0; color:var(--text); }
|
||||
.inn-popover-close { position:absolute; top:4px; right:8px; border:none; background:none; font-size:16px; cursor:pointer; color:var(--muted); line-height:1; }
|
||||
.sec-title { font-size:11px; color:var(--muted); text-transform:uppercase; letter-spacing:.05em; margin-bottom:6px; }
|
||||
|
||||
/* lineup */
|
||||
.lineup-grid { display:grid; grid-template-columns:1fr 1fr; gap:10px; margin-bottom:10px; }
|
||||
@media(max-width:480px){ .lineup-grid{ grid-template-columns:1fr; } }
|
||||
.lineup-panel { background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); overflow:hidden; }
|
||||
.lineup-hdr { padding:8px 12px; background:var(--header-bg); display:flex; justify-content:space-between; align-items:center; font-size:13px; font-weight:600; border-bottom:1px solid var(--border); }
|
||||
.lineup-slot { border-bottom:1px solid var(--border); }
|
||||
.lineup-slot:last-child { border-bottom:none; }
|
||||
.lineup-row { display:flex; align-items:center; gap:5px; padding:5px 8px; }
|
||||
.lineup-row.dimmed { opacity:.42; }
|
||||
.bnum { font-size:12px; color:var(--muted); width:14px; text-align:center; flex-shrink:0; }
|
||||
.bname { flex:1; font-size:13px; background:transparent; border:none; color:var(--text); font-family:inherit; outline:none; min-width:0; }
|
||||
.bname:disabled { color:var(--muted); }
|
||||
.roster-sel { flex:1; font-size:13px; padding:3px 6px; border:1px solid var(--border); border-radius:6px; background:var(--surface); color:var(--text); font-family:inherit; cursor:pointer; min-width:60px; max-width:100%; }
|
||||
.pos-sel { width:52px; font-size:12px; padding:3px 2px; border:1px solid var(--border); border-radius:6px; background:var(--surface); color:var(--muted); font-family:inherit; cursor:pointer; flex-shrink:0; }
|
||||
.pos-sel:disabled { opacity:.5; }
|
||||
.ab-dot { width:8px; height:8px; border-radius:50%; background:var(--blue); flex-shrink:0; }
|
||||
.ab-dot.hidden { background:transparent; }
|
||||
.set-btn { font-size:11px; padding:2px 5px; border:1px solid var(--border); border-radius:4px; background:transparent; cursor:pointer; color:var(--muted); flex-shrink:0; }
|
||||
.set-btn:hover { background:var(--header-bg); }
|
||||
.sub-btn { font-size:11px; padding:2px 5px; border:1px solid var(--gc); border-radius:4px; background:transparent; cursor:pointer; color:var(--teal); flex-shrink:0; }
|
||||
.sub-btn:hover { background:var(--gl); }
|
||||
/* sub rows */
|
||||
.sub-row { display:flex; align-items:center; gap:5px; padding:4px 8px 4px 18px; background:var(--gl); border-top:1px solid var(--gc); }
|
||||
.sub-arrow { font-size:13px; color:var(--teal); flex-shrink:0; }
|
||||
.sub-inn { font-size:10px; padding:1px 5px; border-radius:3px; background:var(--gc); color:var(--teal); font-weight:600; flex-shrink:0; white-space:nowrap; }
|
||||
.sub-pos { width:52px; font-size:12px; padding:3px 2px; border:1px solid var(--gc); border-radius:6px; background:var(--surface); color:var(--teal); font-family:inherit; cursor:pointer; flex-shrink:0; }
|
||||
.sub-name-el { flex:1; font-size:13px; font-weight:600; background:transparent; border:none; color:var(--teal); font-family:inherit; outline:none; min-width:0; }
|
||||
/* pending sub form */
|
||||
.sub-form { display:flex; align-items:center; gap:5px; padding:5px 8px 5px 18px; background:var(--al); border-top:1px solid var(--ac); flex-wrap:wrap; }
|
||||
.sub-form-lbl { font-size:11px; color:var(--amber); font-weight:600; flex-shrink:0; }
|
||||
.sub-form-pos { width:58px; font-size:12px; padding:3px 4px; border:1px solid var(--ac); border-radius:6px; background:var(--surface); color:var(--muted); font-family:inherit; flex-shrink:0; }
|
||||
.sub-form-inp { flex:1; font-size:13px; padding:3px 6px; border:1px solid var(--ac); border-radius:4px; background:var(--surface); color:var(--text); font-family:inherit; min-width:80px; outline:none; }
|
||||
.sub-form-inp:focus { border-color:var(--amber); }
|
||||
.sub-ok { font-size:11px; padding:3px 8px; border:1px solid var(--amber); border-radius:4px; background:transparent; cursor:pointer; color:var(--amber); font-weight:600; flex-shrink:0; }
|
||||
.sub-cancel { font-size:11px; padding:3px 8px; border:1px solid var(--border); border-radius:4px; background:transparent; cursor:pointer; color:var(--muted); flex-shrink:0; }
|
||||
/* hit badges */
|
||||
.hits { display:flex; gap:2px; flex-shrink:0; flex-wrap:wrap; }
|
||||
.hbadge { font-size:10px; padding:1px 4px; border-radius:3px; font-weight:600; }
|
||||
.hb1 { background:var(--gl); color:var(--teal); }
|
||||
.hb2 { background:var(--bl); color:var(--blue); }
|
||||
.hb3 { background:var(--pl); color:var(--purple); }
|
||||
.hbhr { background:var(--rl); color:var(--red); }
|
||||
.hbkl { background:var(--cl); color:var(--coral); }
|
||||
.hbks { background:var(--rl); color:var(--red); }
|
||||
.hbfo { background:var(--flyout-bg); color:var(--flyout-text); }
|
||||
.hbgo { background:var(--groundout-bg); color:var(--groundout-text); }
|
||||
.hbsb { background:#E6F1FB; color:#185FA5; }
|
||||
.hbcs { background:#FAEEDA; color:#BA7517; }
|
||||
.hberr { background:#FAEEDA; color:#BA7517; }
|
||||
.hbhbp { background:#FAEEDA; color:#BA7517; }
|
||||
.hbbb { background:#E1F5EE; color:#0F6E56; }
|
||||
.hbfc { background:#EEEDFE; color:#534AB7; }
|
||||
.hbibb { background:#E1F5EE; color:#0F6E56; }
|
||||
.hbwp { background:#FAECE7; color:#993C1D; }
|
||||
.hbr { background:var(--bl); color:var(--blue); }
|
||||
.hbrbi { background:var(--al); color:var(--amber); }
|
||||
|
||||
/* pitchers */
|
||||
.prow { display:flex; flex-wrap:wrap; align-items:center; gap:8px; padding:7px 12px; border-bottom:1px solid var(--border); cursor:pointer; }
|
||||
.p-line:empty { display:none; }
|
||||
.p-line[role=button] { cursor:pointer; border-radius:4px; }
|
||||
.p-line[role=button]:hover, .p-line[role=button]:focus-visible { color:var(--text); text-decoration:underline dotted; outline:none; }
|
||||
.p-warn { padding:7px 12px; font-size:11px; line-height:1.4; color:var(--amber); background:var(--al); border-top:1px solid var(--border); }
|
||||
.ple-grid { display:grid; grid-template-columns:repeat(4, 1fr); gap:8px; }
|
||||
.ple-grid label { display:flex; flex-direction:column; gap:3px; font-size:11px; color:var(--muted); text-transform:uppercase; letter-spacing:.04em; }
|
||||
.ple-grid input { width:100%; padding:6px 8px; font:inherit; font-size:14px; border:1.5px solid var(--border); border-radius:6px; background:var(--surface); color:var(--text); }
|
||||
.ple-grid input.bad { border-color:var(--red); }
|
||||
@media(max-width:420px){ .ple-grid { grid-template-columns:repeat(3, 1fr); } }
|
||||
.p-line { order:1; flex-basis:100%; font-size:11px; color:var(--muted); padding-left:16px; margin-top:-3px; font-variant-numeric:tabular-nums; }
|
||||
.prow:last-child { border-bottom:none; }
|
||||
.prow.active-p { background:var(--bl); }
|
||||
.p-dot { width:8px; height:8px; border-radius:50%; background:var(--blue); flex-shrink:0; }
|
||||
.p-dot.hidden { background:transparent; }
|
||||
.p-name { flex:1; font-size:13px; background:transparent; border:none; color:var(--text); font-family:inherit; }
|
||||
.pc { font-size:13px; font-weight:600; min-width:28px; text-align:right; transition:color .15s; }
|
||||
/* Pitch count milestones — subtle warning/over-limit coloring */
|
||||
.pc.warn { color:var(--amber); }
|
||||
.pc.over { color:var(--red); }
|
||||
.padj { display:flex; gap:3px; }
|
||||
.pb { width:22px; height:22px; border:1px solid var(--border); border-radius:4px; background:transparent; font-size:14px; cursor:pointer; display:flex; align-items:center; justify-content:center; color:var(--muted); line-height:1; }
|
||||
.pb:hover { background:var(--header-bg); }
|
||||
.add-p { display:flex; align-items:center; gap:6px; padding:6px 12px; font-size:13px; color:var(--muted); cursor:pointer; }
|
||||
.add-p:hover { background:var(--header-bg); }
|
||||
.pitcher-panel { background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); overflow:hidden; margin-bottom:10px; }
|
||||
.ph { padding:8px 12px; background:var(--header-bg); display:flex; justify-content:space-between; align-items:center; font-size:13px; font-weight:600; border-bottom:1px solid var(--border); }
|
||||
.ph-hint { font-size:11px; color:var(--muted); font-style:italic; }
|
||||
.p-name-sel { flex:1; font-size:13px; padding:3px 4px; border:1px solid var(--border); border-radius:6px; background:var(--surface); color:var(--text); font-family:inherit; min-width:60px; }
|
||||
|
||||
/* log */
|
||||
.log-panel { background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); overflow:hidden; }
|
||||
.log-inner { max-height:160px; overflow-y:auto; transition:max-height .25s ease; }
|
||||
.log-inner.expanded { max-height:600px; }
|
||||
.log-toggle { display:flex; justify-content:center; padding:4px 0; border-top:1px solid var(--border); cursor:pointer; font-size:11px; color:var(--muted); font-weight:600; letter-spacing:.03em; background:var(--surface); }
|
||||
.log-toggle:hover { background:var(--header-bg); }
|
||||
.log-row { font-size:12px; color:var(--muted); padding:4px 12px; border-bottom:1px solid var(--border); display:flex; justify-content:space-between; align-items:center; gap:6px; }
|
||||
.log-row:last-child { border-bottom:none; }
|
||||
.log-row-text { flex:1; min-width:0; }
|
||||
.log-row-actions { display:flex; align-items:center; gap:4px; flex-shrink:0; }
|
||||
.log-edit-btn { border:none; background:none; font-size:11px; cursor:pointer; color:var(--muted); padding:1px 3px; border-radius:3px; opacity:0; transition:opacity .15s; line-height:1; }
|
||||
.log-row:hover .log-edit-btn { opacity:1; }
|
||||
@media(hover:none){ .log-edit-btn { opacity:.5; } }
|
||||
.log-editing { background:var(--header-bg); padding:6px 12px; flex-wrap:wrap; }
|
||||
.log-edit-input { flex:1; min-width:120px; font-size:12px; padding:3px 6px; border:1px solid var(--blue); border-radius:4px; background:var(--surface); color:var(--text); font-family:inherit; outline:none; }
|
||||
.log-edit-save { padding:3px 8px; font-size:11px; font-weight:600; border:none; border-radius:4px; background:var(--blue); color:#fff; cursor:pointer; }
|
||||
.log-edit-save:hover { background:#1150a0; }
|
||||
.log-edit-play { padding:3px 8px; font-size:11px; font-weight:600; border:1px solid var(--blue); border-radius:4px; background:transparent; color:var(--blue); cursor:pointer; }
|
||||
.log-edit-del { padding:3px 8px; font-size:11px; font-weight:600; border:1px solid var(--red); border-radius:4px; background:transparent; color:var(--red); cursor:pointer; }
|
||||
.log-edit-del:hover { background:var(--rl); }
|
||||
.log-edit-cancel { padding:3px 8px; font-size:11px; border:1px solid var(--border); border-radius:4px; background:transparent; color:var(--muted); cursor:pointer; }
|
||||
.log-edit-cancel:hover { background:var(--header-bg); }
|
||||
.ltag { font-size:11px; padding:1px 5px; border-radius:3px; font-weight:600; }
|
||||
.t-ball { background:var(--gl); color:var(--green); }
|
||||
.t-k { background:var(--rl); color:var(--red); }
|
||||
.t-foul { background:var(--pl); color:var(--purple); }
|
||||
.t-out { background:var(--flyout-bg); color:var(--out-color); }
|
||||
.t-kl { background:var(--cl); color:var(--coral); }
|
||||
.t-ks { background:var(--rl); color:var(--red); }
|
||||
.t-run { background:var(--bl); color:var(--blue); }
|
||||
.t-info { background:var(--al); color:var(--amber); }
|
||||
.t-hit { background:var(--gl); color:var(--teal); }
|
||||
.t-hr { background:var(--rl); color:var(--red); }
|
||||
.t-sub { background:var(--gl); color:var(--teal); }
|
||||
.t-fo { background:var(--flyout-bg); color:var(--flyout-text); }
|
||||
.t-go { background:var(--groundout-bg); color:var(--groundout-text); }
|
||||
.t-err { background:#FAEEDA; color:#BA7517; }
|
||||
.t-sb { background:#E6F1FB; color:#185FA5; }
|
||||
.t-cs { background:#FAEEDA; color:#BA7517; }
|
||||
.t-pb { background:#FAECE7; color:#993C1D; }
|
||||
.t-hbp { background:#FAEEDA; color:#BA7517; }
|
||||
.t-sf { background:#E6F1FB; color:#185FA5; }
|
||||
.t-sac { background:#EEEDFE; color:#534AB7; }
|
||||
.t-fc { background:#EEEDFE; color:#534AB7; }
|
||||
.t-ibb { background:#E1F5EE; color:#0F6E56; }
|
||||
.t-wp { background:#FAECE7; color:#993C1D; }
|
||||
.t-abs { background:#F0E6FB; color:#7C3AED; }
|
||||
.empty-log { font-size:13px; color:var(--muted); padding:16px 12px; text-align:center; }
|
||||
|
||||
/* ABS challenge picker */
|
||||
.abs-picker { margin-top:8px; padding:8px; border:1.5px solid #7C3AED; border-radius:var(--radius); background:var(--surface); }
|
||||
.abs-picker-title { font-size:11px; color:#7C3AED; font-weight:700; text-transform:uppercase; letter-spacing:.04em; margin-bottom:6px; }
|
||||
.abs-picker-row { display:flex; gap:5px; flex-wrap:wrap; align-items:center; margin-bottom:6px; }
|
||||
.abs-picker-row:last-child { margin-bottom:0; }
|
||||
.abs-picker-label { font-size:11px; color:var(--muted); font-weight:600; min-width:65px; flex-shrink:0; }
|
||||
.abs-opt { padding:5px 10px; font-size:12px; font-weight:600; border:1.5px solid var(--border); border-radius:6px; background:transparent; cursor:pointer; color:var(--text); transition:border-color .1s, background .1s; }
|
||||
.abs-opt:hover { background:var(--header-bg); }
|
||||
.abs-opt.sel { border-color:#7C3AED; background:#F0E6FB; color:#7C3AED; }
|
||||
.abs-opt.sel-over { border-color:var(--green); background:var(--gl); color:var(--green); }
|
||||
.abs-opt.sel-upheld { border-color:var(--red); background:var(--rl); color:var(--red); }
|
||||
.abs-confirm { padding:6px 14px; font-size:12px; font-weight:600; border:none; border-radius:6px; background:#7C3AED; color:#fff; cursor:pointer; }
|
||||
.abs-confirm:hover { background:#6D28D9; }
|
||||
.abs-confirm:disabled { background:var(--disabled); cursor:not-allowed; }
|
||||
.abs-cancel { padding:6px 10px; font-size:12px; border:1px solid var(--border); border-radius:6px; background:transparent; cursor:pointer; color:var(--muted); }
|
||||
.abs-cancel:hover { background:var(--header-bg); }
|
||||
.abs-btn { border-color:#7C3AED; color:#7C3AED; }
|
||||
.abs-tally { font-size:11px; color:var(--muted); margin-top:4px; }
|
||||
.abs-tally-won { color:var(--green); font-weight:600; }
|
||||
.abs-tally-lost { color:var(--red); font-weight:600; }
|
||||
|
||||
/* log filter bar */
|
||||
.log-filters { display:flex; align-items:center; gap:5px; padding:6px 10px; border-bottom:1px solid var(--border); flex-wrap:wrap; }
|
||||
.log-filter-label { font-size:10px; color:var(--muted); text-transform:uppercase; letter-spacing:.04em; font-weight:600; flex-shrink:0; }
|
||||
.log-filter-inn { font-size:11px; padding:2px 6px; border:1px solid var(--border); border-radius:5px; background:var(--surface); color:var(--text); font-family:inherit; cursor:pointer; }
|
||||
.log-fpill { font-size:10px; padding:2px 7px; border:1px solid var(--border); border-radius:10px; background:transparent; cursor:pointer; color:var(--muted); font-weight:600; }
|
||||
.log-fpill:hover { background:var(--header-bg); }
|
||||
.log-fpill.active { background:var(--bl); border-color:var(--blue); color:var(--blue); }
|
||||
|
||||
/* ── Game info / notes panel ── */
|
||||
.game-info { background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); margin-bottom:10px; overflow:hidden; }
|
||||
.game-info-toggle { display:flex; align-items:center; justify-content:space-between; padding:8px 12px; cursor:pointer; user-select:none; }
|
||||
.game-info-toggle:hover { background:var(--header-bg); }
|
||||
.game-info-title { font-size:11px; text-transform:uppercase; letter-spacing:.05em; color:var(--muted); font-weight:600; }
|
||||
.game-info-arrow { font-size:13px; color:var(--muted); transition:transform .2s; }
|
||||
.game-info-arrow.open { transform:rotate(180deg); }
|
||||
.game-info-body { padding:0 12px 12px; display:none; }
|
||||
.game-info-body.open { display:block; }
|
||||
.gi-row { display:flex; align-items:center; gap:8px; margin-bottom:8px; }
|
||||
.gi-row:last-child { margin-bottom:0; }
|
||||
.gi-label { font-size:11px; color:var(--muted); text-transform:uppercase; letter-spacing:.04em; font-weight:600; min-width:70px; flex-shrink:0; }
|
||||
.gi-input { flex:1; font-size:13px; padding:5px 8px; border:1px solid var(--border); border-radius:6px; background:var(--surface); color:var(--text); font-family:inherit; outline:none; }
|
||||
.gi-input:focus { border-color:var(--blue); }
|
||||
.gi-input::placeholder { color:var(--muted); opacity:.7; }
|
||||
.gi-weather-row { display:flex; gap:4px; flex-wrap:wrap; align-items:center; }
|
||||
.gi-weather-btn { width:32px; height:32px; border:1.5px solid var(--border); border-radius:6px; background:transparent; cursor:pointer; font-size:17px; display:flex; align-items:center; justify-content:center; transition:border-color .1s, background .1s; line-height:1; }
|
||||
.gi-weather-btn:hover { background:var(--header-bg); }
|
||||
.gi-weather-btn.sel { border-color:var(--blue); background:var(--bl); }
|
||||
.gi-temp { width:60px; font-size:13px; padding:5px 6px; border:1px solid var(--border); border-radius:6px; background:var(--surface); color:var(--text); font-family:inherit; text-align:center; outline:none; }
|
||||
.gi-temp:focus { border-color:var(--blue); }
|
||||
.gi-wind-row { display:flex; gap:6px; align-items:center; flex-wrap:wrap; }
|
||||
.gi-wind-dir { width:60px; font-size:12px; padding:4px 4px; border:1px solid var(--border); border-radius:6px; background:var(--surface); color:var(--text); font-family:inherit; text-align:center; cursor:pointer; }
|
||||
.gi-wind-speed { width:50px; font-size:13px; padding:5px 4px; border:1px solid var(--border); border-radius:6px; background:var(--surface); color:var(--text); font-family:inherit; text-align:center; outline:none; }
|
||||
.gi-wind-speed:focus { border-color:var(--blue); }
|
||||
.gi-wind-unit { font-size:11px; color:var(--muted); }
|
||||
.gi-textarea { flex:1; font-size:13px; padding:5px 8px; border:1px solid var(--border); border-radius:6px; background:var(--surface); color:var(--text); font-family:inherit; outline:none; resize:vertical; min-height:48px; }
|
||||
.gi-textarea:focus { border-color:var(--blue); }
|
||||
.gi-first-pitch-row { display:flex; gap:6px; align-items:center; }
|
||||
|
||||
/* ── Keyboard shortcuts overlay ── */
|
||||
.kb-overlay { position:fixed; inset:0; background:rgba(0,0,0,.45); z-index:300; display:flex; align-items:center; justify-content:center; padding:16px; }
|
||||
.kb-modal { background:var(--surface); border:1px solid var(--border); border-radius:12px; max-width:520px; width:100%; max-height:80vh; overflow-y:auto; box-shadow:0 8px 32px rgba(0,0,0,.2); padding:0; }
|
||||
.kb-modal-hdr { padding:14px 16px; border-bottom:1px solid var(--border); display:flex; justify-content:space-between; align-items:center; }
|
||||
.kb-modal-hdr h3 { font-size:15px; font-weight:700; margin:0; }
|
||||
.kb-modal-close { border:none; background:none; font-size:20px; cursor:pointer; color:var(--muted); line-height:1; padding:0 4px; }
|
||||
.kb-modal-body { padding:12px 16px; }
|
||||
.kb-section { margin-bottom:14px; }
|
||||
.kb-section-title { font-size:11px; text-transform:uppercase; letter-spacing:.05em; color:var(--muted); font-weight:600; margin-bottom:6px; }
|
||||
.kb-row { display:flex; align-items:center; justify-content:space-between; padding:3px 0; font-size:13px; color:var(--text); }
|
||||
.kb-key { display:inline-flex; align-items:center; justify-content:center; min-width:24px; padding:2px 7px; font-size:12px; font-weight:600; font-family:inherit; background:var(--header-bg); border:1px solid var(--border); border-radius:4px; color:var(--text); line-height:1.4; }
|
||||
.kb-key + .kb-key { margin-left:3px; }
|
||||
/* flash feedback toast */
|
||||
.kb-flash { position:fixed; top:12px; left:50%; transform:translateX(-50%); z-index:400; padding:6px 16px; border-radius:8px; font-size:13px; font-weight:600; color:#fff; background:var(--blue); box-shadow:0 4px 12px rgba(0,0,0,.2); pointer-events:none; opacity:0; transition:opacity .15s; }
|
||||
.kb-flash.show { opacity:1; }
|
||||
|
||||
/* ── Confirm / alert modal ── */
|
||||
.cf-overlay { position:fixed; inset:0; background:rgba(0,0,0,.5); z-index:500; display:flex; align-items:center; justify-content:center; padding:16px; }
|
||||
.cf-modal { background:var(--surface); border:1px solid var(--border); border-radius:12px; max-width:400px; width:100%; box-shadow:0 12px 40px rgba(0,0,0,.25); overflow:hidden; }
|
||||
.cf-hdr { padding:14px 16px 8px; display:flex; align-items:center; gap:10px; }
|
||||
.cf-icon { width:28px; height:28px; border-radius:50%; display:flex; align-items:center; justify-content:center; font-size:16px; flex-shrink:0; }
|
||||
.cf-icon.warn { background:var(--al); color:var(--amber); }
|
||||
.cf-icon.danger { background:var(--rl); color:var(--red); }
|
||||
.cf-icon.info { background:var(--bl); color:var(--blue); }
|
||||
.cf-title { font-size:15px; font-weight:700; color:var(--text); line-height:1.3; }
|
||||
.cf-body { padding:0 16px 14px; font-size:13px; color:var(--text); line-height:1.45; }
|
||||
.cf-body.with-icon { padding-left:52px; }
|
||||
.cf-btns { padding:10px 14px 14px; display:flex; justify-content:flex-end; gap:8px; }
|
||||
.cf-btn { padding:7px 14px; font-size:13px; font-weight:600; border-radius:6px; cursor:pointer; font-family:inherit; border:1px solid var(--border); background:var(--surface); color:var(--text); min-width:72px; }
|
||||
.cf-btn:hover { background:var(--header-bg); }
|
||||
.cf-btn.primary { background:var(--blue); border-color:var(--blue); color:#fff; }
|
||||
.cf-btn.primary:hover { filter:brightness(1.08); background:var(--blue); }
|
||||
.cf-btn.danger { background:var(--red); border-color:var(--red); color:#fff; }
|
||||
.cf-btn.danger:hover { filter:brightness(1.08); background:var(--red); }
|
||||
|
||||
/* ── Sync ── */
|
||||
.sync-pill { padding:5px 10px; font:inherit; font-size:12px; font-weight:600; border:1px solid var(--border); border-radius:999px; background:var(--surface); color:var(--muted); cursor:pointer; white-space:nowrap; }
|
||||
.sync-pill.sync-ok { color:var(--green); border-color:var(--gc); }
|
||||
.sync-pill.sync-warn { color:var(--amber); border-color:var(--ac); }
|
||||
.sync-modal { max-width:440px; }
|
||||
.sync-body { padding:14px 16px 16px; font-size:13px; color:var(--text); }
|
||||
.sync-body p { margin:0 0 10px; }
|
||||
.sync-line { color:var(--text); }
|
||||
.sync-note { color:var(--muted); font-size:12px; line-height:1.45; }
|
||||
.sync-err { color:var(--red); font-size:12px; }
|
||||
.sync-ok-msg { color:var(--green); font-size:12px; font-weight:600; }
|
||||
.sync-form { display:flex; flex-direction:column; gap:10px; }
|
||||
.sync-field { display:flex; flex-direction:column; gap:4px; font-size:12px; color:var(--muted); margin-bottom:10px; }
|
||||
.sync-field input { font:inherit; font-size:14px; padding:7px 9px; border:1.5px solid var(--border); border-radius:6px; background:var(--surface); color:var(--text); }
|
||||
|
||||
/* ── Season stats ── */
|
||||
.ss-modal { max-width:920px; }
|
||||
.ss-filters { display:flex; flex-wrap:wrap; gap:8px 14px; padding:12px 16px; border-bottom:1px solid var(--border); }
|
||||
.ss-filters label { display:flex; align-items:center; gap:6px; font-size:12px; color:var(--muted); }
|
||||
.ss-filters select { font:inherit; font-size:13px; padding:4px 6px; border:1px solid var(--border); border-radius:6px; background:var(--surface); color:var(--text); }
|
||||
.ss-sum { display:flex; flex-wrap:wrap; align-items:baseline; justify-content:space-between; gap:6px 16px; padding:10px 16px; font-size:12px; color:var(--muted); }
|
||||
.ss-record b { font-size:22px; color:var(--text); margin-right:4px; font-variant-numeric:tabular-nums; }
|
||||
.ss-tabs { display:flex; gap:6px; padding:0 16px 10px; }
|
||||
.ss-scroll { overflow-x:auto; border-top:1px solid var(--border); }
|
||||
.ss-table { width:100%; border-collapse:collapse; font-size:12px; font-variant-numeric:tabular-nums; }
|
||||
.ss-table th, .ss-table td { padding:6px 8px; text-align:right; border-bottom:1px solid var(--border); white-space:nowrap; }
|
||||
.ss-table th { background:var(--header-bg); position:sticky; top:0; }
|
||||
.ss-table th button { border:none; background:none; padding:0; font:inherit; font-size:11px; font-weight:600; color:var(--muted); cursor:pointer; text-transform:uppercase; letter-spacing:.03em; }
|
||||
.ss-table .ss-name { text-align:left; }
|
||||
.ss-table td.ss-name { font-weight:600; color:var(--text); }
|
||||
.ss-team { color:var(--muted); }
|
||||
.ss-att { font-size:10px; font-weight:600; color:var(--teal); background:var(--gl); border-radius:4px; padding:1px 5px; margin-left:4px; }
|
||||
.ss-live { font-size:10px; color:var(--blue); }
|
||||
.ss-w { color:var(--green); font-weight:700; }
|
||||
.ss-l { color:var(--red); font-weight:700; }
|
||||
.gi-check { display:flex; align-items:center; gap:6px; font-size:13px; color:var(--text); }
|
||||
|
||||
/* ── Share final ── */
|
||||
.sf-modal { max-width:720px; }
|
||||
.sf-body { padding:14px 16px 16px; }
|
||||
.sf-img { display:block; width:100%; height:auto; border:1px solid var(--border); border-radius:8px; }
|
||||
.sf-acts { display:flex; gap:8px; justify-content:flex-end; flex-wrap:wrap; margin-top:12px; }
|
||||
.sf-acts button { padding:8px 14px; font-size:13px; }
|
||||
|
||||
/* ── Check vs MLB ── */
|
||||
.mlb-modal { max-width:640px; }
|
||||
.mlb-hdr-btns { display:flex; align-items:center; gap:8px; }
|
||||
.mlb-btn { padding:5px 10px; font:inherit; font-size:12px; font-weight:600; border:1px solid var(--blue); border-radius:6px; background:transparent; color:var(--blue); cursor:pointer; }
|
||||
.mlb-btn:disabled { opacity:.5; cursor:wait; }
|
||||
.mlb-msg { padding:24px 16px; font-size:13px; color:var(--muted); text-align:center; }
|
||||
.mlb-err { color:var(--red); }
|
||||
.mlb-sum { padding:10px 16px; font-size:12px; color:var(--muted); line-height:1.6; border-bottom:1px solid var(--border); }
|
||||
.mlb-sum b { color:var(--text); }
|
||||
.mlb-sum b.mlb-ok { color:var(--green); }
|
||||
.mlb-catchup { margin-left:6px; background:var(--blue); color:#fff; padding:3px 10px; }
|
||||
.mlb-link { border:none; background:none; padding:0; font:inherit; color:var(--blue); text-decoration:underline; cursor:pointer; }
|
||||
.mlb-sec { display:flex; justify-content:space-between; align-items:center; padding:10px 16px 6px; font-size:11px; color:var(--muted); text-transform:uppercase; letter-spacing:.05em; background:var(--header-bg); border-bottom:1px solid var(--border); }
|
||||
.mlb-row { display:flex; gap:10px; align-items:flex-start; flex-wrap:wrap; padding:9px 16px; border-bottom:1px solid var(--border); font-size:13px; }
|
||||
.mlb-row.mlb-kept { opacity:.55; }
|
||||
.mlb-where { font-weight:700; color:var(--muted); min-width:34px; font-size:12px; padding-top:1px; }
|
||||
.mlb-cmp { flex:1; min-width:200px; }
|
||||
.mlb-who { font-weight:600; color:var(--text); }
|
||||
.mlb-you { color:var(--muted); }
|
||||
.mlb-them { color:var(--text); font-weight:600; }
|
||||
.mlb-desc { font-size:11px; color:var(--muted); margin-top:2px; }
|
||||
.mlb-diff { background:var(--al); color:var(--amber); font-weight:700; border-radius:3px; padding:0 3px; }
|
||||
.mlb-differs { font-size:11px; font-weight:600; color:var(--amber); margin-top:2px; }
|
||||
.mlb-note { font-size:11px; color:var(--amber); margin-top:2px; }
|
||||
.mlb-acts { display:flex; gap:6px; align-items:center; }
|
||||
.mlb-use { padding:5px 10px; font:inherit; font-size:12px; font-weight:600; border:none; border-radius:6px; background:var(--blue); color:#fff; cursor:pointer; white-space:nowrap; }
|
||||
.mlb-keep { padding:5px 10px; font:inherit; font-size:12px; border:1px solid var(--border); border-radius:6px; background:transparent; color:var(--muted); cursor:pointer; white-space:nowrap; }
|
||||
.mlb-foot { padding:10px 16px 14px; font-size:11px; color:var(--muted); line-height:1.4; }
|
||||
|
||||
/* ── Scorecard grid ── */
|
||||
.scorecard-wrap { background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); overflow:hidden; margin-bottom:14px; }
|
||||
.sc-tabs { display:flex; gap:4px; padding:6px 8px; background:var(--header-bg); border-bottom:1px solid var(--border); }
|
||||
.sc-tab { font:inherit; font-size:12px; font-weight:600; padding:4px 10px; border-radius:6px; border:1px solid var(--border); background:var(--surface); color:var(--muted); cursor:pointer; }
|
||||
.sc-tab.sel { background:var(--blue); border-color:var(--blue); color:#fff; }
|
||||
.sc-tabs { align-items:center; }
|
||||
.sc-tab { display:inline-flex; align-items:center; gap:5px; }
|
||||
.sc-tab-logo { width:16px; height:16px; object-fit:contain; }
|
||||
.sc-tab.sel .sc-tab-logo { background:#fff; border-radius:3px; padding:1px; }
|
||||
/* Dark mode uses MLB's dark-background logos (light-colored): no white chip behind them */
|
||||
@media(prefers-color-scheme: dark){ .sc-tab.sel .sc-tab-logo { background:none; padding:0; } }
|
||||
.sc-hdr-logo { width:16px; height:16px; object-fit:contain; vertical-align:middle; margin-right:5px; }
|
||||
.ps-badge { margin-left:auto; display:inline-flex; align-items:center; gap:6px; font-size:12px; font-weight:700; letter-spacing:.04em; text-transform:uppercase; color:var(--text); white-space:nowrap; }
|
||||
.ps-badge img { width:24px; height:24px; object-fit:contain; background:#fff; border-radius:4px; padding:2px; }
|
||||
.print-header .ps-badge { margin:0 0 4px; font-size:13px; }
|
||||
.print-header .ps-badge img { width:30px; height:30px; }
|
||||
.ps-badge-official img { width:auto; height:36px; padding:3px 6px; border-radius:6px; }
|
||||
.print-header .ps-badge-official img { width:auto; height:44px; }
|
||||
.sc-scroll { overflow-x:auto; -webkit-overflow-scrolling:touch; }
|
||||
.sc-table { display:none; border-collapse:collapse; font-variant-numeric:tabular-nums; }
|
||||
.sc-table.sc-active { display:table; }
|
||||
.sc-print-hdr { display:none; }
|
||||
.sc-table th, .sc-table td { border:1px solid var(--border); text-align:center; font-size:11px; }
|
||||
.sc-table thead th { background:var(--header-bg); color:var(--muted); font-weight:600; padding:4px 2px; }
|
||||
.sc-table tr > :first-child { border-left:none; }
|
||||
.sc-name { position:sticky; left:0; z-index:1; background:var(--surface); text-align:left!important; padding:3px 8px; min-width:120px; max-width:150px; }
|
||||
.sc-table thead .sc-name { background:var(--header-bg); }
|
||||
.sc-pname { font-weight:600; color:var(--text); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
|
||||
.sc-ppos { font-size:10px; color:var(--muted); margin-left:4px; font-weight:500; }
|
||||
.sc-psub { font-size:10px; color:var(--teal); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
|
||||
.sc-cell { width:52px; min-width:52px; height:52px; padding:2px; vertical-align:top; }
|
||||
.sc-cell.sc-cur { background:var(--bl); }
|
||||
.sc-pa { position:relative; width:46px; height:46px; margin:0 auto; }
|
||||
.sc-pa + .sc-pa { border-top:1px dashed var(--border); }
|
||||
.sc-pa[role=button] { cursor:pointer; border-radius:4px; }
|
||||
.sc-pa[role=button]:hover, .sc-pa[role=button]:focus-visible { background:var(--header-bg); outline:none; }
|
||||
.pe-field { margin-bottom:10px; }
|
||||
.pe-label { font-size:11px; color:var(--muted); text-transform:uppercase; letter-spacing:.04em; margin-bottom:5px; }
|
||||
.pe-fielders { display:flex; align-items:center; gap:8px; margin-top:6px; font-size:12px; color:var(--muted); }
|
||||
.pe-fielders input { width:90px; padding:6px 8px; font:inherit; font-size:13px; border:1.5px solid var(--border); border-radius:6px; background:var(--surface); color:var(--text); }
|
||||
.pe-preview { font-size:12px; color:var(--muted); margin-top:6px; }
|
||||
.pe-preview b { color:var(--text); }
|
||||
.pe-note { font-size:11px; color:var(--muted); line-height:1.4; margin-top:10px; }
|
||||
.pe-actions { display:flex; gap:6px; margin-top:12px; }
|
||||
.pe-actions .rp-confirm { margin-top:0; flex:1; }
|
||||
.pe-remove { padding:9px 12px; font-size:13px; font-weight:600; border:1.5px solid var(--red); border-radius:8px; background:transparent; color:var(--red); cursor:pointer; }
|
||||
.pe-cancel { padding:9px 12px; font-size:13px; font-weight:500; border:1px solid var(--border); border-radius:8px; background:transparent; color:var(--muted); cursor:pointer; }
|
||||
.sc-dia { display:block; width:100%; height:100%; }
|
||||
.sc-dia-bg { fill:none; stroke:var(--border); stroke-width:1; }
|
||||
.sc-scored .sc-dia-bg { fill:var(--gl); stroke:var(--green); }
|
||||
.sc-path { stroke:var(--green); stroke-width:3; stroke-linecap:round; }
|
||||
.sc-res { position:absolute; inset:0; display:flex; align-items:center; justify-content:center; font-size:11px; font-weight:700; color:var(--text); }
|
||||
.sc-res.sc-hit { color:var(--teal); }
|
||||
.sc-res.sc-k { color:var(--red); }
|
||||
.sc-res.sc-walk { color:var(--blue); }
|
||||
.sc-res.sc-err { color:var(--amber); }
|
||||
.sc-outn { position:absolute; top:0; right:0; width:14px; height:14px; border:1px solid var(--red); border-radius:50%; color:var(--red); font-size:9px; font-weight:700; line-height:12px; text-align:center; background:var(--surface); }
|
||||
.sc-tot { min-width:30px; padding:3px 4px; font-weight:600; }
|
||||
.sc-tot-first { border-left:2px solid var(--border)!important; }
|
||||
.sc-table tfoot td { background:var(--header-bg); padding:3px 2px; font-weight:600; color:var(--text); }
|
||||
.sc-table tfoot .sc-name { background:var(--header-bg); font-size:10px; color:var(--muted); text-transform:uppercase; letter-spacing:.04em; }
|
||||
|
||||
/* ═══════════════════════════════════════════════
|
||||
PRINT / PDF STYLES
|
||||
═══════════════════════════════════════════════ */
|
||||
@media print {
|
||||
@page { size: letter landscape; margin: 0.4in; }
|
||||
.team-sel { background-image:none; padding-right:3px; }
|
||||
body { background:#fff; font-size:11px; }
|
||||
.app { max-width:none; padding:0; }
|
||||
/* hide interactive controls */
|
||||
.hdr-btns, .half-tog, .btns, .action-row, .add-p, .padj,
|
||||
.set-btn, .sub-btn, .sub-form,
|
||||
.pdf-btn, .reset-btn, .out-card, #kbHelpBtn,
|
||||
.kb-flash, .add-inn-cell, .runner-labels, .rp-overlay,
|
||||
.abs-picker, .abs-tally, .abs-btn, .atbat-bar, .backup-nudge { display:none!important; }
|
||||
.cf-overlay { display:none!important; }
|
||||
/* score strip */
|
||||
.score-strip { border:1.5px solid #333; border-radius:0; margin-bottom:6px; }
|
||||
.score-table th, .score-table td { font-size:10px; padding:4px 6px; border-right:1px solid #ccc; }
|
||||
.score-table thead th { background:#e8e8e0!important; -webkit-print-color-adjust:exact; print-color-adjust:exact; }
|
||||
.total-cell { background:#e8e8e0!important; -webkit-print-color-adjust:exact; print-color-adjust:exact; }
|
||||
/* game state */
|
||||
.game-state { grid-template-columns:1fr 1fr 1fr; gap:6px; }
|
||||
.card { border:1px solid #ccc; padding:6px 8px; border-radius:0; page-break-inside:avoid; }
|
||||
.dot { width:16px; height:16px; }
|
||||
.dot.on { -webkit-print-color-adjust:exact; print-color-adjust:exact; }
|
||||
.dot.ball.on { background:var(--green)!important; border-color:var(--green)!important; }
|
||||
.dot.strike.on { background:var(--red)!important; border-color:var(--red)!important; }
|
||||
.dot.foul.on { background:var(--purple)!important; border-color:var(--purple)!important; }
|
||||
.dot.out.on { background:var(--out-color)!important; border-color:var(--out-color)!important; }
|
||||
.infield svg, .stadium-photo img { -webkit-print-color-adjust:exact; print-color-adjust:exact; }
|
||||
/* lineup */
|
||||
.lineup-grid { grid-template-columns:1fr 1fr; gap:6px; }
|
||||
.lineup-panel { border:1.5px solid #333; border-radius:0; page-break-inside:avoid; }
|
||||
.lineup-hdr { background:#e8e8e0!important; -webkit-print-color-adjust:exact; print-color-adjust:exact; font-size:11px; padding:5px 8px; }
|
||||
.lineup-row { padding:3px 6px; }
|
||||
.bname, .bname:disabled { color:#333!important; }
|
||||
.pos-sel, .pos-sel:disabled { color:#333!important; border-color:#ccc!important; background:#fff!important; font-size:11px; }
|
||||
.sub-row { background:var(--gl)!important; -webkit-print-color-adjust:exact; print-color-adjust:exact; padding:3px 6px 3px 16px; }
|
||||
.sub-inn { background:var(--gc)!important; -webkit-print-color-adjust:exact; print-color-adjust:exact; }
|
||||
.sub-name-el { color:var(--teal)!important; font-size:11px; }
|
||||
.sub-pos { color:var(--teal)!important; border-color:var(--gc)!important; font-size:11px; }
|
||||
.dimmed { opacity:.5; }
|
||||
/* hit badges */
|
||||
.hbadge { -webkit-print-color-adjust:exact; print-color-adjust:exact; }
|
||||
.hb1 { background:var(--gl)!important; color:var(--teal)!important; }
|
||||
.hb2 { background:var(--bl)!important; color:var(--blue)!important; }
|
||||
.hb3 { background:var(--pl)!important; color:var(--purple)!important; }
|
||||
.hbhr { background:var(--rl)!important; color:var(--red)!important; }
|
||||
.hbkl { background:var(--cl)!important; color:var(--coral)!important; }
|
||||
.hbks { background:var(--rl)!important; color:var(--red)!important; }
|
||||
.hbr { background:var(--bl)!important; color:var(--blue)!important; }
|
||||
.hbrbi { background:var(--al)!important; color:var(--amber)!important; }
|
||||
/* pitchers */
|
||||
.pitcher-panel { border:1.5px solid #333; border-radius:0; page-break-inside:avoid; margin-bottom:6px; }
|
||||
.ph { background:#e8e8e0!important; -webkit-print-color-adjust:exact; print-color-adjust:exact; font-size:11px; padding:5px 8px; }
|
||||
.prow { padding:4px 8px; }
|
||||
.prow.active-p { background:var(--bl)!important; -webkit-print-color-adjust:exact; print-color-adjust:exact; }
|
||||
.p-dot.hidden { display:none; }
|
||||
.p-warn { display:none!important; }
|
||||
/* score color accents */
|
||||
.active-inn { background:var(--bl)!important; color:var(--blue)!important; -webkit-print-color-adjust:exact; print-color-adjust:exact; }
|
||||
.half-top { background:var(--bl)!important; color:var(--blue)!important; -webkit-print-color-adjust:exact; print-color-adjust:exact; }
|
||||
.half-bot { background:var(--al)!important; color:var(--amber)!important; -webkit-print-color-adjust:exact; print-color-adjust:exact; }
|
||||
/* section titles on print */
|
||||
.sec-title { font-size:10px; margin-bottom:4px; margin-top:8px; }
|
||||
/* game info on print */
|
||||
.game-info { border:1px solid #ccc; border-radius:0; page-break-inside:avoid; margin-bottom:6px; }
|
||||
.game-info-toggle { display:none!important; }
|
||||
.game-info-body { display:block!important; padding:6px 8px!important; }
|
||||
.gi-row { margin-bottom:4px; }
|
||||
.gi-label { font-size:9px; min-width:55px; }
|
||||
.gi-input, .gi-temp, .gi-wind-speed, .gi-wind-dir, .gi-textarea { border:none!important; background:transparent!important; color:#333!important; font-size:10px; padding:1px 2px!important; }
|
||||
.gi-weather-btn { display:none!important; }
|
||||
.gi-weather-btn.sel { display:flex!important; border:none!important; background:none!important; font-size:14px; width:20px; height:20px; min-width:0; }
|
||||
.gi-textarea { min-height:auto!important; resize:none!important; }
|
||||
/* hide empty gi rows on print */
|
||||
.gi-row-empty { display:none!important; }
|
||||
|
||||
/* ── Play log on print ── */
|
||||
.sec-title-log { display:block!important; font-size:10px; margin-bottom:4px; margin-top:8px; }
|
||||
.log-panel { border:1.5px solid #333; border-radius:0; page-break-inside:avoid; }
|
||||
.log-toggle { display:none!important; }
|
||||
.log-filters { display:none!important; }
|
||||
.log-inner { max-height:none!important; overflow:visible!important; column-count:2; column-gap:8px; }
|
||||
.log-inner.expanded { max-height:none!important; }
|
||||
.log-row { font-size:9px; padding:2px 6px; border-bottom:1px solid #eee; break-inside:avoid; }
|
||||
.log-row.log-cat-pitches { display:none!important; } /* full games: print plays, not every pitch */
|
||||
.log-edit-btn { display:none!important; }
|
||||
.log-editing { display:none!important; }
|
||||
.ltag { font-size:8px; padding:0 3px; -webkit-print-color-adjust:exact; print-color-adjust:exact; }
|
||||
.empty-log { display:none; }
|
||||
|
||||
/* ── Print-only box score table ── */
|
||||
.print-boxscore { display:block!important; margin-top:8px; page-break-inside:avoid; }
|
||||
.print-boxscore table { width:100%; border-collapse:collapse; font-size:9px; }
|
||||
.print-boxscore th, .print-boxscore td { padding:2px 4px; border:1px solid #ccc; text-align:center; }
|
||||
.print-boxscore th { background:#e8e8e0!important; -webkit-print-color-adjust:exact; print-color-adjust:exact; font-weight:600; font-size:8px; text-transform:uppercase; }
|
||||
.print-boxscore td:first-child { text-align:left; font-weight:600; padding-left:6px; }
|
||||
.print-boxscore .bs-team-hdr { background:#f0efe8!important; -webkit-print-color-adjust:exact; print-color-adjust:exact; font-weight:700; text-align:left!important; padding:3px 6px; font-size:10px; }
|
||||
.print-boxscore .bs-totals td { font-weight:700; border-top:2px solid #333; }
|
||||
|
||||
/* ── Scorecard grid on print: both teams, no tabs ── */
|
||||
.scorecard-wrap { border:none; border-radius:0; overflow:visible; }
|
||||
.sc-tabs { display:none!important; }
|
||||
.sc-scroll { overflow:visible; }
|
||||
.sc-table { display:table!important; width:100%; margin-bottom:8px; page-break-inside:avoid; }
|
||||
.sc-print-hdr { display:table-caption; caption-side:top; text-align:left; font-weight:700; font-size:11px; padding:2px 0; }
|
||||
.sc-table th, .sc-table td { border-color:#999; }
|
||||
.sc-table thead th, .sc-table tfoot td, .sc-name { -webkit-print-color-adjust:exact; print-color-adjust:exact; }
|
||||
.sc-cell { width:auto; min-width:0; }
|
||||
.sc-pa { width:38px; height:38px; }
|
||||
.sc-cell.sc-cur { background:none!important; }
|
||||
.sc-pa[role=button] { background:none!important; }
|
||||
.sc-scored .sc-dia-bg, .sc-path, .sc-outn { -webkit-print-color-adjust:exact; print-color-adjust:exact; }
|
||||
|
||||
/* print header */
|
||||
.print-header { display:block!important; }
|
||||
.header { margin-bottom:6px; }
|
||||
.print-sub { display:block!important; }
|
||||
}
|
||||
|
||||
.print-header {
|
||||
display:none;
|
||||
text-align:center;
|
||||
font-size:18px;
|
||||
font-weight:700;
|
||||
letter-spacing:.04em;
|
||||
margin-bottom:2px;
|
||||
border-bottom:2px solid #333;
|
||||
padding-bottom:4px;
|
||||
}
|
||||
.print-sub {
|
||||
display:none;
|
||||
text-align:center;
|
||||
font-size:11px;
|
||||
color:#666;
|
||||
margin-bottom:8px;
|
||||
}
|
||||
.print-boxscore {
|
||||
display:none;
|
||||
}
|
||||
|
||||
/* ── Current at-bat bar ── */
|
||||
.atbat-bar { background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); padding:8px 12px; margin-bottom:10px; display:flex; align-items:center; gap:10px; flex-wrap:wrap; }
|
||||
.atbat-batter { display:flex; align-items:center; gap:7px; flex:1; min-width:0; }
|
||||
.atbat-logo { width:22px; height:22px; object-fit:contain; flex-shrink:0; }
|
||||
.atbat-name { font-size:14px; font-weight:700; color:var(--text); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
|
||||
.atbat-detail { font-size:11px; color:var(--muted); flex-shrink:0; }
|
||||
.atbat-pos { font-size:11px; font-weight:600; padding:1px 5px; border-radius:3px; background:var(--header-bg); color:var(--muted); flex-shrink:0; }
|
||||
.atbat-badges { display:flex; gap:3px; flex-wrap:wrap; flex-shrink:0; }
|
||||
.atbat-extra { flex-basis:100%; display:flex; flex-wrap:wrap; gap:4px 16px; font-size:11.5px; color:var(--muted); padding-top:2px; margin-top:-2px; }
|
||||
.atbat-count { font-size:13px; font-weight:700; color:var(--text); flex-shrink:0; letter-spacing:.5px; }
|
||||
.atbat-count-b { color:var(--green); }
|
||||
.atbat-count-s { color:var(--red); }
|
||||
.atbat-sep { width:1px; height:20px; background:var(--border); flex-shrink:0; }
|
||||
.atbat-vs { display:flex; align-items:center; gap:6px; flex-shrink:0; }
|
||||
.atbat-vs-label { font-size:10px; color:var(--muted); text-transform:uppercase; letter-spacing:.04em; }
|
||||
.atbat-pitcher { font-size:12px; font-weight:600; color:var(--text); white-space:nowrap; }
|
||||
.atbat-pc { font-size:11px; color:var(--muted); }
|
||||
.atbat-ondeck { font-size:11px; color:var(--muted); flex-shrink:0; }
|
||||
.atbat-inhole { font-size:11px; color:var(--muted); flex-shrink:0; opacity:.75; }
|
||||
@media(max-width:480px){
|
||||
.atbat-bar { padding:6px 10px; gap:6px; }
|
||||
.atbat-name { font-size:13px; }
|
||||
.atbat-sep { display:none; }
|
||||
.atbat-inhole { display:none; }
|
||||
}
|
||||
@@ -1,383 +0,0 @@
|
||||
/* Scorebook: a ballpark palette, a paper scorecard, and room to keep the game. */
|
||||
:root {
|
||||
color-scheme:light;
|
||||
--green:#23694f; --teal:#23694f; --gl:#edf4ee; --gc:#b8d4c0;
|
||||
--blue:#2b6955; --bl:#eaf2eb; --red:#b74d3e; --rl:#fbefea;
|
||||
--amber:#96631e; --al:#fcf4e3; --purple:#766383; --pl:#f3eff5;
|
||||
--coral:#ad6144; --cl:#faf0e9;
|
||||
--bg:#f6f5ef; --surface:#fffefa; --text:#233b32; --muted:#66746b;
|
||||
--border:#dedfd5; --header-bg:#f0f1e9; --radius:12px; --out-color:#b74d3e;
|
||||
--field-grass:#52775a; --field-foul:#456a4e; --field-dirt:#d4b18a; --field-wall:#214a38;
|
||||
/* Georgia for the scorebook display, a native UI sans for everything else.
|
||||
Both resolve on every platform with no web font, so the look holds up
|
||||
offline and off-Apple (Avenir Next only ever shipped on Apple devices). */
|
||||
--font-serif: Georgia, 'Times New Roman', 'Noto Serif', serif;
|
||||
--font-sans: system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||
/* tokens for the light surfaces that used to be hardcoded, so dark mode can flip them */
|
||||
--sc-cur:#eaf1df; --tip-bg:#eeeedd; --brand:#214a38;
|
||||
}
|
||||
|
||||
/* Dark mode: a night-ballpark palette. The two blocks carry the same values so
|
||||
the Auto/Light/Dark control wins in both directions — the media query covers
|
||||
"Auto" on a dark device, [data-theme="dark"] covers an explicit Dark choice.
|
||||
The scoreboard stays its deep green (a lit board reads on either background).
|
||||
Shared app.css tokens are redefined too, so an explicit Dark choice on a
|
||||
light device stays consistent. */
|
||||
@media (prefers-color-scheme:dark){ :root:not([data-theme="light"]){
|
||||
color-scheme:dark;
|
||||
--green:#54bb8d; --teal:#54bb8d; --gl:#1c2b21; --gc:#2f5f44;
|
||||
--blue:#54bb8d; --bl:#1b2b23; --red:#df755c; --rl:#331d18;
|
||||
--amber:#d7a258; --al:#2c2414; --purple:#aa9dd3; --pl:#242132;
|
||||
--coral:#d4886b; --cl:#2e2018;
|
||||
--bg:#13160f; --surface:#1c211c; --text:#e8ebe2; --muted:#9ba89b;
|
||||
--border:#333a31; --header-bg:#232922; --out-color:#d07a5f;
|
||||
--sc-cur:#223a2b; --tip-bg:#232a1d; --brand:#7cc6a0;
|
||||
--flyout-bg:#23241d; --flyout-text:#9ba89b; --flyout-border:#3a3c33;
|
||||
--groundout-bg:#1b2a18; --groundout-text:#89bb67; --groundout-border:#2f4a25; --disabled:#4a4a44;
|
||||
} }
|
||||
:root[data-theme="dark"]{
|
||||
color-scheme:dark;
|
||||
--green:#54bb8d; --teal:#54bb8d; --gl:#1c2b21; --gc:#2f5f44;
|
||||
--blue:#54bb8d; --bl:#1b2b23; --red:#df755c; --rl:#331d18;
|
||||
--amber:#d7a258; --al:#2c2414; --purple:#aa9dd3; --pl:#242132;
|
||||
--coral:#d4886b; --cl:#2e2018;
|
||||
--bg:#13160f; --surface:#1c211c; --text:#e8ebe2; --muted:#9ba89b;
|
||||
--border:#333a31; --header-bg:#232922; --out-color:#d07a5f;
|
||||
--sc-cur:#223a2b; --tip-bg:#232a1d; --brand:#7cc6a0;
|
||||
--flyout-bg:#23241d; --flyout-text:#9ba89b; --flyout-border:#3a3c33;
|
||||
--groundout-bg:#1b2a18; --groundout-text:#89bb67; --groundout-border:#2f4a25; --disabled:#4a4a44;
|
||||
}
|
||||
/* The filled cream buttons would read as bright blocks on dark, so give them
|
||||
dark fills with the same semantic accent — once per dark context. */
|
||||
@media (prefers-color-scheme:dark){
|
||||
:root:not([data-theme="light"]) .btn.big.strike{ background:var(--al); border-color:#5a4a28; color:var(--amber); }
|
||||
:root:not([data-theme="light"]) .btn.big.foul{ background:var(--header-bg); border-color:var(--border); color:var(--muted); }
|
||||
:root:not([data-theme="light"]) .h1b, :root:not([data-theme="light"]) .h2b, :root:not([data-theme="light"]) .h3b{ background:var(--gl); border-color:var(--gc); color:var(--green); }
|
||||
:root:not([data-theme="light"]) .hhbp, :root:not([data-theme="light"]) .hibb{ background:var(--header-bg); border-color:var(--border); color:var(--muted); }
|
||||
:root:not([data-theme="light"]) .ko-btn{ background:var(--cl); border-color:#6b4433; color:var(--coral); }
|
||||
}
|
||||
:root[data-theme="dark"] .btn.big.strike{ background:var(--al); border-color:#5a4a28; color:var(--amber); }
|
||||
:root[data-theme="dark"] .btn.big.foul{ background:var(--header-bg); border-color:var(--border); color:var(--muted); }
|
||||
:root[data-theme="dark"] .h1b, :root[data-theme="dark"] .h2b, :root[data-theme="dark"] .h3b{ background:var(--gl); border-color:var(--gc); color:var(--green); }
|
||||
:root[data-theme="dark"] .hhbp, :root[data-theme="dark"] .hibb{ background:var(--header-bg); border-color:var(--border); color:var(--muted); }
|
||||
:root[data-theme="dark"] .ko-btn{ background:var(--cl); border-color:#6b4433; color:var(--coral); }
|
||||
body { font-family: var(--font-sans); -webkit-font-smoothing:antialiased; }
|
||||
button,input,select,textarea { font-family:inherit; }
|
||||
button { touch-action:manipulation; transition:background .16s, border-color .16s, box-shadow .16s, transform .16s; }
|
||||
button:disabled { cursor:default; opacity:.5; }
|
||||
button:focus-visible,summary:focus-visible,[tabindex]:focus-visible,a:focus-visible { outline:3px solid #b17836; outline-offset:4px; }
|
||||
button:not(:disabled):active { transform:translateY(1px); }
|
||||
[hidden] { display:none!important; }
|
||||
.skip-link { position:fixed; top:8px; left:8px; z-index:1000; transform:translateY(-150%); background:var(--surface); color:var(--text); padding:12px; border:2px solid var(--green); }
|
||||
.skip-link:focus { transform:none; }
|
||||
.site-header { border-bottom:1px solid var(--border); background:var(--surface); }
|
||||
.site-header-inner { max-width:1540px; margin:0 auto; min-height:86px; padding:16px 42px; display:flex; align-items:center; gap:22px; }
|
||||
.brand { display:flex; align-items:center; gap:10px; color:var(--brand); text-decoration:none; font-family:var(--font-serif); font-size:32px; font-weight:bold; letter-spacing:-1.5px; flex-shrink:0; }
|
||||
.brand-mark { width:34px; height:34px; display:block; }
|
||||
.brand-mark svg { width:100%; height:100%; }
|
||||
.brand-period { color:#b56c42; }
|
||||
.brand-tagline { font-size:9px; line-height:1.7; max-width:100px; color:var(--muted); letter-spacing:1.7px; padding-left:20px; border-left:1px solid var(--border); }
|
||||
.hdr-btns { margin-left:auto; gap:10px; }
|
||||
.hdr-spacer { display:none; }
|
||||
.today-btn,.library-btn,.export-btn,.reset-btn,.pdf-btn { font:inherit; font-size:12px; line-height:1.4; font-weight:600; padding:10px 14px; border:1px solid var(--border); border-radius:7px; background:transparent; color:var(--text); white-space:nowrap; }
|
||||
.today-btn { border-color:var(--green); color:var(--green); }
|
||||
.today-btn:hover,.library-btn:hover,.export-btn:hover,.reset-btn:hover { background:var(--gl); }
|
||||
.library-btn { border-color:transparent; }
|
||||
.export-btn { background:#214a38; color:#fff; border-color:#214a38; }
|
||||
.export-btn:hover { background:#17392b; color:#fff; }
|
||||
.export-btn span { margin-left:10px; }
|
||||
.pdf-btn { background:var(--surface); }
|
||||
.pdf-btn:hover { background:var(--header-bg); }
|
||||
#undoBtn:not(:disabled) { color:var(--text); border-color:var(--border); }
|
||||
.sync-pill { font-size:10px; }
|
||||
.theme-toggle { display:inline-flex; border:1px solid var(--border); border-radius:7px; overflow:hidden; }
|
||||
.theme-toggle button { font:inherit; font-size:11px; font-weight:600; line-height:1; padding:9px 10px; border:0; border-left:1px solid var(--border); background:transparent; color:var(--muted); cursor:pointer; }
|
||||
.theme-toggle button:first-child { border-left:0; }
|
||||
.theme-toggle button[aria-pressed="true"] { background:var(--gl); color:var(--green); }
|
||||
@media(max-width:600px){ .theme-toggle button { padding:7px 8px; font-size:10px; } }
|
||||
.app { max-width:1540px; display:block; padding:30px 42px 0; }
|
||||
.page-heading { display:flex; justify-content:space-between; gap:20px; align-items:center; margin:0 0 26px; }
|
||||
.eyebrow { font-size:10px; font-weight:600; letter-spacing:1.9px; color:var(--muted); text-transform:uppercase; }
|
||||
h1 { font-family:var(--font-serif); font-size:36px; font-weight:400; letter-spacing:-1.2px; line-height:1.25; margin-top:8px; }
|
||||
.save-status { display:flex; align-items:center; gap:7px; font-size:11px; color:var(--muted); }
|
||||
.save-status>span { width:6px; height:6px; border-radius:100%; background:var(--green); }
|
||||
.save-status button { width:22px; height:22px; margin-left:8px; border:1px solid var(--border); color:var(--muted); background:transparent; border-radius:50%; font-size:11px; }
|
||||
.scoreboard { background:linear-gradient(165deg, #1f4c3b 0%, #193e31 55%, #14362a 100%); color:#fffdf3; border-radius:14px; overflow:hidden; box-shadow:0 4px 12px #183c3010; position:relative; }
|
||||
/* Manual collapse: fold the board to a slim score strip so scoring leads. */
|
||||
.board-collapse { color:#c1d0bc; }
|
||||
.board-collapse:hover { color:#fffdf3; }
|
||||
.board-collapsed { display:none; }
|
||||
.scoreboard.collapsed .board-content, .scoreboard.collapsed .board-bottom, .scoreboard.collapsed .board-collapse { display:none; }
|
||||
.scoreboard.collapsed .board-collapsed { display:flex; align-items:center; gap:16px; padding:11px 22px; cursor:pointer; }
|
||||
.board-collapsed .bc-score { font-family:var(--font-serif); font-size:18px; font-variant-numeric:tabular-nums; color:#fffdf3; min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
||||
.board-collapsed .bc-inn { font-size:10px; letter-spacing:1.3px; text-transform:uppercase; color:#e0c58a; white-space:nowrap; flex:none; }
|
||||
.board-collapsed .bc-expand { margin-left:auto; font-size:10px; letter-spacing:.6px; color:#c1d0bc; white-space:nowrap; flex:none; }
|
||||
.board-collapsed:hover .bc-expand { color:#fffdf3; }
|
||||
/* Focus mode: once scoring starts, hide the header + page heading so the board
|
||||
strip and workspace lead. "Show menu / Hide top" in the tab row brings them
|
||||
back (Undo is also Ctrl/Cmd-Z or U). */
|
||||
body.game-focus .site-header, body.game-focus .page-heading { display:none; }
|
||||
.nav-right { display:flex; align-items:center; gap:16px; }
|
||||
.focus-toggle { display:none; background:transparent; border:0; font:inherit; font-size:10px; color:var(--muted); padding-bottom:16px; white-space:nowrap; cursor:pointer; align-items:center; gap:5px; }
|
||||
.focus-toggle:hover { color:var(--green); }
|
||||
.app.has-plays .focus-toggle { display:inline-flex; }
|
||||
.board-dot { width:5px; height:5px; background:#d8b36d; border-radius:50%; flex:none; }
|
||||
.board-content { display:grid; grid-template-columns:minmax(300px,.85fr) minmax(450px,1.45fr); align-items:center; gap:18px; padding:15px 26px; }
|
||||
.matchup { display:grid; grid-template-columns:1fr auto 1fr; gap:18px; align-items:center; }
|
||||
.matchup-team { text-align:center; min-width:0; }
|
||||
.matchup-badge { display:flex; justify-content:center; align-items:center; width:40px; height:40px; margin:0 auto 7px; border-radius:50%; border:1px solid #ffffff30; color:#ddd9bb; font:16px var(--font-serif); }
|
||||
.matchup-badge img { width:34px; height:34px; object-fit:contain; }
|
||||
.matchup-name { font-size:12px; font-weight:600; line-height:1.4; min-height:34px; display:flex; align-items:center; justify-content:center; }
|
||||
.matchup-side { font-size:8px; letter-spacing:1.6px; color:#aec4b2; margin-top:4px; }
|
||||
.matchup-score { text-align:center; white-space:nowrap; font-size:32px; font-weight:500; font-variant-numeric:tabular-nums; letter-spacing:2px; }
|
||||
.matchup-score em { font:24px var(--font-serif); font-style:normal; color:#819987; margin:0 7px; }
|
||||
.matchup-inning { color:#e0c58a; font-size:9px; letter-spacing:1px; margin-top:6px; }
|
||||
.linescore { min-width:0; border-left:1px solid #ffffff1c; padding-left:26px; }
|
||||
.linescore-title { font-size:9px; letter-spacing:1.5px; color:#d7e3d2; display:flex; justify-content:space-between; gap:8px; margin:0 0 12px; }
|
||||
.linescore-title span { font-size:9px; letter-spacing:0; color:#9fb9a9; }
|
||||
.score-strip { background:transparent; border:0; border-radius:0; margin:0; scrollbar-width:thin; scrollbar-color:#668472 transparent; }
|
||||
.score-table { min-width:440px; }
|
||||
.score-table th,.score-table td { border:0; padding:9px 6px; color:#f9f7e9; font-size:12px; }
|
||||
.score-table thead th { background:transparent; color:#a4bdab; font-size:9px; }
|
||||
.score-table tr { border-top:1px solid #ffffff14; }
|
||||
.score-table thead tr { border:0; }
|
||||
.score-table .team-label { padding-left:0!important; }
|
||||
.score-table .team-cell img { background:#f5f2e7; padding:2px; border-radius:3px; }
|
||||
.score-table .team-sel { font-size:10px; color:#f9f7e9; max-width:160px; }
|
||||
.score-table .team-sel option { color:#233b32; background:#fffefa; }
|
||||
.score-table .team-sel:hover { background-color:#ffffff16; }
|
||||
.score-table .total-cell { background:#ffffff07; font-weight:700; }
|
||||
.score-table .total-cell:first-of-type { color:#efd498; }
|
||||
.score-table .active-inn { background:#ffffff0d!important; color:#efd498; }
|
||||
.score-table .inning-cell:hover { background:#ffffff19!important; }
|
||||
.score-table .add-inn { color:#a5bbaa; border-color:#ffffff30; width:19px; height:19px; }
|
||||
.score-table .score-edit { color:#233b32; }
|
||||
.board-bottom { display:flex; flex-wrap:wrap; justify-content:space-between; align-items:center; gap:6px 16px; padding:8px 25px; background:#102f2580; font-size:10px; color:#c1d0bc; }
|
||||
.board-bottom button { padding:0; border:0; background:transparent; color:#e6d3a5; font-size:10px; }
|
||||
.board-bottom button span { margin-left:12px; }
|
||||
.bb-left { display:flex; align-items:center; gap:8px; min-width:0; flex:1 1 auto; }
|
||||
.bb-right { display:flex; align-items:center; gap:14px; flex:0 0 auto; }
|
||||
.bb-left #boardStatus { letter-spacing:1.3px; text-transform:uppercase; color:#bbcebc; white-space:nowrap; }
|
||||
.bb-left #boardSituation { min-width:0; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
||||
.bb-sep { opacity:.45; }
|
||||
#boardVenue { letter-spacing:1.3px; text-transform:uppercase; color:#bbcebc; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; max-width:230px; }
|
||||
.workspace-nav { display:flex; align-items:center; justify-content:space-between; border-bottom:1px solid #d7dbce; margin:24px 0 23px; gap:16px; }
|
||||
.view-tabs { display:flex; gap:26px; }
|
||||
.view-tabs button { font-size:12px; font-weight:500; background:none; border:0; border-bottom:2px solid transparent; color:var(--muted); padding:0 0 16px; white-space:nowrap; }
|
||||
.view-tabs button[aria-selected=true] { border-bottom-color:#2b6955; color:var(--green); font-weight:700; }
|
||||
.view-tabs button span { margin-right:5px; }
|
||||
.shortcuts-btn { background:transparent; border:0; font-size:10px; color:var(--muted); padding-bottom:16px; }
|
||||
kbd { font:9px inherit; border:1px solid currentColor; border-radius:3px; padding:1px 4px; opacity:.65; display:inline-block; }
|
||||
.shortcuts-btn kbd { margin-left:5px; }
|
||||
.workspace { display:grid; grid-template-columns:minmax(0,1.03fr) minmax(0,1fr); gap:26px; align-items:start; outline:none; }
|
||||
.col-main,.col-side { min-width:0; }
|
||||
.col-side { position:static; max-height:none; overflow:visible; }
|
||||
.section-heading { display:flex; align-items:baseline; justify-content:space-between; gap:10px; margin-bottom:13px; min-height:25px; }
|
||||
.section-heading h2 { font-family:var(--font-serif); font-size:22px; font-weight:400; letter-spacing:-.5px; }
|
||||
.section-heading>span { color:var(--muted); font-size:10px; }
|
||||
.section-heading.small { margin-top:23px; margin-bottom:10px; }
|
||||
.section-heading.small h2 { font-size:18px; }
|
||||
.setup-tip { display:flex; gap:12px; align-items:center; padding:13px 15px; background:var(--tip-bg); border:1px solid var(--border); border-radius:9px; margin-bottom:14px; }
|
||||
.tip-icon { font-size:22px; color:#777d48; }
|
||||
.setup-tip strong { font-size:11px; font-weight:600; }
|
||||
.setup-tip p { font-size:10px; line-height:1.5; color:var(--muted); margin-top:2px; }
|
||||
.setup-tip button { margin-left:auto; background:none; border:0; font-size:10px; font-weight:600; color:var(--green); white-space:nowrap; }
|
||||
.atbat-bar { padding:14px 16px; margin-bottom:12px; gap:8px; background:var(--gl); border-radius:10px; border-top:3px solid #698b60; }
|
||||
.atbat-name { font-family:var(--font-serif); font-size:18px; font-weight:400; }
|
||||
.atbat-batter { flex-basis:50%; }
|
||||
.atbat-count { font-size:15px; }
|
||||
.atbat-extra { font-size:10px; }
|
||||
.atbat-pitcher { font-size:11px; }
|
||||
.atbat-inhole { display:none; }
|
||||
.atbat-ondeck { font-size:10px; }
|
||||
.game-state { grid-template-columns:.8fr 1.25fr 1fr; gap:10px; margin-bottom:12px; }
|
||||
/* Only the count buttons set a floor; the photo caption must not widen the inning card and squeeze the bases. */
|
||||
.game-state>.inning-card,.game-state>.bases-card { min-width:0; }
|
||||
.card { padding:15px 13px; border-radius:10px; box-shadow:0 2px 0 #183c3003; }
|
||||
.label { font-size:9px; letter-spacing:1.2px; font-weight:600; margin-bottom:12px; }
|
||||
.inn-ctrl { gap:5px; }
|
||||
.inn-num { font-family:var(--font-serif); font-size:27px; }
|
||||
.arr { width:25px; height:29px; border-radius:5px; }
|
||||
.half-pill { font-size:9px; padding:3px 5px; }
|
||||
.half-tog { font-size:9px; margin-top:8px; }
|
||||
.dot { width:15px; height:15px; border-width:1.5px; }
|
||||
.dot.out { cursor:pointer; }
|
||||
.dot-row { gap:5px; }
|
||||
.dlabel { font-size:9px; display:inline-block; width:11px; }
|
||||
.btn { font-size:10px; border-radius:5px; padding:5px 8px; }
|
||||
.btns { gap:5px; }
|
||||
.count-card .btns { display:grid; grid-template-columns:repeat(3,1fr); }
|
||||
.count-card .btn.big { font-size:11px; padding:9px 3px; display:flex; align-items:center; justify-content:center; gap:5px; }
|
||||
.btn.big.ball { background:#28634b; border-color:#28634b; color:white; }
|
||||
.btn.big.ball:hover { background:#1d4e39; }
|
||||
.btn.big.strike { background:#f8efe1; border-color:#d9bb8f; color:#8b5b23; }
|
||||
.btn.big.foul { background:#f0f0e9; border-color:#d5d8ca; color:#63715f; }
|
||||
.count-card .btns#brBtns { display:flex; }
|
||||
.count-card .btns#brBtns .btn { font-size:9px; min-width:29px; }
|
||||
.abs-tally,.foul-note { font-size:9px; }
|
||||
.stadium-slot { margin-top:12px; }
|
||||
.stadium-photo img { max-height:70px; object-fit:cover; }
|
||||
.stadium-photo figcaption { flex-direction:column; align-items:flex-start; gap:1px; }
|
||||
.stadium-credit { white-space:normal; }
|
||||
.stadium-name { font-size:9px; }
|
||||
.stadium-credit { font-size:8px; }
|
||||
.bases-label { flex-wrap:wrap; gap:6px; }
|
||||
.field-toggle button { font-size:8px; padding:3px 4px; }
|
||||
.bases-field { margin-top:5px; }
|
||||
.infield svg { border-radius:7px; max-height:174px; }
|
||||
.runner-labels { font-size:9px; }
|
||||
.action-row { grid-template-columns:1fr; gap:12px; margin-bottom:12px; }
|
||||
.hit-btns { gap:7px; }
|
||||
.hit-btn { border-radius:7px; min-height:66px; padding:10px 3px; font-size:21px; font-weight:500; border-width:1px; }
|
||||
.hlabel { font-size:9px; margin-top:5px; font-weight:500; }
|
||||
.h1b,.h2b,.h3b { background:#edf3ea; border-color:#cfdcc7; color:#386341; }
|
||||
.hhr { background:#ad6947; border-color:#ad6947; color:#fff9eb; }
|
||||
.hhbp,.hibb { background:#f6f4eb; border-color:#dedbcd; color:#756641; }
|
||||
.hit-btn:hover { box-shadow:0 3px 7px #23422f16; transform:translateY(-2px); }
|
||||
.hit-err-toggle { font-size:9px; }
|
||||
.strikeout-card { display:flex; align-items:center; gap:15px; flex-wrap:wrap; }
|
||||
.strikeout-card>.label { margin:0; min-width:60px; }
|
||||
.ko-btns { flex:1; margin:0; }
|
||||
.ko-btn { display:flex; align-items:center; justify-content:center; gap:10px; font-size:23px; padding:8px; border-width:1px; border-radius:7px; background:#faf1e9; border-color:#e5d4c4; color:#9c5b42; }
|
||||
.kolabel { font-size:10px; margin:0; }
|
||||
.strikeout-card>div:last-child { flex-basis:100%; margin-top:-7px!important; font-size:9px!important; }
|
||||
.out-card { padding:0; border-radius:10px; overflow:hidden; background:var(--surface); }
|
||||
.out-card summary { cursor:pointer; list-style:none; padding:15px; display:flex; align-items:center; gap:12px; font-size:12px; font-weight:600; }
|
||||
.out-card summary::-webkit-details-marker { display:none; }
|
||||
.out-card summary span { font-size:9px; color:var(--muted); margin-left:auto; font-weight:400; }
|
||||
.out-card summary::after { content:'−'; font-size:17px; color:var(--muted); }
|
||||
.out-card:not([open]) summary::after { content:'+'; }
|
||||
.fielding-body { padding:0 15px 15px; }
|
||||
.out-type-btn { font-size:17px; border-width:1px; padding:9px 5px; border-radius:6px; }
|
||||
.multi-out-btn,.sac-toggle { border-width:1px; border-radius:5px; font-size:11px; }
|
||||
.fielder-btn { min-height:36px; border-width:1px; font-size:11px; }
|
||||
.rec-out-btn { border-radius:6px; padding:10px; font-size:11px; }
|
||||
.sc-tabs { background:var(--header-bg); padding:10px; gap:5px; }
|
||||
.sc-tab { padding:6px 9px; font-size:10px; font-weight:500; border-color:transparent; background:transparent; border-radius:5px; }
|
||||
.sc-tab.sel { background:#284f3b; color:#fffdf3; }
|
||||
.ps-badge { font-size:9px; }
|
||||
.ps-badge-official img { height:25px; }
|
||||
.scorecard-wrap { border-radius:10px; margin-bottom:0; }
|
||||
.sc-table { width:100%; }
|
||||
.sc-table th,.sc-table td { border-color:var(--border); }
|
||||
.sc-table thead th { font-size:9px; padding:10px 3px; background:var(--header-bg); }
|
||||
.sc-name { min-width:110px; max-width:130px; padding:5px 9px; }
|
||||
.sc-pname { font-size:13px; font-weight:700; }
|
||||
.sc-ppos { font-size:9px; }
|
||||
.sc-cell { min-width:39px; width:39px; height:44px; }
|
||||
.sc-pa { width:36px; height:36px; }
|
||||
.sc-tot { min-width:24px; font-size:10px!important; }
|
||||
.sc-table tfoot td { font-size:9px; padding:5px 3px; background:var(--header-bg); }
|
||||
.sc-res { font-size:10px; }
|
||||
.sc-cell.sc-cur { background:var(--sc-cur); box-shadow:inset 0 0 0 1px var(--gc); }
|
||||
.sc-table .sc-cur:empty::after { content:'·'; color:var(--muted); font-size:21px; line-height:32px; }
|
||||
.col-side .lineup-grid { gap:9px; }
|
||||
.ph { font-size:10px; padding:10px; background:#f0f1e9; gap:5px; }
|
||||
.ph img { width:19px!important; height:19px!important; }
|
||||
.prow { padding:9px; gap:5px; }
|
||||
.pname,.pitcher-select { font-size:10px; }
|
||||
.pitches-count { font-size:14px; }
|
||||
.pstats { font-size:9px; }
|
||||
.padj { width:23px; height:23px; font-size:12px; }
|
||||
.add-p { font-size:10px; padding:8px 10px; }
|
||||
.pitcher-panel { border-radius:9px; margin-bottom:0; }
|
||||
.log-panel { border-radius:9px; }
|
||||
.log-inner { max-height:230px; }
|
||||
.log-row { font-size:11px; padding:9px 12px; }
|
||||
.empty-log { padding:25px; font-family:var(--font-serif); color:var(--muted); font-size:14px; }
|
||||
.log-filters { padding:8px; gap:4px; }
|
||||
.log-fpill,.log-filter-inn { font-size:9px; }
|
||||
.log-filter-label { font-size:9px; }
|
||||
.workspace-view { grid-column:1/-1; }
|
||||
.view-heading { padding:6px 0 22px; }
|
||||
.view-heading h2 { font:30px var(--font-serif); letter-spacing:-.5px; margin:9px 0; }
|
||||
.view-heading p { font-size:12px; color:var(--muted); line-height:1.5; }
|
||||
#lineupsPanel .lineup-grid { gap:24px; }
|
||||
#lineupsPanel .lineup-hdr { padding:14px 16px; background:var(--header-bg); font-size:13px; }
|
||||
#lineupsPanel .lineup-row { padding:10px 12px; }
|
||||
#lineupsPanel .bname { font-size:13px; }
|
||||
#lineupsPanel .set-btn,#lineupsPanel .sub-btn { min-height:34px; }
|
||||
#notesPanel { max-width:850px; }
|
||||
#notesPanel .game-info-toggle { display:none; }
|
||||
#notesPanel .game-info-body { display:block!important; padding:24px; }
|
||||
#notesPanel .gi-row { margin-bottom:17px; gap:14px; }
|
||||
#notesPanel .gi-label { min-width:90px; font-size:11px; }
|
||||
#notesPanel .gi-input { min-height:36px; font-size:12px; }
|
||||
#notesPanel .gi-textarea { min-height:110px; }
|
||||
.app[data-view=scorecard] .workspace { grid-template-columns:1fr; }
|
||||
.app[data-view=scorecard] .sc-cell { height:63px; }
|
||||
.app[data-view=scorecard] .sc-pa { width:53px; height:53px; }
|
||||
.app[data-view=scorecard] .sc-pname { font-size:14px; }
|
||||
.app[data-view=scorecard] .sc-name { min-width:175px; }
|
||||
.app[data-view=lineups] .workspace,.app[data-view=notes] .workspace { grid-template-columns:1fr; }
|
||||
.site-footer { display:flex; align-items:center; gap:22px; padding:23px 0; border-top:1px solid var(--border); margin-top:35px; color:var(--muted); font-size:10px; }
|
||||
.footer-wordmark { font:bold 18px var(--font-serif); letter-spacing:-.8px; color:var(--brand); }
|
||||
.site-footer button { margin-left:auto; background:none; border:0; color:var(--muted); font-size:10px; }
|
||||
.site-footer button span { margin-left:10px; }
|
||||
@media(min-width:1700px) { .app { padding-top:40px; } .board-content { padding:18px 30px; } .game-state { grid-template-columns:.8fr 1.2fr 1fr; } .sc-cell { height:50px; } .sc-pa { height:42px; width:42px; } }
|
||||
@media(max-width:1150px) { .site-header-inner,.app { padding-left:25px; padding-right:25px; } .brand-tagline { display:none; } .workspace { gap:20px; grid-template-columns:1fr 1fr; } .board-content { grid-template-columns:minmax(240px,.7fr) minmax(400px,1.4fr); gap:18px; padding:20px; } .matchup { gap:8px; } .matchup-score { font-size:35px; } .linescore { padding-left:18px; } .game-state { grid-template-columns:.8fr 1.2fr; } .bases-card { grid-column:1/-1; display:grid; grid-template-columns:1fr 1fr; align-items:center; } .bases-card>.label { grid-column:1/-1; } .bases-field { grid-row:2/4; } .bases-card>.btns { align-self:end; margin:0!important; } .bases-card>.runner-labels { align-self:start; } .infield svg { max-width:160px; } .setup-tip { flex-wrap:wrap; } .setup-tip button { margin-left:33px; } .linescore-title span { display:none; } }
|
||||
@media(max-width:900px) { .workspace { grid-template-columns:1fr; } .col-side { margin-top:10px; } .game-state { grid-template-columns:.8fr 1.3fr 1fr; } .bases-card { grid-column:auto; display:block; } .bases-field { display:block; } .infield svg { max-width:230px; max-height:195px; } .bases-card>.btns { margin-top:8px!important; } .hit-btn { min-height:76px; } .action-row { grid-template-columns:1fr; } .setup-tip { flex-wrap:nowrap; } .setup-tip button { margin-left:auto; } .board-content { grid-template-columns:1fr; gap:20px; } .matchup { max-width:450px; width:100%; margin:auto; } .matchup-badge { width:43px; height:43px; margin-bottom:5px; } .matchup-name { min-height:0; } .matchup-score { font-size:42px; } .linescore { border-left:0; padding-left:0; padding-top:15px; border-top:1px solid #ffffff20; } .linescore-title { display:none; } .hdr-btns { gap:5px; } .library-btn { display:none; } .page-heading { margin-bottom:22px; } h1 { font-size:32px; } .save-status { font-size:10px; } }
|
||||
@media(max-width:600px) {
|
||||
.site-header-inner { min-height:65px; padding:12px 16px; gap:12px; flex-wrap:wrap; }
|
||||
.brand { font-size:26px; gap:6px; } .brand-mark { width:27px; height:27px; }
|
||||
.hdr-btns { gap:6px; } .today-btn,.pdf-btn { padding:8px 10px; font-size:10px; }
|
||||
.export-btn { display:none; } .reset-btn { padding:8px; font-size:10px; }
|
||||
.hdr-btns .sync-pill { display:none; }
|
||||
.app { padding:23px 16px 0; } h1 { font-size:29px; margin-top:9px; } .eyebrow { font-size:8px; letter-spacing:1.5px; }
|
||||
.page-heading { display:block; margin-bottom:20px; } .save-status { margin-top:12px; font-size:9px; } .save-status button { display:none; }
|
||||
.board-topline { padding:12px 15px; font-size:8px; letter-spacing:1px; } #boardVenue { max-width:46%; text-align:right; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
||||
.board-content { padding:19px 12px 13px; gap:15px; } .matchup { gap:10px; } .matchup-name { font-size:11px; } .matchup-score { font-size:37px; }
|
||||
.board-bottom { padding:11px 14px; font-size:9px; gap:8px; } .board-bottom button { font-size:9px; } .board-bottom button span { margin-left:3px; }
|
||||
.score-table { min-width:445px; } .score-table th,.score-table td { padding:8px 5px; font-size:10px; }
|
||||
.score-table .team-sel { max-width:123px; font-size:9px; } .score-table .team-cell img { width:17px!important; height:17px!important; }
|
||||
.workspace-nav { margin:20px 0; overflow:visible; } .view-tabs { width:100%; justify-content:space-between; gap:5px; } .view-tabs button { font-size:11px; padding-bottom:14px; } .view-tabs button span { display:none; } .shortcuts-btn { display:none; }
|
||||
.section-heading h2 { font-size:21px; } .section-heading>span { font-size:9px; }
|
||||
.setup-tip { gap:8px; align-items:flex-start; padding:12px; flex-wrap:wrap; } .setup-tip strong { font-size:11px; } .setup-tip p { font-size:10px; } .setup-tip>div { flex:1; } .setup-tip button { margin-left:28px; margin-top:1px; }
|
||||
.atbat-name { font-size:16px; } .atbat-bar { padding:12px; } .atbat-batter { flex-basis:65%; } .atbat-vs { flex:1; } .atbat-sep { display:none; }
|
||||
.game-state { grid-template-columns:.75fr 1.25fr; gap:9px; }
|
||||
.card { padding:13px 12px; } .label { font-size:8px; letter-spacing:1px; }
|
||||
.bases-card { grid-column:1/-1; display:grid; grid-template-columns:1.1fr 1fr; gap:0 12px; padding:13px; }
|
||||
.bases-card>.label { grid-column:1/-1; margin-bottom:10px; } .bases-field { grid-row:2/4; } .infield svg { max-width:180px; }
|
||||
.bases-card>.btns { margin:0!important; align-self:end; } .bases-card>.runner-labels { align-self:start; padding-top:10px; }
|
||||
.count-card .btn.big { padding:10px 4px; } .count-card kbd { display:none; } .dot { width:16px; height:16px; }
|
||||
.stadium-photo img { max-height:75px; }
|
||||
.hit-btns { grid-template-columns:repeat(3,1fr); gap:7px; } .hit-btn { min-height:67px; } .hlabel { font-size:10px; }
|
||||
.strikeout-card { gap:12px; } .ko-btn { padding:10px; } .out-card summary { padding:14px 12px; } .out-card summary span { font-size:8px; max-width:160px; text-align:right; line-height:1.4; }
|
||||
.fielder-grid { grid-template-columns:repeat(5,1fr); }
|
||||
.sc-tabs { flex-wrap:wrap; } .ps-badge { font-size:8px; } .sc-tab { font-size:9px; } .sc-name { min-width:105px; }
|
||||
.col-side .lineup-grid { grid-template-columns:1fr; } .prow { padding:12px; } .pname,.pitcher-select { font-size:12px; } .pstats { font-size:10px; } .ph { font-size:12px; }
|
||||
#lineupsPanel .lineup-grid { grid-template-columns:1fr; gap:18px; } #lineupsPanel .lineup-row { padding:9px 7px; }
|
||||
#notesPanel .game-info-body { padding:16px 12px; } #notesPanel .gi-row { flex-wrap:wrap; gap:8px; } #notesPanel .gi-label { flex-basis:100%; font-weight:600; } #notesPanel .gi-input { min-width:0; } .gi-weather-row { flex-wrap:wrap; }
|
||||
.site-footer { gap:10px; flex-wrap:wrap; margin-top:27px; padding:20px 0; font-size:9px; } .site-footer>span:nth-child(2) { display:none; } .site-footer button { font-size:9px; }
|
||||
.app[data-view=scorecard] .sc-name { min-width:110px; } .app[data-view=scorecard] .sc-pname { font-size:11px; }
|
||||
}
|
||||
@media(prefers-reduced-motion:reduce) { * { scroll-behavior:auto!important; transition:none!important; } }
|
||||
@media print {
|
||||
:root { --text:#1a1a1a; --muted:#555; --surface:#fff; --border:#bbb; }
|
||||
.site-header,.page-heading,.workspace-nav,.site-footer,.setup-tip,.skip-link,.board-topline,.matchup,.board-bottom,.linescore-title,.section-heading { display:none!important; }
|
||||
.app { padding:0; } .workspace { display:block; } .workspace-view[hidden],#scoringPanel[hidden],#scorecardPanel[hidden] { display:block!important; }
|
||||
.scoreboard { background:white; color:black; border-radius:0; box-shadow:none; } .board-content { display:block; padding:0; } .linescore { border:0; padding:0; }
|
||||
.score-table th,.score-table td,.score-table .team-sel { color:#222; } .score-table tr { border-color:#aaa; }
|
||||
.out-card { display:none; } .col-side { margin-top:0; } .sc-table { width:100%; } .sc-name { min-width:110px!important; }
|
||||
.sc-cell,.app[data-view=scorecard] .sc-cell { height:44px; } .sc-pa,.app[data-view=scorecard] .sc-pa { width:38px; height:38px; }
|
||||
.view-heading { display:none; } #notesPanel { max-width:none; } #notesPanel .game-info-body { padding:8px; }
|
||||
}
|
||||
/* Keep active games compact, with the full inning table a tap away on phones. */
|
||||
.mobile-linescore { display:none; }
|
||||
.app.has-plays .page-heading h1 { display:none; }
|
||||
.app.has-plays .page-heading { margin-bottom:18px; }
|
||||
.app.has-plays .page-heading .eyebrow { margin-top:0; }
|
||||
@media(min-width:901px) { .board-content { padding-top:10px; padding-bottom:10px; } .matchup-badge { width:32px; height:32px; margin-bottom:5px; } .matchup-badge img { width:24px; height:24px; } .matchup-name { min-height:20px; } }
|
||||
@media(max-width:600px) {
|
||||
.site-header-inner { gap:9px; padding:11px 16px; } .hdr-btns { flex-basis:100%; justify-content:flex-end; }
|
||||
.app.has-plays .page-heading { display:flex; align-items:center; gap:8px; margin-bottom:17px; } .app.has-plays .save-status { margin:0; font-size:8px; } .app.has-plays .page-heading .eyebrow { font-size:7px; letter-spacing:.8px; }
|
||||
.app.has-matchup .linescore { display:none; } .app.has-matchup .scoreboard.show-linescore .linescore { display:block; }
|
||||
.app.has-matchup .mobile-linescore { display:block; flex:none; color:#d6dfce; }
|
||||
.app.has-matchup .board-bottom { flex-wrap:wrap; } .app.has-matchup #boardSituation { flex-basis:100%; }
|
||||
.game-state { grid-template-columns:minmax(125px,.8fr) minmax(0,1.2fr); }
|
||||
.game-state>.card { min-width:0; }
|
||||
.count-card .btn.big { min-width:0; min-height:44px; font-size:10px; }
|
||||
.count-card .btns#brBtns { gap:4px; } .count-card .btns#brBtns .btn { padding:5px; min-width:28px; }
|
||||
.inn-ctrl { gap:3px; flex-wrap:wrap; }
|
||||
}
|
||||
@media print { .mobile-linescore { display:none!important; } }
|
||||
|
Before Width: | Height: | Size: 1.4 KiB |
@@ -1,32 +0,0 @@
|
||||
rules_version = '2';
|
||||
|
||||
// Baseball Scorecard sync: each signed-in user reads and writes only their own games.
|
||||
// An update is accepted only if it's newer than what's stored, so an older offline
|
||||
// edit can't overwrite a newer one (the app then keeps the older version as a copy).
|
||||
// Games are never hard-deleted from the app; deletions are stored as { deleted: true }.
|
||||
service cloud.firestore {
|
||||
match /databases/{database}/documents {
|
||||
match /users/{uid}/games/{gameId} {
|
||||
function isOwner() {
|
||||
return request.auth != null && request.auth.uid == uid;
|
||||
}
|
||||
function validGame() {
|
||||
let d = request.resource.data;
|
||||
return d.updatedAt is number
|
||||
&& d.deleted is bool
|
||||
&& (d.payload == null || (d.payload is string && d.payload.size() < 900000));
|
||||
}
|
||||
|
||||
allow read: if isOwner();
|
||||
allow create: if isOwner() && validGame();
|
||||
allow update: if isOwner() && validGame()
|
||||
&& request.resource.data.updatedAt > resource.data.updatedAt;
|
||||
allow delete: if false;
|
||||
}
|
||||
|
||||
// Nothing else is readable or writable
|
||||
match /{document=**} {
|
||||
allow read, write: if false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Before Width: | Height: | Size: 22 KiB |
|
Before Width: | Height: | Size: 115 KiB |
@@ -1,160 +0,0 @@
|
||||
// Reference data: positions, MLB teams and ids, logos, ballparks and stadium photos, postseason rounds.
|
||||
// Loaded as a plain script; files share one global scope (see index.html for the order).
|
||||
|
||||
var POSITIONS = ['—','P','C','1B','2B','3B','SS','LF','CF','RF','DH','PH','PR','IF','OF'];
|
||||
|
||||
// Map team name → MLB Stats API team ID
|
||||
var TEAM_IDS = {
|
||||
'Arizona Diamondbacks':109,'Atlanta Braves':144,'Baltimore Orioles':110,
|
||||
'Boston Red Sox':111,'Chicago Cubs':112,'Chicago White Sox':145,
|
||||
'Cincinnati Reds':113,'Cleveland Guardians':114,'Colorado Rockies':115,
|
||||
'Detroit Tigers':116,'Houston Astros':117,'Kansas City Royals':118,
|
||||
'Los Angeles Angels':108,'Los Angeles Dodgers':119,'Miami Marlins':146,
|
||||
'Milwaukee Brewers':158,'Minnesota Twins':142,'New York Mets':121,
|
||||
'New York Yankees':147,'Oakland Athletics':133,'Philadelphia Phillies':143,
|
||||
'Pittsburgh Pirates':134,'San Diego Padres':135,'San Francisco Giants':137,
|
||||
'Seattle Mariners':136,'St. Louis Cardinals':138,'Tampa Bay Rays':139,
|
||||
'Texas Rangers':140,'Toronto Blue Jays':141,'Washington Nationals':120
|
||||
};
|
||||
|
||||
// Reverse map: team ID → team name
|
||||
var TEAM_NAMES = {};
|
||||
|
||||
Object.keys(TEAM_IDS).forEach(function(name){ TEAM_NAMES[TEAM_IDS[name]] = name; });
|
||||
|
||||
var MLB_TEAMS = [
|
||||
'— Select Team —',
|
||||
// AL East
|
||||
'Baltimore Orioles','Boston Red Sox','New York Yankees','Tampa Bay Rays','Toronto Blue Jays',
|
||||
// AL Central
|
||||
'Chicago White Sox','Cleveland Guardians','Detroit Tigers','Kansas City Royals','Minnesota Twins',
|
||||
// AL West
|
||||
'Houston Astros','Los Angeles Angels','Oakland Athletics','Seattle Mariners','Texas Rangers',
|
||||
// NL East
|
||||
'Atlanta Braves','Miami Marlins','New York Mets','Philadelphia Phillies','Washington Nationals',
|
||||
// NL Central
|
||||
'Chicago Cubs','Cincinnati Reds','Milwaukee Brewers','Pittsburgh Pirates','St. Louis Cardinals',
|
||||
// NL West
|
||||
'Arizona Diamondbacks','Colorado Rockies','Los Angeles Dodgers','San Diego Padres','San Francisco Giants'
|
||||
];
|
||||
|
||||
// Postseason badge per game type. MLB doesn't publish the round-specific event
|
||||
// logos on its CDN, so pair the league logo with the round name.
|
||||
var MLB_LEAGUE_LOGO = 'https://www.mlbstatic.com/team-logos/league-on-light/';
|
||||
|
||||
// maxGames: series length, for the "Game #" picker
|
||||
var POSTSEASON = {
|
||||
wild: { label:'Wild Card', logo: MLB_LEAGUE_LOGO + '1.svg', maxGames: 3 },
|
||||
alds: { label:'ALDS', logo: MLB_LEAGUE_LOGO + '103.svg', maxGames: 5,
|
||||
official: { '2026': 'assets/postseason/alds-2026.png' } }, // that year's official logo, bundled
|
||||
alcs: { label:'ALCS', logo: MLB_LEAGUE_LOGO + '103.svg', maxGames: 7,
|
||||
official: { '2026': 'assets/postseason/alcs-2026.png' } },
|
||||
nlds: { label:'NLDS', logo: MLB_LEAGUE_LOGO + '104.svg', maxGames: 5,
|
||||
official: { '2026': 'assets/postseason/nlds-2026.png' } },
|
||||
nlcs: { label:'NLCS', logo: MLB_LEAGUE_LOGO + '104.svg', maxGames: 7,
|
||||
official: { '2026': 'assets/postseason/nlcs-2026.png' } },
|
||||
ws: { label:'World Series', logo: MLB_LEAGUE_LOGO + '1.svg', maxGames: 7,
|
||||
official: { '2026': 'assets/postseason/ws-2026.png' } }
|
||||
};
|
||||
|
||||
var TEAM_LOGOS = {
|
||||
'Arizona Diamondbacks': 'https://www.mlbstatic.com/team-logos/109.svg',
|
||||
'Atlanta Braves': 'https://www.mlbstatic.com/team-logos/144.svg',
|
||||
'Baltimore Orioles': 'https://www.mlbstatic.com/team-logos/110.svg',
|
||||
'Boston Red Sox': 'https://www.mlbstatic.com/team-logos/111.svg',
|
||||
'Chicago Cubs': 'https://www.mlbstatic.com/team-logos/112.svg',
|
||||
'Chicago White Sox': 'https://www.mlbstatic.com/team-logos/145.svg',
|
||||
'Cincinnati Reds': 'https://www.mlbstatic.com/team-logos/113.svg',
|
||||
'Cleveland Guardians': 'https://www.mlbstatic.com/team-logos/114.svg',
|
||||
'Colorado Rockies': 'https://www.mlbstatic.com/team-logos/115.svg',
|
||||
'Detroit Tigers': 'https://www.mlbstatic.com/team-logos/116.svg',
|
||||
'Houston Astros': 'https://www.mlbstatic.com/team-logos/117.svg',
|
||||
'Kansas City Royals': 'https://www.mlbstatic.com/team-logos/118.svg',
|
||||
'Los Angeles Angels': 'https://www.mlbstatic.com/team-logos/108.svg',
|
||||
'Los Angeles Dodgers': 'https://www.mlbstatic.com/team-logos/119.svg',
|
||||
'Miami Marlins': 'https://www.mlbstatic.com/team-logos/146.svg',
|
||||
'Milwaukee Brewers': 'https://www.mlbstatic.com/team-logos/158.svg',
|
||||
'Minnesota Twins': 'https://www.mlbstatic.com/team-logos/142.svg',
|
||||
'New York Mets': 'https://www.mlbstatic.com/team-logos/121.svg',
|
||||
'New York Yankees': 'https://www.mlbstatic.com/team-logos/147.svg',
|
||||
'Oakland Athletics': 'https://www.mlbstatic.com/team-logos/133.svg',
|
||||
'Philadelphia Phillies': 'https://www.mlbstatic.com/team-logos/143.svg',
|
||||
'Pittsburgh Pirates': 'https://www.mlbstatic.com/team-logos/134.svg',
|
||||
'San Diego Padres': 'https://www.mlbstatic.com/team-logos/135.svg',
|
||||
'San Francisco Giants': 'https://www.mlbstatic.com/team-logos/137.svg',
|
||||
'Seattle Mariners': 'https://www.mlbstatic.com/team-logos/136.svg',
|
||||
'St. Louis Cardinals': 'https://www.mlbstatic.com/team-logos/138.svg',
|
||||
'Tampa Bay Rays': 'https://www.mlbstatic.com/team-logos/139.svg',
|
||||
'Texas Rangers': 'https://www.mlbstatic.com/team-logos/140.svg',
|
||||
'Toronto Blue Jays': 'https://www.mlbstatic.com/team-logos/141.svg',
|
||||
'Washington Nationals': 'https://www.mlbstatic.com/team-logos/120.svg'
|
||||
};
|
||||
|
||||
// ── Ballparks (venue names and locations, used for venue auto-fill) ──
|
||||
var STADIUMS = {
|
||||
'Arizona Diamondbacks': { name:'Chase Field', lat:33.44528, lng:-112.06694 },
|
||||
'Atlanta Braves': { name:'Truist Park', lat:33.89089, lng:-84.46778 },
|
||||
'Baltimore Orioles': { name:'Oriole Park', lat:39.28389, lng:-76.62167 },
|
||||
'Boston Red Sox': { name:'Fenway Park', lat:42.34667, lng:-71.09722 },
|
||||
'Chicago Cubs': { name:'Wrigley Field', lat:41.94833, lng:-87.65528 },
|
||||
'Chicago White Sox': { name:'Guaranteed Rate Field', lat:41.83000, lng:-87.63389 },
|
||||
'Cincinnati Reds': { name:'Great American Ball Park',lat:39.09750, lng:-84.50833 },
|
||||
'Cleveland Guardians': { name:'Progressive Field', lat:41.49583, lng:-81.68528 },
|
||||
'Colorado Rockies': { name:'Coors Field', lat:39.75583, lng:-104.99417 },
|
||||
'Detroit Tigers': { name:'Comerica Park', lat:42.33917, lng:-83.04861 },
|
||||
'Houston Astros': { name:'Minute Maid Park', lat:29.75722, lng:-95.35556 },
|
||||
'Kansas City Royals': { name:'Kauffman Stadium', lat:39.05139, lng:-94.48028 },
|
||||
'Los Angeles Angels': { name:'Angel Stadium', lat:33.80028, lng:-117.88278 },
|
||||
'Los Angeles Dodgers': { name:'Dodger Stadium', lat:34.07361, lng:-118.24000 },
|
||||
'Miami Marlins': { name:'LoanDepot Park', lat:25.77806, lng:-80.21972 },
|
||||
'Milwaukee Brewers': { name:'American Family Field', lat:43.02806, lng:-87.97111 },
|
||||
'Minnesota Twins': { name:'Target Field', lat:44.98167, lng:-93.27806 },
|
||||
'New York Mets': { name:'Citi Field', lat:40.75694, lng:-73.84583 },
|
||||
'New York Yankees': { name:'Yankee Stadium', lat:40.82944, lng:-73.92611 },
|
||||
'Oakland Athletics': { name:'Sutter Health Park', lat:38.58000, lng:-121.50056 },
|
||||
'Philadelphia Phillies': { name:'Citizens Bank Park', lat:39.90583, lng:-75.16639 },
|
||||
'Pittsburgh Pirates': { name:'PNC Park', lat:40.44694, lng:-80.00583 },
|
||||
'San Diego Padres': { name:'Petco Park', lat:32.70722, lng:-117.15722 },
|
||||
'San Francisco Giants': { name:'Oracle Park', lat:37.77861, lng:-122.38917 },
|
||||
'Seattle Mariners': { name:'T-Mobile Park', lat:47.59139, lng:-122.33250 },
|
||||
'St. Louis Cardinals': { name:'Busch Stadium', lat:38.62250, lng:-90.19278 },
|
||||
'Tampa Bay Rays': { name:'Tropicana Field', lat:27.76833, lng:-82.65333 },
|
||||
'Texas Rangers': { name:'Globe Life Field', lat:32.74722, lng:-97.08222 },
|
||||
'Toronto Blue Jays': { name:'Rogers Centre', lat:43.64139, lng:-79.38944 },
|
||||
'Washington Nationals': { name:'Nationals Park', lat:38.87306, lng:-77.00750 }
|
||||
};
|
||||
|
||||
// Stadium photos: each ballpark's lead photo from Wikipedia / Wikimedia Commons
|
||||
// (freely licensed — credited under the photo, linking to the file page).
|
||||
var STADIUM_PHOTOS = {
|
||||
"Arizona Diamondbacks": { img:"https://thumb.wikimedia.org/wikipedia/commons/thumb/a/a2/Reserve_A-10_Warthogs_Flyover_2023_World_Series_%288099146%29.jpg/500px-Reserve_A-10_Warthogs_Flyover_2023_World_Series_%288099146%29.jpg?utm_source=commons.wikimedia.org&utm_campaign=imageinfo&utm_content=thumbnail", page:"https://commons.wikimedia.org/wiki/File:Reserve_A-10_Warthogs_Flyover_2023_World_Series_(8099146).jpg", by:"U.S. Air Force photo by Staff Sgt. Tyler J. Bolken", lic:"Public domain" },
|
||||
"Athletics": { img:"https://thumb.wikimedia.org/wikipedia/commons/thumb/e/e6/Sutter_Health_Park_aerial_view_2023_%28Quintin_Soloviev%29.jpg/500px-Sutter_Health_Park_aerial_view_2023_%28Quintin_Soloviev%29.jpg?utm_source=commons.wikimedia.org&utm_campaign=imageinfo&utm_content=thumbnail", page:"https://commons.wikimedia.org/wiki/File:Sutter_Health_Park_aerial_view_2023_(Quintin_Soloviev).jpg", by:"Quintin Soloviev", lic:"CC BY 4.0" },
|
||||
"Atlanta Braves": { img:"https://thumb.wikimedia.org/wikipedia/commons/thumb/0/04/Truist_Park_2025.jpg/500px-Truist_Park_2025.jpg?utm_source=commons.wikimedia.org&utm_campaign=imageinfo&utm_content=thumbnail", page:"https://commons.wikimedia.org/wiki/File:Truist_Park_2025.jpg", by:"TarheelBornBred", lic:"CC0" },
|
||||
"Baltimore Orioles": { img:"https://thumb.wikimedia.org/wikipedia/commons/thumb/5/51/OrioleParkatCamdenYardsSummer2025.jpg/500px-OrioleParkatCamdenYardsSummer2025.jpg?utm_source=commons.wikimedia.org&utm_campaign=imageinfo&utm_content=thumbnail", page:"https://commons.wikimedia.org/wiki/File:OrioleParkatCamdenYardsSummer2025.jpg", by:"Aspifi", lic:"CC BY-SA 4.0" },
|
||||
"Boston Red Sox": { img:"https://thumb.wikimedia.org/wikipedia/commons/thumb/4/4f/131023-F-PR861-033_Hanscom_participates_in_World_Series_pregame_events.jpg/500px-131023-F-PR861-033_Hanscom_participates_in_World_Series_pregame_events.jpg?utm_source=commons.wikimedia.org&utm_campaign=imageinfo&utm_content=thumbnail", page:"https://commons.wikimedia.org/wiki/File:131023-F-PR861-033_Hanscom_participates_in_World_Series_pregame_events.jpg", by:"Rick Berry", lic:"Public domain" },
|
||||
"Chicago Cubs": { img:"https://thumb.wikimedia.org/wikipedia/commons/thumb/c/c9/Wrigley_Field_in_line_with_sign.jpg/500px-Wrigley_Field_in_line_with_sign.jpg?utm_source=commons.wikimedia.org&utm_campaign=imageinfo&utm_content=thumbnail", page:"https://commons.wikimedia.org/wiki/File:Wrigley_Field_in_line_with_sign.jpg", by:"Sea Cow", lic:"CC BY-SA 4.0" },
|
||||
"Chicago White Sox": { img:"https://thumb.wikimedia.org/wikipedia/commons/thumb/5/57/Chicago%2C_Illinois%2C_U.S._%282023%29_-_062.jpg/500px-Chicago%2C_Illinois%2C_U.S._%282023%29_-_062.jpg?utm_source=commons.wikimedia.org&utm_campaign=imageinfo&utm_content=thumbnail", page:"https://commons.wikimedia.org/wiki/File:Chicago,_Illinois,_U.S._(2023)_-_062.jpg", by:"Another Believer", lic:"CC BY-SA 4.0" },
|
||||
"Cincinnati Reds": { img:"https://thumb.wikimedia.org/wikipedia/commons/thumb/4/4a/10Cincinnati_2015_%282%29.jpg/500px-10Cincinnati_2015_%282%29.jpg?utm_source=commons.wikimedia.org&utm_campaign=imageinfo&utm_content=thumbnail", page:"https://commons.wikimedia.org/wiki/File:10Cincinnati_2015_(2).jpg", by:"Laslovarga", lic:"CC BY-SA 4.0" },
|
||||
"Cleveland Guardians": { img:"https://thumb.wikimedia.org/wikipedia/commons/thumb/f/f1/Cleveland_Guardians_vs._New_York_Yankees_on_Oct_17_2024_%2854102149292%29.jpg/500px-Cleveland_Guardians_vs._New_York_Yankees_on_Oct_17_2024_%2854102149292%29.jpg?utm_source=commons.wikimedia.org&utm_campaign=imageinfo&utm_content=thumbnail", page:"https://commons.wikimedia.org/wiki/File:Cleveland_Guardians_vs._New_York_Yankees_on_Oct_17_2024_(54102149292).jpg", by:"Erik Drost", lic:"CC BY 2.0" },
|
||||
"Colorado Rockies": { img:"https://thumb.wikimedia.org/wikipedia/commons/thumb/e/e2/Coors_Field_July_2015.jpg/500px-Coors_Field_July_2015.jpg?utm_source=commons.wikimedia.org&utm_campaign=imageinfo&utm_content=thumbnail", page:"https://commons.wikimedia.org/wiki/File:Coors_Field_July_2015.jpg", by:"Thelastcanadian", lic:"CC BY-SA 4.0" },
|
||||
"Detroit Tigers": { img:"https://thumb.wikimedia.org/wikipedia/commons/thumb/0/06/Detroit_Tigers_opening_game_at_Comerica_Park%2C_2007.jpg/500px-Detroit_Tigers_opening_game_at_Comerica_Park%2C_2007.jpg?utm_source=commons.wikimedia.org&utm_campaign=imageinfo&utm_content=thumbnail", page:"https://commons.wikimedia.org/wiki/File:Detroit_Tigers_opening_game_at_Comerica_Park,_2007.jpg", by:"User MJCdetroit on en.wikipedia", lic:"CC BY-SA 3.0" },
|
||||
"Houston Astros": { img:"https://thumb.wikimedia.org/wikipedia/commons/thumb/1/10/Houston%2C_Texas_%282024%29_-_09.jpg/500px-Houston%2C_Texas_%282024%29_-_09.jpg?utm_source=commons.wikimedia.org&utm_campaign=imageinfo&utm_content=thumbnail", page:"https://commons.wikimedia.org/wiki/File:Houston,_Texas_(2024)_-_09.jpg", by:"Another Believer", lic:"CC BY-SA 4.0" },
|
||||
"Kansas City Royals": { img:"https://thumb.wikimedia.org/wikipedia/commons/thumb/3/35/Kauffman2017.jpg/500px-Kauffman2017.jpg?utm_source=commons.wikimedia.org&utm_campaign=imageinfo&utm_content=thumbnail", page:"https://commons.wikimedia.org/wiki/File:Kauffman2017.jpg", by:"Chibears85", lic:"CC BY-SA 4.0" },
|
||||
"Los Angeles Angels": { img:"https://thumb.wikimedia.org/wikipedia/commons/thumb/4/4a/Angelstadiummarch2019.jpg/500px-Angelstadiummarch2019.jpg?utm_source=commons.wikimedia.org&utm_campaign=imageinfo&utm_content=thumbnail", page:"https://commons.wikimedia.org/wiki/File:Angelstadiummarch2019.jpg", by:"CrispyCream27", lic:"CC BY-SA 4.0" },
|
||||
"Los Angeles Dodgers": { img:"https://thumb.wikimedia.org/wikipedia/commons/thumb/5/50/Dodger_Stadium_and_Chavez_Ravine_far_view%2C_Chicago_Cubs_at_Los_Angeles_Dodgers%2C_%28April_12%2C_2025%29.jpg/500px-Dodger_Stadium_and_Chavez_Ravine_far_view%2C_Chicago_Cubs_at_Los_Angeles_Dodgers%2C_%28April_12%2C_2025%29.jpg?utm_source=commons.wikimedia.org&utm_campaign=imageinfo&utm_content=thumbnail", page:"https://commons.wikimedia.org/wiki/File:Dodger_Stadium_and_Chavez_Ravine_far_view,_Chicago_Cubs_at_Los_Angeles_Dodgers,_(April_12,_2025).jpg", by:"Spatms", lic:"CC BY-SA 4.0" },
|
||||
"Miami Marlins": { img:"https://thumb.wikimedia.org/wikipedia/commons/thumb/5/53/LOAN_DEPOT_PARK.jpg/500px-LOAN_DEPOT_PARK.jpg?utm_source=commons.wikimedia.org&utm_campaign=imageinfo&utm_content=thumbnail", page:"https://commons.wikimedia.org/wiki/File:LOAN_DEPOT_PARK.jpg", by:"Ven-Lib", lic:"CC BY-SA 4.0" },
|
||||
"Milwaukee Brewers": { img:"https://thumb.wikimedia.org/wikipedia/commons/thumb/c/cc/Miller_Park_in_Milwaukee%2C_Wisconsin.jpg/500px-Miller_Park_in_Milwaukee%2C_Wisconsin.jpg?utm_source=commons.wikimedia.org&utm_campaign=imageinfo&utm_content=thumbnail", page:"https://commons.wikimedia.org/wiki/File:Miller_Park_in_Milwaukee,_Wisconsin.jpg", by:"Carol H. Highsmith", lic:"Public domain" },
|
||||
"Minnesota Twins": { img:"https://thumb.wikimedia.org/wikipedia/commons/thumb/1/17/Target_Field%2C_Minneapolis%2C_Minnesota_%2843167053335%29.jpg/500px-Target_Field%2C_Minneapolis%2C_Minnesota_%2843167053335%29.jpg?utm_source=commons.wikimedia.org&utm_campaign=imageinfo&utm_content=thumbnail", page:"https://commons.wikimedia.org/wiki/File:Target_Field,_Minneapolis,_Minnesota_(43167053335).jpg", by:"Ken Lund from Reno, Nevada, USA", lic:"CC BY-SA 2.0" },
|
||||
"New York Mets": { img:"https://thumb.wikimedia.org/wikipedia/commons/thumb/e/e6/Citi_Field_%2848613685207%29.jpg/500px-Citi_Field_%2848613685207%29.jpg?utm_source=commons.wikimedia.org&utm_campaign=imageinfo&utm_content=thumbnail", page:"https://commons.wikimedia.org/wiki/File:Citi_Field_(48613685207).jpg", by:"Ajay Suresh from New York, NY, USA", lic:"CC BY 2.0" },
|
||||
"New York Yankees": { img:"https://thumb.wikimedia.org/wikipedia/commons/thumb/a/af/Yankee_Stadium_overhead_2010.jpg/500px-Yankee_Stadium_overhead_2010.jpg?utm_source=commons.wikimedia.org&utm_campaign=imageinfo&utm_content=thumbnail", page:"https://commons.wikimedia.org/wiki/File:Yankee_Stadium_overhead_2010.jpg", by:"vtravelled.com", lic:"CC BY 2.0" },
|
||||
"Philadelphia Phillies": { img:"https://thumb.wikimedia.org/wikipedia/commons/thumb/f/f6/Citizens_Bank_Park_2021.jpg/500px-Citizens_Bank_Park_2021.jpg?utm_source=commons.wikimedia.org&utm_campaign=imageinfo&utm_content=thumbnail", page:"https://commons.wikimedia.org/wiki/File:Citizens_Bank_Park_2021.jpg", by:"Chris6d", lic:"CC BY-SA 4.0" },
|
||||
"Pittsburgh Pirates": { img:"https://thumb.wikimedia.org/wikipedia/commons/thumb/0/0e/Pittsburgh_Pirates_park_%28Unsplash%29.jpg/500px-Pittsburgh_Pirates_park_%28Unsplash%29.jpg?utm_source=commons.wikimedia.org&utm_campaign=imageinfo&utm_content=thumbnail", page:"https://commons.wikimedia.org/wiki/File:Pittsburgh_Pirates_park_(Unsplash).jpg", by:"Joshua Peacock jcpeacock", lic:"CC0" },
|
||||
"San Diego Padres": { img:"https://thumb.wikimedia.org/wikipedia/commons/thumb/5/55/Petco_Park_Padres_Game.jpg/500px-Petco_Park_Padres_Game.jpg?utm_source=commons.wikimedia.org&utm_campaign=imageinfo&utm_content=thumbnail", page:"https://commons.wikimedia.org/wiki/File:Petco_Park_Padres_Game.jpg", by:"Mds08011", lic:"CC BY 4.0" },
|
||||
"San Francisco Giants": { img:"https://thumb.wikimedia.org/wikipedia/commons/thumb/8/8e/Oracle_Park_2021.jpg/500px-Oracle_Park_2021.jpg?utm_source=commons.wikimedia.org&utm_campaign=imageinfo&utm_content=thumbnail", page:"https://commons.wikimedia.org/wiki/File:Oracle_Park_2021.jpg", by:"Chris6d", lic:"CC BY-SA 4.0" },
|
||||
"Seattle Mariners": { img:"https://thumb.wikimedia.org/wikipedia/commons/thumb/1/10/SafecoFieldTop.jpg/500px-SafecoFieldTop.jpg?utm_source=commons.wikimedia.org&utm_campaign=imageinfo&utm_content=thumbnail", page:"https://commons.wikimedia.org/wiki/File:SafecoFieldTop.jpg", by:"MyName (Cacophony)", lic:"CC BY-SA 3.0" },
|
||||
"St. Louis Cardinals": { img:"https://thumb.wikimedia.org/wikipedia/commons/thumb/f/fb/Busch_Stadium_2022.jpg/500px-Busch_Stadium_2022.jpg?utm_source=commons.wikimedia.org&utm_campaign=imageinfo&utm_content=thumbnail", page:"https://commons.wikimedia.org/wiki/File:Busch_Stadium_2022.jpg", by:"Lightmetro", lic:"CC BY-SA 4.0" },
|
||||
"Tampa Bay Rays": { img:"https://thumb.wikimedia.org/wikipedia/commons/thumb/5/5e/PXL_20220528_205520913.jpg/500px-PXL_20220528_205520913.jpg?utm_source=commons.wikimedia.org&utm_campaign=imageinfo&utm_content=thumbnail", page:"https://commons.wikimedia.org/wiki/File:PXL_20220528_205520913.jpg", by:"Vmartin12", lic:"CC BY-SA 4.0" },
|
||||
"Texas Rangers": { img:"https://thumb.wikimedia.org/wikipedia/commons/thumb/a/a0/GlobeLifeField2021.jpg/500px-GlobeLifeField2021.jpg?utm_source=commons.wikimedia.org&utm_campaign=imageinfo&utm_content=thumbnail", page:"https://commons.wikimedia.org/wiki/File:GlobeLifeField2021.jpg", by:"slgckgc", lic:"CC BY 2.0" },
|
||||
"Toronto Blue Jays": { img:"https://thumb.wikimedia.org/wikipedia/commons/thumb/6/6e/Rogers_Centre_%28500_Level%29_-_Toronto%2C_ON.jpg/500px-Rogers_Centre_%28500_Level%29_-_Toronto%2C_ON.jpg?utm_source=commons.wikimedia.org&utm_campaign=imageinfo&utm_content=thumbnail", page:"https://commons.wikimedia.org/wiki/File:Rogers_Centre_(500_Level)_-_Toronto,_ON.jpg", by:"JFVoll", lic:"CC BY-SA 4.0" },
|
||||
"Washington Nationals": { img:"https://thumb.wikimedia.org/wikipedia/commons/thumb/f/f9/Nationals_Park_8.16.19_-_7.jpg/500px-Nationals_Park_8.16.19_-_7.jpg?utm_source=commons.wikimedia.org&utm_campaign=imageinfo&utm_content=thumbnail", page:"https://commons.wikimedia.org/wiki/File:Nationals_Park_8.16.19_-_7.jpg", by:"APK", lic:"CC BY-SA 4.0" }
|
||||
};
|
||||
@@ -1,41 +0,0 @@
|
||||
// Outfield walls for the Bases card's full-field view. GENERATED by
|
||||
// ~/Developer/stadium-editor/export.py from walls.json; don't edit by hand.
|
||||
// Per home team: w = wall from the left-field pole to the right-field pole, in feet
|
||||
// (x toward right field, y toward center field, home plate at 0,0); t = warning
|
||||
// track width; s = MLB's posted distance signs as [angle from center (+ = left
|
||||
// field), feet]; src = where the outline came from.
|
||||
// Outlines: GeomMLBStadiums (MIT, Ben Dilday; Statcast spray-chart outlines),
|
||||
// adjusted by hand against satellite imagery; Braves from OpenStreetMap
|
||||
// (© OpenStreetMap contributors, ODbL); Rangers and A's from MLB's distances.
|
||||
var FIELD_WALLS = {
|
||||
"Arizona Diamondbacks": {"w":[[-234.0,234.0],[-232.0,262.0],[-228.0,276.5],[-214.5,280.0],[-99.0,383.0],[-86.5,390.5],[-48.0,391.0],[-35.0,399.5],[-21.0,401.0],[31.5,401.0],[41.0,391.5],[83.0,391.0],[96.0,385.0],[210.0,284.0],[232.0,272.0],[235.5,257.0],[235.5,235.5]],"t":23,"s":[[45,328],[-4.5,407],[-45,335]],"src":"statcast"},
|
||||
"Oakland Athletics": {"w":[[-233.5,233.5],[-222.5,247.0],[-213.0,263.0],[-204.0,281.0],[-195.0,300.0],[-183.5,318.5],[-170.5,334.5],[-154.5,346.5],[-136.5,355.0],[-118.0,363.5],[-100.0,372.5],[-81.0,382.0],[-62.0,390.0],[-41.5,397.0],[-21.0,401.5],[0.0,403.0],[21.0,401.5],[41.5,397.0],[62.0,390.0],[81.0,382.0],[100.0,372.5],[118.0,363.5],[136.5,355.0],[154.5,346.5],[170.0,334.0],[183.0,317.0],[193.5,298.0],[202.0,278.5],[210.5,259.5],[219.0,243.5],[230.0,230.0]],"t":15,"s":[[45,330],[21.6,380],[0.0,403],[-21.6,380],[-45,325]],"src":"mlb"},
|
||||
"Atlanta Braves": {"w":[[-237.0,237.0],[-199.0,318.5],[-151.0,352.0],[-45.0,392.5],[39.5,399.0],[140.5,335.5],[228.5,228.5]],"t":19,"s":[[45,335],[32.2,375],[14.5,385],[-5.9,400],[-15.3,375],[-45,325]],"src":"osm"},
|
||||
"Baltimore Orioles": {"w":[[-229.5,229.5],[-237.5,254.5],[-245.0,277.0],[-234.0,304.0],[-206.0,325.0],[-126.0,376.0],[-114.5,384.5],[-107.0,371.5],[-100.0,362.5],[-39.0,403.0],[-28.0,410.0],[117.5,369.5],[129.5,365.5],[168.5,312.0],[176.5,298.0],[195.5,270.5],[224.0,224.0]],"t":20,"s":[[45,333],[15.4,376],[4.2,410],[-23.0,373],[-45,318]],"src":"statcast"},
|
||||
"Boston Red Sox": {"w":[[-216.0,216.0],[-210.0,225.0],[-59.5,375.5],[-36.0,375.5],[71.5,405.0],[81.5,407.0],[92.0,370.0],[101.5,365.5],[228.0,302.5],[236.5,292.0],[241.0,277.0],[239.0,270.0],[214.5,214.5]],"t":14,"s":[[45,310],[-11.3,420],[-45,302]],"src":"statcast"},
|
||||
"Chicago Cubs": {"w":[[-252.5,252.5],[-223.5,279.5],[-183.5,312.0],[-172.0,305.5],[-143.5,324.0],[-34.5,392.5],[-4.5,404.0],[31.5,406.0],[70.0,396.0],[91.5,383.5],[103.5,373.5],[117.5,362.0],[172.0,309.0],[181.0,303.0],[193.5,306.0],[226.5,275.0],[247.5,247.5]],"t":16,"s":[[45,355],[14.5,368],[-10.9,400],[-22.3,368],[-45,353]],"src":"statcast"},
|
||||
"Chicago White Sox": {"w":[[-234.0,234.0],[-189.5,292.0],[-128.0,352.0],[-93.5,374.5],[-45.5,398.0],[-31.5,401.5],[38.5,400.5],[103.0,372.0],[123.5,359.0],[144.5,340.5],[237.5,237.5]],"t":20,"s":[[45,330],[18.4,377],[-6.5,400],[-22.1,372],[-45,335]],"src":"statcast"},
|
||||
"Cincinnati Reds": {"w":[[-230.5,230.5],[-224.0,248.5],[-214.5,260.0],[-100.0,372.5],[-10.5,402.0],[3.5,404.0],[34.5,395.0],[67.0,380.5],[94.5,365.0],[128.0,342.5],[179.0,297.5],[211.5,256.5],[226.5,234.5],[228.5,228.5]],"t":18,"s":[[45,328],[16.8,379],[-0.6,404],[-17.9,370],[-45,325]],"src":"statcast"},
|
||||
"Cleveland Guardians": {"w":[[-229.5,229.5],[-197.5,287.5],[-187.5,300.5],[-28.5,407.5],[-14.0,406.0],[152.5,342.5],[162.0,332.0],[230.0,230.0]],"t":18,"s":[[45,325],[1.6,405],[-17.1,375],[-45,325]],"src":"statcast"},
|
||||
"Colorado Rockies": {"w":[[-242.5,242.5],[-113.5,396.0],[-100.0,401.5],[40.0,413.5],[54.5,413.0],[67.5,403.5],[241.0,258.5],[246.5,246.5]],"t":21,"s":[[45,347],[-5.0,415],[-45,350]],"src":"statcast"},
|
||||
"Detroit Tigers": {"w":[[-241.0,241.0],[-230.0,255.5],[-74.0,404.0],[-51.0,414.0],[70.0,411.0],[98.0,399.5],[108.0,389.5],[127.5,370.5],[138.5,358.0],[142.0,336.0],[214.5,261.0],[234.0,242.5],[234.5,234.5]],"t":21,"s":[[45,345],[21.8,370],[-9.6,420],[-22.9,365],[-45,330]],"src":"statcast"},
|
||||
"Houston Astros": {"w":[[-222.5,222.5],[-180.0,268.5],[-126.0,315.0],[-133.0,334.0],[-38.0,412.5],[-8.5,414.0],[17.0,412.5],[46.5,413.0],[76.0,413.5],[98.5,385.0],[130.0,346.5],[142.0,346.5],[151.0,334.0],[231.5,231.5]],"t":20,"s":[[45,315],[20.5,362],[-12.3,409],[-21.7,373],[-45,326]],"src":"statcast"},
|
||||
"Kansas City Royals": {"w":[[-234.5,234.5],[-237.5,250.0],[-236.0,262.0],[-228.0,281.5],[-190.0,322.5],[-134.5,369.0],[-110.0,384.0],[-70.5,400.0],[-28.5,408.5],[3.5,410.0],[46.0,405.5],[87.5,393.5],[113.0,381.5],[148.5,358.5],[172.5,338.5],[224.0,286.5],[231.0,275.5],[236.0,262.0],[237.0,249.5],[233.5,233.5]],"t":22,"s":[[45,347],[26.8,379],[-0.2,410],[-27.4,379],[-45,344]],"src":"statcast"},
|
||||
"Los Angeles Angels": {"w":[[-237.5,237.5],[-237.0,263.0],[-230.0,279.0],[-152.5,359.5],[14.0,404.5],[207.0,301.0],[227.0,280.5],[235.5,257.0],[237.0,237.0]],"t":19,"s":[[45,330],[20.8,389],[2.9,396],[-33.9,365],[-45,330]],"src":"statcast"},
|
||||
"Los Angeles Dodgers": {"w":[[-233.0,233.0],[-230.5,256.0],[-225.5,273.5],[-214.0,294.0],[-201.5,304.5],[-142.0,343.0],[-89.0,371.0],[-37.5,390.0],[3.5,394.5],[34.0,391.0],[98.0,366.5],[150.5,338.0],[209.0,299.0],[225.5,273.5],[230.0,260.0],[233.0,233.0]],"t":21,"s":[[45,330],[10.1,385],[-0.5,395],[-10.0,385],[-45,330]],"src":"statcast"},
|
||||
"Miami Marlins": {"w":[[-238.5,238.5],[-213.0,277.5],[-195.0,300.5],[-174.0,320.5],[-110.0,370.5],[-68.5,389.0],[-40.0,416.5],[-29.0,417.0],[14.5,413.5],[53.5,404.5],[80.5,395.0],[118.0,375.0],[147.5,348.0],[235.5,235.5]],"t":18,"s":[[45,344],[16.7,386],[-8.3,407],[-17.8,392],[-45,335]],"src":"statcast"},
|
||||
"Milwaukee Brewers": {"w":[[-241.5,241.5],[-228.5,272.5],[-178.5,322.0],[-75.0,369.0],[-58.0,388.0],[-45.0,396.0],[38.0,396.0],[51.5,391.5],[60.0,380.0],[72.5,372.5],[138.5,343.0],[165.5,318.0],[170.5,301.5],[239.5,239.5]],"t":22,"s":[[45,344],[16.1,371],[6.5,400],[-15.4,374],[-45,345]],"src":"statcast"},
|
||||
"Minnesota Twins": {"w":[[-237.5,237.5],[-143.0,344.5],[-49.0,401.0],[-31.5,402.5],[35.0,397.5],[48.0,393.0],[130.0,339.0],[150.5,323.0],[161.5,297.5],[210.5,251.0],[229.5,229.5]],"t":19,"s":[[45,339],[19.1,377],[7.0,404],[-18.5,367],[-45,328]],"src":"statcast"},
|
||||
"New York Mets": {"w":[[-237.5,237.5],[-238.0,242.0],[-218.5,279.5],[-39.0,406.5],[-21.5,411.0],[18.0,411.0],[35.5,405.5],[130.0,347.0],[141.5,341.5],[167.0,335.0],[178.0,327.5],[211.5,280.5],[220.0,253.5],[232.0,232.0]],"t":19,"s":[[45,335],[27.2,358],[18.6,370],[-4.5,408],[-14.8,380],[-29.3,370],[-45,330]],"src":"statcast"},
|
||||
"New York Yankees": {"w":[[-225.5,225.5],[-219.5,259.0],[-209.0,285.0],[-187.5,309.0],[-119.0,373.5],[-89.0,396.0],[-59.5,403.0],[-26.0,410.0],[10.0,408.5],[36.5,404.5],[53.5,397.5],[75.0,383.5],[99.5,359.5],[211.5,256.5],[221.5,242.0],[226.5,226.5]],"t":21,"s":[[45,318],[7.4,408],[-12.4,385],[-45,314]],"src":"statcast"},
|
||||
"Philadelphia Phillies": {"w":[[-231.5,231.5],[-231.0,239.5],[-222.0,251.0],[-108.0,365.0],[-97.0,374.5],[-75.5,371.5],[-50.0,396.0],[-39.0,407.0],[65.0,390.5],[75.5,388.0],[231.0,231.0]],"t":20,"s":[[45,329],[12.2,381],[0.3,401],[-10.0,398],[-45,330]],"src":"statcast"},
|
||||
"Pittsburgh Pirates": {"w":[[-229.5,229.5],[-223.5,281.0],[-219.5,296.5],[-114.0,384.5],[-103.5,383.5],[-88.0,381.5],[-7.0,395.5],[7.0,396.0],[74.0,381.0],[134.5,350.5],[145.5,343.0],[226.5,226.5]],"t":18,"s":[[45,325],[15.0,399],[-21.3,375],[-45,320]],"src":"statcast"},
|
||||
"San Diego Padres": {"w":[[-236.5,236.5],[-218.0,259.5],[-111.5,371.5],[-80.0,389.0],[-57.0,388.0],[-27.5,388.0],[-11.5,398.5],[39.0,401.0],[76.0,395.5],[95.0,388.5],[119.0,366.0],[206.5,279.0],[213.5,268.5],[215.5,239.0],[225.5,225.5]],"t":18,"s":[[45,336],[12.2,396],[-16.2,391],[-45,322]],"src":"statcast"},
|
||||
"San Francisco Giants": {"w":[[-240.5,240.5],[-234.5,255.5],[-224.5,267.5],[-75.0,393.5],[-58.5,393.5],[125.5,394.0],[133.0,393.5],[138.5,382.0],[158.0,329.5],[174.0,320.5],[182.5,310.0],[217.5,217.5]],"t":21,"s":[[45,339],[13.3,391],[-18.5,415],[-45,309]],"src":"statcast"},
|
||||
"Seattle Mariners": {"w":[[-234.5,234.5],[-233.5,242.0],[-226.0,251.0],[-139.5,345.0],[-96.5,372.5],[-17.5,403.0],[-3.5,400.5],[114.5,363.5],[126.5,357.0],[223.0,239.0],[228.0,228.0]],"t":22,"s":[[45,331],[2.5,405],[-10.0,387],[-45,327]],"src":"statcast"},
|
||||
"St. Louis Cardinals": {"w":[[-235.0,235.0],[-238.0,250.5],[-231.0,261.5],[-131.5,361.0],[-120.0,369.0],[-41.5,394.5],[-24.5,397.0],[28.0,397.0],[41.5,394.5],[122.5,366.5],[134.0,358.5],[231.0,261.0],[237.0,237.0]],"t":19,"s":[[45,336],[23.2,375],[-4.0,400],[-23.3,375],[-45,335]],"src":"statcast"},
|
||||
"Tampa Bay Rays": {"w":[[-223.0,223.0],[-227.0,252.0],[-221.5,264.0],[-99.5,385.0],[-78.5,403.0],[-65.0,409.0],[46.0,405.5],[64.0,403.0],[85.5,386.5],[225.5,246.5],[228.5,232.5],[230.0,230.0]],"t":15,"s":[[45,315],[11.1,410],[-10.1,404],[-45,322]],"src":"statcast"},
|
||||
"Texas Rangers": {"w":[[-232.5,232.5],[-142.5,343.5],[0.0,407.0],[143.0,345.5],[230.5,230.5]],"t":15,"s":[[45,329],[22.5,372],[0.0,407],[-22.1,374],[-45,326]],"src":"mlb"},
|
||||
"Toronto Blue Jays": {"w":[[-233.0,233.0],[-165.0,331.0],[-153.5,344.5],[-96.0,385.0],[-80.0,393.0],[-38.5,399.5],[-3.5,401.0],[38.5,399.0],[83.5,392.0],[144.5,349.5],[158.0,338.5],[231.0,231.0]],"t":22,"s":[[45,328],[24.7,375],[11.5,404],[-24.1,375],[-45,328]],"src":"statcast"},
|
||||
"Washington Nationals": {"w":[[-237.5,237.5],[-198.5,300.0],[-181.0,320.0],[-95.5,368.5],[-81.5,367.5],[-21.0,400.5],[-7.0,403.0],[186.0,316.0],[196.0,308.0],[235.5,235.5]],"t":18,"s":[[45,336],[12.8,377],[2.1,402],[-14.4,370],[-45,335]],"src":"statcast"}
|
||||
};
|
||||
@@ -1,11 +0,0 @@
|
||||
// Firebase project settings for sync (Firebase console → Project settings → Your apps → Web).
|
||||
// These values are public by design; the security rules in firestore.rules and the
|
||||
// account's password protect the data. null = sync not set up.
|
||||
var FIREBASE_CONFIG = {
|
||||
apiKey: 'AIzaSyCvvQkrYr-iO0njbnBpZSWHOn5psILcux0',
|
||||
authDomain: 'baseball-scorecard-1b370.firebaseapp.com',
|
||||
projectId: 'baseball-scorecard-1b370',
|
||||
storageBucket: 'baseball-scorecard-1b370.firebasestorage.app',
|
||||
messagingSenderId: '593888563418',
|
||||
appId: '1:593888563418:web:6fe9a2e8801194d12e15e3'
|
||||
};
|
||||
@@ -1,173 +0,0 @@
|
||||
// Follow MLB: keeps the scorecard caught up with MLB's live play-by-play while
|
||||
// watching a game. Every FOLLOW_MS it asks MLB for the game's list of update
|
||||
// times (a few KB) and downloads the play-by-play only when that changed. It
|
||||
// adds the plays the scorecard doesn't have yet (the same code as Catch up, one
|
||||
// Undo step per batch) and moves the count of the at-bat in progress forward —
|
||||
// never back, so scoring pitches yourself ahead of MLB's feed is never undone.
|
||||
// It waits while a dialog or an unfinished entry is open, pauses in the
|
||||
// background, and stops at the final out. The game remembers which device is
|
||||
// following (G.mlbFollow), so with sync on only one device polls.
|
||||
// Loaded as a plain script; files share one global scope (see index.html for the order).
|
||||
|
||||
var FOLLOW_MS = 20000;
|
||||
var _follow = { timer: null, busy: false, stamp: null, pk: null, error: '', checkedAt: 0 };
|
||||
|
||||
function followDevice(){ return (typeof syncState === 'function' && syncState().device) || 'This device'; }
|
||||
function followIsMine(){ return !!(G.mlbFollow && G.mlbFollow.device === followDevice()); }
|
||||
function followIsElsewhere(){ return !!(G.mlbFollow && G.mlbFollow.device !== followDevice()); }
|
||||
function gameIsFinal(){ return G.log.some(function(l){ return l.tag === 'Final'; }); }
|
||||
|
||||
// Something the scorer is in the middle of: don't change the game under them
|
||||
function followBlocked(){
|
||||
if(document.querySelector('.rp-overlay, .cf-overlay')) return true;
|
||||
var br = document.getElementById('brPicker');
|
||||
if(br && br.style.display !== 'none' && br.innerHTML) return true;
|
||||
return !!(outState && (outState.type || outState.fielder !== null));
|
||||
}
|
||||
|
||||
function startFollow(){
|
||||
if(gameIsFinal()){ showAlert({ title: 'This game is over', message: 'There\'s nothing left to follow.', tone: 'info' }); return; }
|
||||
G.mlbFollow = { device: followDevice(), since: Date.now() };
|
||||
_follow.stamp = null; _follow.error = '';
|
||||
saveToStorage();
|
||||
renderFollowPill();
|
||||
kbFlash('Following MLB', '#185FA5');
|
||||
return followTick();
|
||||
}
|
||||
|
||||
function stopFollow(msg){
|
||||
G.mlbFollow = null;
|
||||
clearTimeout(_follow.timer); _follow.timer = null;
|
||||
saveToStorage();
|
||||
renderFollowPill();
|
||||
if(msg) kbFlash(msg, '#BA7517');
|
||||
}
|
||||
|
||||
function followSchedule(){
|
||||
clearTimeout(_follow.timer); _follow.timer = null;
|
||||
if(followIsMine()) _follow.timer = setTimeout(followTick, FOLLOW_MS);
|
||||
}
|
||||
|
||||
// One check. Returns a promise (resolved when the check is done) for callers and tests.
|
||||
function followTick(){
|
||||
clearTimeout(_follow.timer); _follow.timer = null;
|
||||
if(!followIsMine()){ renderFollowPill(); return Promise.resolve(); }
|
||||
if(document.visibilityState === 'hidden' || _follow.busy) return Promise.resolve(); // resumes when shown
|
||||
if(followBlocked()){ followSchedule(); return Promise.resolve(); }
|
||||
_follow.busy = true;
|
||||
return mlbGamePk().then(function(pk){
|
||||
if(pk !== _follow.pk){ _follow.pk = pk; _follow.stamp = null; }
|
||||
return mlbFetchJSON(MLB_FEED + pk + '/feed/live/timestamps').then(function(ts){
|
||||
var stamp = Array.isArray(ts) && ts.length ? ts[ts.length - 1] : null;
|
||||
if(stamp && stamp === _follow.stamp) return null; // nothing new at MLB
|
||||
return mlbFetchJSON(MLB_FEED + pk + '/feed/live').then(function(feed){ return { feed: feed, stamp: stamp }; });
|
||||
});
|
||||
}).then(function(r){
|
||||
_follow.busy = false; _follow.error = ''; _follow.checkedAt = Date.now();
|
||||
if(r && r.feed && r.feed.liveData && followApply(r.feed)) _follow.stamp = r.stamp;
|
||||
renderFollowPill();
|
||||
followSchedule();
|
||||
}, function(err){
|
||||
_follow.busy = false;
|
||||
_follow.error = (err && err.message) || 'Couldn\'t reach MLB.';
|
||||
renderFollowPill();
|
||||
followSchedule();
|
||||
});
|
||||
}
|
||||
|
||||
// Bring the scorecard up to MLB. Returns false if it had to wait (try the same data again).
|
||||
function followApply(feed){
|
||||
if(!followIsMine()) return true;
|
||||
if(followBlocked()) return false;
|
||||
_mlb = { feed: feed, fetchedAt: Date.now() }; // Check vs MLB shows the same data
|
||||
var changed = false, n = mlbCatchUpCount(feed);
|
||||
if(n > 0){
|
||||
saveState();
|
||||
mlbApplyCatchUp(feed);
|
||||
addLog('Following MLB: ' + n + ' plate appearance' + (n === 1 ? '' : 's') + ' added', 'MLB', 't-info');
|
||||
changed = true;
|
||||
} else {
|
||||
var c = mlbCurrentAtBat(feed);
|
||||
if(c && followCountAhead(c)){ mlbApplyCount(c); changed = true; }
|
||||
}
|
||||
if(mlbMarkFinal(feed)) changed = true;
|
||||
if(changed){ renderAll(); saveToStorage(); renderMlbCheck(); }
|
||||
if(gameIsFinal()) stopFollow('Final — stopped following MLB');
|
||||
return true;
|
||||
}
|
||||
|
||||
// MLB's count is further along than the scorecard's (balls + strikes, then fouls)
|
||||
function followCountAhead(c){
|
||||
var mine = G.balls + G.strikes, theirs = c.balls + c.strikes;
|
||||
return theirs > mine || (theirs === mine && c.fouls > G.fouls);
|
||||
}
|
||||
|
||||
// ── Header pill: shows following (and from where); tap to stop or to take over ──
|
||||
function renderFollowPill(){
|
||||
var el = document.getElementById('followPill');
|
||||
if(!el) return;
|
||||
if(!G.mlbFollow || gameIsFinal()){ el.hidden = true; return; }
|
||||
el.hidden = false;
|
||||
if(followIsElsewhere()){
|
||||
el.textContent = '📡 Following on ' + G.mlbFollow.device;
|
||||
el.className = 'sync-pill';
|
||||
el.title = 'Another device is keeping this game caught up with MLB. Tap to follow here instead.';
|
||||
} else if(_follow.error){
|
||||
el.textContent = '📡 MLB: retrying';
|
||||
el.className = 'sync-pill sync-warn';
|
||||
el.title = _follow.error;
|
||||
} else {
|
||||
el.textContent = '📡 Following MLB';
|
||||
el.className = 'sync-pill sync-ok';
|
||||
el.title = _follow.checkedAt ? 'Checked ' + new Date(_follow.checkedAt).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit', second: '2-digit' }) + ' · tap to stop' : 'Tap to stop';
|
||||
}
|
||||
}
|
||||
|
||||
function followPillTap(){
|
||||
if(followIsElsewhere()){
|
||||
showConfirm({ title: 'Follow MLB on this device?', message: G.mlbFollow.device + ' is following this game now. Follow it here instead?', confirmLabel: 'Follow here', cancelLabel: 'Not now', tone: 'info' })
|
||||
.then(function(ok){ if(ok) startFollow(); });
|
||||
} else {
|
||||
showConfirm({ title: 'Stop following MLB?', message: 'The scorecard stops updating from MLB. You can start again from ☰ Menu or Check vs MLB.', confirmLabel: 'Stop', cancelLabel: 'Keep following', tone: 'info' })
|
||||
.then(function(ok){ if(ok) stopFollow(); });
|
||||
}
|
||||
}
|
||||
|
||||
// Menu item: start, or stop
|
||||
function toggleFollow(){
|
||||
if(followIsMine()) followPillTap();
|
||||
else if(followIsElsewhere()) followPillTap();
|
||||
else startFollow();
|
||||
}
|
||||
|
||||
// ── Hooks ──
|
||||
// Undo while following would be redone at the next check; pause following so it sticks
|
||||
var _followOrigUndo = undoAction;
|
||||
undoAction = function(){
|
||||
var was = followIsMine();
|
||||
_followOrigUndo();
|
||||
if(was){
|
||||
G.mlbFollow = null;
|
||||
stopFollow('Stopped following MLB so your Undo sticks');
|
||||
} else {
|
||||
renderFollowPill();
|
||||
}
|
||||
};
|
||||
|
||||
// A different game loaded (My Games, another device's update): show its state,
|
||||
// and keep checking if this device is the one following it
|
||||
var _followOrigRenderAll = renderAll;
|
||||
renderAll = function(){
|
||||
_followOrigRenderAll();
|
||||
renderFollowPill();
|
||||
if(followIsMine() && !_follow.timer && !_follow.busy && !gameIsFinal()) followSchedule();
|
||||
};
|
||||
|
||||
function followInit(){
|
||||
document.addEventListener('visibilitychange', function(){
|
||||
if(document.visibilityState === 'visible' && followIsMine()) followTick();
|
||||
});
|
||||
window.addEventListener('online', function(){ if(followIsMine()) followTick(); });
|
||||
renderFollowPill();
|
||||
if(followIsMine() && !gameIsFinal()) setTimeout(followTick, 0); // resume after a reload
|
||||
}
|
||||
@@ -1,559 +0,0 @@
|
||||
// The game model: state shape and schema migrations, undo, plate-appearance records, run charging, pitch and play-log basics.
|
||||
// Loaded as a plain script; files share one global scope (see index.html for the order).
|
||||
|
||||
function mkHits(){ return {s:0,d:0,t:0,hr:0,kl:0,ks:0,fo:0,go:0,sb:0,cs:0,err:0,roe:0,hbp:0,bb:0,sf:0,sac:0,fc:0,ibb:0,ci:0,wp:0,r:0,rbi:0}; }
|
||||
|
||||
function mkSlot(){ return {name:'',pos:'—',hits:mkHits(),subs:[],pending:false}; }
|
||||
|
||||
function mkPitcher(){ return {name:'',pitches:0,balls:0,outs:0,h:0,r:0,er:0,bb:0,k:0,hr:0,active:true}; }
|
||||
|
||||
function mkNotes(){ return {date:'',firstPitch:'',venue:'',attendance:'',weather:'',temp:'',windSpeed:'',windDir:'',umpHP:'',ump1B:'',ump2B:'',ump3B:'',gameType:'',seriesGame:'',attended:false,text:''}; }
|
||||
|
||||
function mkGame(){
|
||||
return {
|
||||
inning:1, half:'top', outs:0, balls:0, strikes:0, fouls:0,
|
||||
bases:[null,null,null],
|
||||
totalInnings:9,
|
||||
scores:{home:Array(9).fill(null), away:Array(9).fill(null)},
|
||||
rhe:{home:[0,0,0], away:[0,0,0]},
|
||||
homeBatter:0, awayBatter:0,
|
||||
lineup:{home:Array(9).fill(null).map(mkSlot), away:Array(9).fill(null).map(mkSlot)},
|
||||
pitchers:{home:[mkPitcher()], away:[mkPitcher()]},
|
||||
log:[],
|
||||
batterLog:{home:{}, away:{}},
|
||||
pas:[], nextPaId:1,
|
||||
mlbGamePk:null, mlbGameTeams:'', // MLB's id for this game (Check vs MLB)
|
||||
mlbKeep:{}, // MLB differences the scorer chose to keep
|
||||
mlbFollow:null, // { device, since } while a device is following MLB live
|
||||
notes:mkNotes(),
|
||||
abs:{home:{challenged:0,overturned:0}, away:{challenged:0,overturned:0}}
|
||||
};
|
||||
}
|
||||
|
||||
// ── Schema migrations ──
|
||||
// Given a (possibly old-shape) G loaded from JSON or localStorage, fill in any
|
||||
// missing fields so downstream code can assume the current shape. Mutates and
|
||||
// returns g. This is the SINGLE source of truth for backward compatibility —
|
||||
// loadFromStorage, gmLoadFromSlot, and _applyImportedPayload all delegate here.
|
||||
//
|
||||
// When you add a new field to mkGame/mkHits/mkNotes/mkPitcher, add the matching
|
||||
// default here too so games saved before the change still load correctly.
|
||||
function migrateGame(g){
|
||||
if(!g) return g;
|
||||
|
||||
// v1 → v2: batterLog added
|
||||
if(!g.batterLog) g.batterLog = { home:{}, away:{} };
|
||||
if(!g.batterLog.home) g.batterLog.home = {};
|
||||
if(!g.batterLog.away) g.batterLog.away = {};
|
||||
|
||||
// v2 → v3: game notes added
|
||||
if(!g.notes) g.notes = mkNotes();
|
||||
|
||||
// v3 → v4: ABS challenge tracking added
|
||||
if(!g.abs) g.abs = { home:{challenged:0,overturned:0}, away:{challenged:0,overturned:0} };
|
||||
if(!g.abs.home) g.abs.home = {challenged:0,overturned:0};
|
||||
if(!g.abs.away) g.abs.away = {challenged:0,overturned:0};
|
||||
|
||||
// Backfill any newly-added hit keys on every lineup slot and sub.
|
||||
// Subs from old saves may have no hits object at all (pre-per-sub stats).
|
||||
var defaultHitKeys = Object.keys(mkHits());
|
||||
if(g.lineup){
|
||||
['home','away'].forEach(function(side){
|
||||
if(!g.lineup[side]) return;
|
||||
g.lineup[side].forEach(function(sl){
|
||||
if(!sl) return;
|
||||
if(!sl.hits) sl.hits = mkHits();
|
||||
defaultHitKeys.forEach(function(k){
|
||||
if(sl.hits[k] === undefined) sl.hits[k] = 0;
|
||||
});
|
||||
if(sl.subs){
|
||||
sl.subs.forEach(function(sub){
|
||||
if(!sub) return;
|
||||
if(!sub.hits) sub.hits = mkHits();
|
||||
defaultHitKeys.forEach(function(k){
|
||||
if(sub.hits[k] === undefined) sub.hits[k] = 0;
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// v4 → v5: fuller pitching lines. Runs from older saves are assumed earned.
|
||||
var defaultPitcherKeys = Object.keys(mkPitcher());
|
||||
if(g.pitchers){
|
||||
['home','away'].forEach(function(side){
|
||||
(g.pitchers[side] || []).forEach(function(p){
|
||||
if(!p) return;
|
||||
if(p.er === undefined) p.er = p.r || 0;
|
||||
defaultPitcherKeys.forEach(function(k){
|
||||
if(p[k] === undefined) p[k] = 0;
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// v4 → v5: per-PA records for the scorecard grid. Rebuild what we can from
|
||||
// batterLog (result + inning only — base paths and out numbers weren't kept).
|
||||
if(!g.pas){
|
||||
g.pas = [];
|
||||
['away','home'].forEach(function(side){
|
||||
var log = (g.batterLog && g.batterLog[side]) || {};
|
||||
Object.keys(log).forEach(function(key){
|
||||
var half = key[0] === 'T' ? 'top' : 'bot';
|
||||
var inn = parseInt(key.slice(1), 10);
|
||||
(log[key] || []).forEach(function(entry){
|
||||
var cut = entry.lastIndexOf(' — ');
|
||||
if(cut < 0) return;
|
||||
var slot = _slotForName(g, side, entry.slice(0, cut));
|
||||
if(slot < 0) return;
|
||||
var res = entry.slice(cut + 3);
|
||||
g.pas.push({side:side, slot:slot, inn:inn, half:half, res:res,
|
||||
reached:paReachFor(res), out:0, pIdx:0, unearned:res[0] === 'E'});
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// v5 → v6: Check vs MLB
|
||||
if(!g.mlbKeep) g.mlbKeep = {};
|
||||
if(g.mlbFollow === undefined) g.mlbFollow = null;
|
||||
|
||||
// v6 → v7: plate appearances get ids so play-log lines can point at them
|
||||
if(!g.nextPaId) g.nextPaId = 1;
|
||||
(g.pas || []).forEach(function(pa){ if(!pa.id) pa.id = g.nextPaId++; });
|
||||
|
||||
// Very early saves stored bases as booleans; now we store runner names
|
||||
// (string) or null. Normalize either way.
|
||||
if(g.bases){
|
||||
for(var bi = 0; bi < 3; bi++){
|
||||
if(g.bases[bi] === true) g.bases[bi] = '?';
|
||||
else if(g.bases[bi] === false) g.bases[bi] = null;
|
||||
}
|
||||
}
|
||||
|
||||
return g;
|
||||
}
|
||||
|
||||
// Lineup slot for a player name (starter or any sub) in game g, or -1.
|
||||
function _slotForName(g, side, name){
|
||||
var lu = g.lineup && g.lineup[side];
|
||||
if(!lu || !name) return -1;
|
||||
for(var i = 0; i < lu.length; i++){
|
||||
if(!lu[i]) continue;
|
||||
if((lu[i].name || 'Batter ' + (i + 1)) === name) return i;
|
||||
for(var s = 0; s < (lu[i].subs || []).length; s++){
|
||||
if((lu[i].subs[s].name || 'Sub') === name) return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function esc(s){ return (s||'').replace(/&/g,'&').replace(/"/g,'"').replace(/'/g,''').replace(/</g,'<'); }
|
||||
|
||||
function posOpts(sel){ return POSITIONS.map(function(p){ return '<option value="'+p+'"'+(p===sel?' selected':'')+'>'+p+'</option>'; }).join(''); }
|
||||
|
||||
// Returns the hits object for whoever is currently active in a lineup slot
|
||||
// (the last sub if subs exist, otherwise the starter)
|
||||
function activeHits(side, idx){
|
||||
var sl = G.lineup[side][idx];
|
||||
if(sl.subs.length > 0){
|
||||
return sl.subs[sl.subs.length - 1].hits;
|
||||
}
|
||||
return sl.hits;
|
||||
}
|
||||
|
||||
// Find the lineup slot index for a runner by name.
|
||||
// Returns the slot index (0-8) or -1 if not found.
|
||||
function findRunnerSlot(side, runnerName){
|
||||
if(!runnerName || runnerName === '?' || runnerName === true) return -1;
|
||||
for(var i = 0; i < 9; i++){
|
||||
if(curName(side, i) === runnerName) return i;
|
||||
}
|
||||
// Fallback: check starters and subs by raw name (handles edge cases)
|
||||
for(var i = 0; i < 9; i++){
|
||||
var sl = G.lineup[side][i];
|
||||
if(sl.name === runnerName) return i;
|
||||
for(var s = 0; s < sl.subs.length; s++){
|
||||
if(sl.subs[s].name === runnerName) return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Credit a run scored to the runner who crossed home plate, and charge it to
|
||||
// the pitcher who put that runner on base (inherited runners stay with the
|
||||
// pitcher who allowed them).
|
||||
// runnerName: the name string from the base, or null/unknown.
|
||||
// unearned: true when the run scored because of an error or passed ball.
|
||||
function creditRun(side, runnerName, unearned){
|
||||
var slot = findRunnerSlot(side, runnerName);
|
||||
if(slot >= 0) activeHits(side, slot).r++;
|
||||
var pa = paForRunner(side, runnerName);
|
||||
if(pa) pa.reached = 4;
|
||||
chargeRun(pa, unearned);
|
||||
}
|
||||
|
||||
// Charge one run to the responsible pitcher. pa is the scoring runner's plate
|
||||
// appearance (null when unknown → the current pitcher takes it).
|
||||
function chargeRun(pa, unearned){
|
||||
var fSide = fielding();
|
||||
var staff = G.pitchers[fSide];
|
||||
var pIdx = pa && pa.pIdx < staff.length ? pa.pIdx : activePIdx(fSide);
|
||||
var p = staff[pIdx];
|
||||
p.r++;
|
||||
if(!unearned && !(pa && pa.unearned) && !inningOverWithoutErrors(pIdx)) p.er++;
|
||||
renderPitchers(fSide);
|
||||
}
|
||||
|
||||
// Earned-run reconstruction (rule 9.16): count each batter who reached on an
|
||||
// error as the out that should have been made. If those plus the real outs
|
||||
// already reach three, the inning should have been over and the run is
|
||||
// unearned. A reliever gets no benefit from misplays before he came in, so only
|
||||
// errors while this pitcher or a later one was pitching count for him.
|
||||
function inningOverWithoutErrors(pIdx){
|
||||
var bSide = batting(), missed = 0;
|
||||
G.pas.forEach(function(q){
|
||||
if(q.side === bSide && q.inn === G.inning && q.half === G.half && /^E\d?$/.test(q.res) && (q.pIdx || 0) >= pIdx) missed++;
|
||||
});
|
||||
return G.outs + missed >= 3;
|
||||
}
|
||||
|
||||
function newPaId(){
|
||||
if(!G.nextPaId) G.nextPaId = 1;
|
||||
return G.nextPaId++;
|
||||
}
|
||||
|
||||
// ── Plate appearances (scorecard grid) ──
|
||||
// One record per PA in G.pas:
|
||||
// {side, slot, inn, half, res, reached, out, pIdx, unearned, outOnBases}
|
||||
// reached: 0 = retired at the plate, 1-3 = furthest base, 4 = scored.
|
||||
// out: which out of the half-inning (1-3) this player made, 0 if none.
|
||||
var PA_OUT_RE = /^(K|ꓘ|F\d|G\d|SF|SAC|Out)/;
|
||||
|
||||
function paIsOut(res){ return PA_OUT_RE.test(res); }
|
||||
|
||||
function paIsHit(res){ return /^(1B|2B|3B|HR)/.test(res); }
|
||||
|
||||
// Plate appearances that count as at-bats (everything but walks, HBP, sacrifices, interference)
|
||||
function paIsAB(res){ return !/^(BB|IBB|HBP|SF|SAC|CI)/.test(res); }
|
||||
|
||||
// Hits / at-bats with runners in scoring position; inn optional. PAs recorded
|
||||
// before RISP was tracked (risp undefined) are left out.
|
||||
function rispLine(side, inn){
|
||||
var h = 0, ab = 0;
|
||||
G.pas.forEach(function(pa){
|
||||
if(pa.side !== side || !pa.risp || (inn && pa.inn !== inn) || !paIsAB(pa.res)) return;
|
||||
ab++;
|
||||
if(paIsHit(pa.res)) h++;
|
||||
});
|
||||
return { h: h, ab: ab };
|
||||
}
|
||||
|
||||
// Runners left on base in the half-innings this team has finished batting
|
||||
function teamLOB(side){
|
||||
var half = side === 'away' ? 'top' : 'bot', total = 0;
|
||||
var final = G.log.some(function(l){ return l.tag === 'Final'; });
|
||||
G.pas.forEach(function(pa){
|
||||
if(pa.side !== side) return;
|
||||
var done = final || pa.inn < G.inning || (pa.inn === G.inning && half === 'top' && G.half === 'bot');
|
||||
if(done && pa.reached >= 1 && pa.reached <= 3 && !pa.out) total++;
|
||||
});
|
||||
return total;
|
||||
}
|
||||
|
||||
function paReachFor(res){
|
||||
if(paIsOut(res)) return 0;
|
||||
if(/^HR/.test(res)) return 4;
|
||||
if(/^3B/.test(res)) return 3;
|
||||
if(/^2B/.test(res)) return 2;
|
||||
return 1; // 1B, BB, IBB, HBP, E#, FC
|
||||
}
|
||||
|
||||
// The plate appearance a runner is currently on base from (this half-inning).
|
||||
function paForRunner(side, runnerName){
|
||||
var slot = findRunnerSlot(side, runnerName);
|
||||
if(slot < 0) return null;
|
||||
for(var i = G.pas.length - 1; i >= 0; i--){
|
||||
var pa = G.pas[i];
|
||||
if(pa.inn !== G.inning || pa.half !== G.half) break;
|
||||
if(pa.side === side && pa.slot === slot){
|
||||
return (pa.reached >= 1 && pa.reached <= 3 && !pa.out) ? pa : null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Mark a baserunner as retired. Call BEFORE the matching addOut() so the out
|
||||
// number is right and the half-inning hasn't flipped yet.
|
||||
function paRunnerOut(side, runnerName, outNum){
|
||||
var pa = paForRunner(side, runnerName);
|
||||
if(!pa) return;
|
||||
pa.out = Math.min(3, outNum || G.outs + 1);
|
||||
pa.outOnBases = true;
|
||||
}
|
||||
|
||||
// Bases carry runner names; push each runner's PA out to the base they're on.
|
||||
// Called from renderBases, which runs after every base change.
|
||||
function syncPaBases(){
|
||||
var side = batting();
|
||||
for(var i = 0; i < 3; i++){
|
||||
var pa = paForRunner(side, G.bases[i]);
|
||||
if(pa && pa.reached < i + 1) pa.reached = i + 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Credit RBI(s) to the current batter.
|
||||
function creditRBI(side, count){
|
||||
if(!count || count <= 0) return;
|
||||
var idx = abIdx(side);
|
||||
activeHits(side, idx).rbi += count;
|
||||
}
|
||||
|
||||
var G = mkGame();
|
||||
|
||||
// ── Undo history ──
|
||||
var HISTORY = [];
|
||||
|
||||
var MAX_HISTORY = 30;
|
||||
|
||||
// Helper: is a base occupied? Works with both old boolean and new name-string format
|
||||
function baseOcc(i){ return !!G.bases[i]; }
|
||||
|
||||
// Helper: short name for runner labels (first initial + last name)
|
||||
function shortName(n){
|
||||
if(!n) return '?';
|
||||
var parts = n.trim().split(/\s+/);
|
||||
if(parts.length === 1) return parts[0];
|
||||
// Keep a suffix with the surname: "Luis García Jr." → "L. García Jr."
|
||||
var suffix = '';
|
||||
if(parts.length > 2 && /^(jr|sr|ii|iii|iv|v)\.?$/i.test(parts[parts.length - 1])) suffix = ' ' + parts.pop();
|
||||
return parts[0][0] + '. ' + parts[parts.length - 1] + suffix;
|
||||
}
|
||||
|
||||
// Snapshots leave out the play log and keep its length instead: entries are
|
||||
// only ever added at the front, so the older part of the log never moves and
|
||||
// the snapshot's log is the last `logLen` entries of the log at undo time.
|
||||
// (A full game's log copied into 30 snapshots would be several MB.)
|
||||
function saveState(){
|
||||
var g = Object.assign({}, G);
|
||||
delete g.log;
|
||||
g.logLen = G.log.length;
|
||||
HISTORY.push(JSON.stringify({
|
||||
G: g,
|
||||
outState: outState
|
||||
}));
|
||||
if(HISTORY.length > MAX_HISTORY) HISTORY.shift();
|
||||
var btn = document.getElementById('undoBtn');
|
||||
if(btn) btn.disabled = false;
|
||||
saveToStorage();
|
||||
}
|
||||
|
||||
// Rebuild a full game from an undo snapshot (see saveState). Older snapshots
|
||||
// carry their own full log; snapshots from storage may predate the schema.
|
||||
function snapshotG(sg){
|
||||
if(!sg.log){
|
||||
var n = Math.min(sg.logLen || 0, G.log.length);
|
||||
sg.log = G.log.slice(G.log.length - n);
|
||||
}
|
||||
delete sg.logLen;
|
||||
return migrateGame(sg);
|
||||
}
|
||||
|
||||
function undoAction(){
|
||||
if(!HISTORY.length) return;
|
||||
closeRunnerPicker(); // dismiss picker if open mid-hit
|
||||
var snapshot = JSON.parse(HISTORY.pop());
|
||||
G = snapshotG(snapshot.G);
|
||||
// Restore outState if it was saved, otherwise reset it
|
||||
if(snapshot.outState){
|
||||
Object.assign(outState, snapshot.outState);
|
||||
if(outState.sacType === undefined) outState.sacType = null;
|
||||
} else {
|
||||
resetOutState();
|
||||
}
|
||||
var btn = document.getElementById('undoBtn');
|
||||
if(btn) btn.disabled = HISTORY.length === 0;
|
||||
renderAll();
|
||||
saveToStorage();
|
||||
}
|
||||
|
||||
// ── Current at-bat summary bar ──
|
||||
function renderAtBatBar(){
|
||||
var el = document.getElementById('atbatBar');
|
||||
if(!el) return;
|
||||
|
||||
var bSide = batting();
|
||||
var fSide = fielding();
|
||||
var bIdx = abIdx(bSide);
|
||||
var bName = curName(bSide, bIdx);
|
||||
var bSlot = G.lineup[bSide][bIdx];
|
||||
var bPos = bSlot.subs.length > 0 ? bSlot.subs[bSlot.subs.length - 1].pos : bSlot.pos;
|
||||
var bTeamName = team(bSide);
|
||||
var bLogo = TEAM_LOGOS[bTeamName] || '';
|
||||
var bHits = activeHits(bSide, bIdx);
|
||||
var bBadges = badges(bHits);
|
||||
|
||||
// Pitcher info
|
||||
var pIdx = activePIdx(fSide);
|
||||
var pitcher = G.pitchers[fSide][pIdx];
|
||||
var pName = pitcher.name || 'Pitcher ' + (pIdx + 1);
|
||||
var pTeamName = team(fSide);
|
||||
var pLogo = TEAM_LOGOS[pTeamName] || '';
|
||||
|
||||
// On-deck (next batter) and in-the-hole (batter after on-deck)
|
||||
var onDeckIdx = (bIdx + 1) % 9;
|
||||
var onDeckName = curName(bSide, onDeckIdx);
|
||||
var inHoleIdx = (bIdx + 2) % 9;
|
||||
var inHoleName = curName(bSide, inHoleIdx);
|
||||
|
||||
// Count display
|
||||
var countHtml = '<span class="atbat-count-b">' + G.balls + '</span>'
|
||||
+ '-'
|
||||
+ '<span class="atbat-count-s">' + G.strikes + '</span>';
|
||||
|
||||
var html = '';
|
||||
|
||||
// Batter section
|
||||
html += '<div class="atbat-batter">';
|
||||
if(bLogo) html += '<img class="atbat-logo" src="' + bLogo + '" alt="" />';
|
||||
html += '<span class="atbat-name">' + esc(bName) + '</span>';
|
||||
if(bPos && bPos !== '—') html += '<span class="atbat-pos">' + esc(bPos) + '</span>';
|
||||
html += '<span class="atbat-detail">#' + (bIdx + 1) + '</span>';
|
||||
html += '</div>';
|
||||
|
||||
// Badges
|
||||
if(bBadges) html += '<div class="atbat-badges">' + bBadges + '</div>';
|
||||
|
||||
// Count
|
||||
html += '<span class="atbat-count">' + countHtml + '</span>';
|
||||
|
||||
// Separator
|
||||
html += '<div class="atbat-sep"></div>';
|
||||
|
||||
// Pitcher section
|
||||
html += '<div class="atbat-vs">';
|
||||
html += '<span class="atbat-vs-label">vs</span>';
|
||||
if(pLogo) html += '<img class="atbat-logo" src="' + pLogo + '" alt="" />';
|
||||
html += '<span class="atbat-pitcher">' + esc(shortName(pName)) + '</span>';
|
||||
html += '<span class="atbat-pc">' + pitcher.pitches + 'P</span>';
|
||||
html += '</div>';
|
||||
|
||||
// On deck + in the hole
|
||||
html += '<span class="atbat-ondeck">On deck: ' + esc(shortName(onDeckName)) + '</span>';
|
||||
html += '<span class="atbat-inhole">In hole: ' + esc(shortName(inHoleName)) + '</span>';
|
||||
|
||||
// The batter in your other scorecards, and career vs this pitcher
|
||||
if(bSlot.name || bSlot.subs.length) html += abExtrasHtml(bSide, bName, pitcher.name);
|
||||
|
||||
el.innerHTML = html;
|
||||
}
|
||||
|
||||
function team(s){
|
||||
var v = s === 'home'
|
||||
? document.getElementById('teamHome').value
|
||||
: document.getElementById('teamAway').value;
|
||||
return (!v || v === '— Select Team —')
|
||||
? (s === 'home' ? 'Home' : 'Away')
|
||||
: v;
|
||||
}
|
||||
|
||||
function fielding(){ return G.half==='top'?'home':'away'; }
|
||||
|
||||
function batting(){ return G.half==='top'?'away':'home'; }
|
||||
|
||||
function abIdx(side){ return side==='home'?G.homeBatter:G.awayBatter; }
|
||||
|
||||
function curName(side, i){
|
||||
var sl = G.lineup[side][i];
|
||||
if(sl.subs.length > 0){
|
||||
return sl.subs[sl.subs.length - 1].name || 'Sub';
|
||||
}
|
||||
return sl.name || 'Batter ' + (i + 1);
|
||||
}
|
||||
|
||||
function activePIdx(side){
|
||||
var p = G.pitchers[side];
|
||||
for(var i = 0; i < p.length; i++){
|
||||
if(p[i].active) return i;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
function addPitch(side){
|
||||
var idx = activePIdx(side);
|
||||
var pp = G.pitchers[side][idx];
|
||||
var prev = pp.pitches;
|
||||
pp.pitches++;
|
||||
var n = pp.pitches;
|
||||
var el = document.getElementById(side + 'pc' + idx);
|
||||
if(el){
|
||||
el.textContent = n;
|
||||
el.className = 'pc' + pitchCountClass(n);
|
||||
}
|
||||
schedulePitchLines();
|
||||
// Cross-threshold heads-up toast. Only fires on the upward crossing edge so
|
||||
// undo + redo or manual adjustment doesn't nag. Uses the pitcher's name if
|
||||
// set, otherwise a generic label.
|
||||
if(prev < 75 && n >= 75 && n < 100){
|
||||
kbFlash((pp.name || 'Pitcher') + ' — 75 pitches', '#BA7517');
|
||||
} else if(prev < 100 && n >= 100){
|
||||
kbFlash((pp.name || 'Pitcher') + ' — 100 pitches', '#E24B4A');
|
||||
}
|
||||
}
|
||||
|
||||
// Returns a CSS class suffix (empty, ' warn', or ' over') based on pitch count.
|
||||
// Starters typically land ~85-100 pitches; crossing 75 is a useful heads-up
|
||||
// and 100+ is the standard "watch out" threshold.
|
||||
function pitchCountClass(n){
|
||||
if(n >= 100) return ' over';
|
||||
if(n >= 75) return ' warn';
|
||||
return '';
|
||||
}
|
||||
|
||||
// Track balls per pitcher; strikes = pitches − balls (balls in play count as strikes).
|
||||
function addPitcherBall(side, d){
|
||||
var p = G.pitchers[side][activePIdx(side)];
|
||||
p.balls = Math.max(0, (p.balls || 0) + d);
|
||||
schedulePitchLines();
|
||||
}
|
||||
|
||||
// Refresh just the stat lines (not the whole panel) — this runs on every pitch.
|
||||
var _pitchLinesScheduled = false;
|
||||
|
||||
function schedulePitchLines(){
|
||||
if(_pitchLinesScheduled) return;
|
||||
_pitchLinesScheduled = true;
|
||||
var schedule = window.requestAnimationFrame || function(cb){ return setTimeout(cb, 0); };
|
||||
schedule(function(){
|
||||
_pitchLinesScheduled = false;
|
||||
['home','away'].forEach(function(side){
|
||||
G.pitchers[side].forEach(function(p, i){
|
||||
var el = document.getElementById(side + 'pl' + i);
|
||||
if(el) el.innerHTML = pitchingLine(p);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function addPitcherStat(side, stat){
|
||||
var idx = activePIdx(side);
|
||||
G.pitchers[side][idx][stat]++;
|
||||
renderPitchers(side);
|
||||
}
|
||||
|
||||
function addLog(text, tag, cls){
|
||||
var inn = (G.half === 'top' ? 'T' : 'B') + G.inning;
|
||||
// Categorize for filtering
|
||||
var cat = 'info';
|
||||
if(cls === 't-hit' || cls === 't-hr' || cls === 't-hbp' || cls === 't-sb') cat = 'hits';
|
||||
else if(cls === 't-fo' || cls === 't-go' || cls === 't-out' || cls === 't-kl' || cls === 't-ks' || cls === 't-fc' || cls === 't-cs') cat = 'outs';
|
||||
else if(cls === 't-run') cat = 'runs';
|
||||
else if(cls === 't-ball' || cls === 't-k' || cls === 't-foul' || cls === 't-wp' || cls === 't-pb' || cls === 't-ibb') cat = 'pitches';
|
||||
else if(cls === 't-abs') cat = 'abs';
|
||||
// No cap: undo snapshots store only the log's length (see saveState), so a
|
||||
// full game's log stays cheap. New entries always go on the front.
|
||||
G.log.unshift({ text: inn + ' — ' + text, tag: tag, cls: cls, inn: inn, cat: cat });
|
||||
scheduleLogRender();
|
||||
haptic();
|
||||
}
|
||||
@@ -1,869 +0,0 @@
|
||||
// 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 = '<div class="empty-log">No plays logged yet</div>';
|
||||
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 = '<option value="">All innings</option>' + innKeys.map(function(k){
|
||||
return '<option value="'+k+'"'+(k===curVal?' selected':'')+'>'+k+'</option>';
|
||||
}).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 = '<div class="empty-log">No matching plays</div>';
|
||||
} else {
|
||||
el.innerHTML = filtered.map(function(f){
|
||||
var e = f.entry;
|
||||
var i = f.idx;
|
||||
|
||||
if(i === logEditIdx){
|
||||
// Inline edit mode
|
||||
return '<div class="log-row log-editing">'
|
||||
+ '<input class="log-edit-input" id="logEditInput" value="' + esc(e.text) + '" />'
|
||||
+ '<span class="ltag ' + e.cls + '">' + e.tag + '</span>'
|
||||
+ '<button class="log-edit-save" onclick="logEditSave()">Save</button>'
|
||||
+ (logPaIndex(e) >= 0 ? '<button class="log-edit-play" onclick="logEditPlay(' + i + ')" title="Change the result, bases or out on the scorecard (stats follow)">Edit play</button>' : '')
|
||||
+ '<button class="log-edit-del" onclick="logEditDelete(' + i + ')">Delete</button>'
|
||||
+ '<button class="log-edit-cancel" onclick="logEditCancel()">Cancel</button>'
|
||||
+ '</div>';
|
||||
}
|
||||
|
||||
return '<div class="log-row log-cat-' + e.cat + '">'
|
||||
+ '<span class="log-row-text">' + e.text + '</span>'
|
||||
+ '<div class="log-row-actions">'
|
||||
+ '<span class="ltag ' + e.cls + '">' + e.tag + '</span>'
|
||||
+ '<button class="log-edit-btn" onclick="logEditStart(' + i + ')" title="Edit entry">✎</button>'
|
||||
+ '</div>'
|
||||
+ '</div>';
|
||||
}).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 += '<span class="hbadge ' + it.cls + '">'
|
||||
+ (h[it.key] > 1 ? h[it.key] : '')
|
||||
+ it.label + '</span>';
|
||||
}
|
||||
});
|
||||
return b;
|
||||
}
|
||||
|
||||
function playerOpts(side, selectedName, includeBlank) {
|
||||
var roster = ROSTERS[side];
|
||||
var html = includeBlank ? '<option value="">— Select player —</option>' : '';
|
||||
roster.forEach(function(p){
|
||||
var label = (p.jersey ? '#'+p.jersey+' ' : '') + p.name + ' ('+p.pos+')';
|
||||
html += '<option value="'+esc(p.name)+'"'+(p.name===selectedName?' selected':'')+'>'+label+'</option>';
|
||||
});
|
||||
if(!roster.length) html += '<option value="">No roster loaded</option>';
|
||||
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+='<div class="lineup-slot">';
|
||||
html+='<div class="lineup-row'+(hasSubs?' dimmed':'')+'">';
|
||||
html+='<span class="bnum">'+(i+1)+'</span>';
|
||||
html+='<span class="ab-dot'+(isActive&&!hasSubs?'':' hidden')+'"></span>';
|
||||
html+='<select class="pos-sel" data-action="set-pos" data-side="'+side+'" data-idx="'+i+'"'+(hasSubs?' disabled':'')+'>'+posOpts(sl.pos)+'</select>';
|
||||
if(hasRoster && !hasSubs){
|
||||
html+='<select class="bname roster-sel" id="'+side+'_rs_'+i+'" data-action="select-player" data-side="'+side+'" data-idx="'+i+'">'
|
||||
+'<option value="">— Select player —</option>'
|
||||
+playerOpts(side, sl.name, false)
|
||||
+'</select>';
|
||||
} else if(isLoading && !hasSubs){
|
||||
html+='<input class="bname" value="'+esc(sl.name)+'" placeholder="Loading roster…" disabled />';
|
||||
} else {
|
||||
html+='<input class="bname" id="'+side+'_n_'+i+'" value="'+esc(sl.name)+'" placeholder="Player '+(i+1)+'"'+(hasSubs?' disabled':'')+' data-action="set-name" data-side="'+side+'" data-idx="'+i+'" />';
|
||||
}
|
||||
var hb=badges(sl.hits); if(hb) html+='<div class="hits">'+hb+'</div>';
|
||||
if(!hasSubs&&!sl.pending){ html+='<button class="set-btn" data-action="at-bat" data-side="'+side+'" data-idx="'+i+'">At bat</button><button class="sub-btn" data-action="start-sub" data-side="'+side+'" data-idx="'+i+'">Sub</button>'; }
|
||||
html+='</div>';
|
||||
for(var s=0;s<sl.subs.length;s++){
|
||||
var sub=sl.subs[s]; var isLast=(s===sl.subs.length-1); var inn=(sub.half==='top'?'T':'B')+sub.inning;
|
||||
html+='<div class="sub-row"><span class="sub-arrow">↳</span><span class="sub-inn">'+inn+'</span>';
|
||||
html+='<select class="sub-pos" data-action="set-sub-pos" data-side="'+side+'" data-idx="'+i+'" data-sub="'+s+'">'+posOpts(sub.pos)+'</select>';
|
||||
html+='<input class="sub-name-el" value="'+esc(sub.name)+'" data-action="set-sub-name" data-side="'+side+'" data-idx="'+i+'" data-sub="'+s+'" />';
|
||||
var subBadges = sub.hits ? badges(sub.hits) : '';
|
||||
if(isLast){ if(subBadges) html+='<div class="hits">'+subBadges+'</div>'; html+='<span class="ab-dot'+(isActive&&isLast?'':' hidden')+'" style="margin-left:2px"></span>'; if(!sl.pending){ html+='<button class="set-btn" data-action="at-bat" data-side="'+side+'" data-idx="'+i+'">At bat</button><button class="sub-btn" data-action="start-sub" data-side="'+side+'" data-idx="'+i+'">Sub</button>'; } }
|
||||
else { if(subBadges) html+='<div class="hits">'+subBadges+'</div>'; }
|
||||
html+='</div>';
|
||||
}
|
||||
if(sl.pending){
|
||||
html+='<div class="sub-form"><span class="sub-form-lbl">↳ Sub in:</span>';
|
||||
html+='<select class="sub-form-pos" id="'+side+'_sp_'+i+'">'+posOpts('—')+'</select>';
|
||||
if(hasRoster){
|
||||
html+='<select class="sub-form-inp" id="'+side+'_ss_'+i+'"><option value="">— Select player —</option>'+playerOpts(side,'',false)+'</select>';
|
||||
} else {
|
||||
html+='<input class="sub-form-inp" id="'+side+'_si_'+i+'" placeholder="New player name" />';
|
||||
}
|
||||
html+='<button class="sub-ok" data-action="confirm-sub" data-side="'+side+'" data-idx="'+i+'" data-subtype="ph" title="Pinch Hitter">PH</button>';
|
||||
html+='<button class="sub-ok" style="border-color:var(--teal);color:var(--teal)" data-action="confirm-sub" data-side="'+side+'" data-idx="'+i+'" data-subtype="pr" title="Pinch Runner">PR</button>';
|
||||
html+='<button class="sub-cancel" data-action="cancel-sub" data-side="'+side+'" data-idx="'+i+'">Cancel</button>';
|
||||
html+='</div>';
|
||||
}
|
||||
html+='</div>';
|
||||
}
|
||||
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 = '<thead><tr><th></th>';
|
||||
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 ? '<span style="display:block;width:4px;height:4px;border-radius:50%;background:var(--blue);margin:2px auto 0;"></span>' : '';
|
||||
hdr += '<th id="h' + i + '" class="inning-cell' + (G.inning === i ? ' active-inn' : '') + '" onclick="setInning(' + i + ');showInningPopover(' + (i - 1) + ',event)">' + i + dotHint + '</th>';
|
||||
}
|
||||
hdr += '<th class="add-inn-cell"><button class="add-inn" onclick="addExtraInning()" title="Add an extra inning" aria-label="Add an extra inning">+</button></th>';
|
||||
hdr += '<th>R</th><th>H</th><th>E</th></tr></thead>';
|
||||
// Body rows
|
||||
var body = '<tbody>';
|
||||
['away','home'].forEach(function(side){
|
||||
var tName = team(side);
|
||||
var logo = TEAM_LOGOS[tName] ? '<img src="' + TEAM_LOGOS[tName] + '" style="width:20px;height:20px;object-fit:contain;flex:none;" alt="" />' : '';
|
||||
var c = '<tr id="row-' + side + '"><td class="team-label"><span class="team-cell">' + logo
|
||||
+ (sels[side] ? '<span class="team-sel-slot" data-side="' + side + '"></span>' : esc(tName)) + '</span></td>';
|
||||
for(var i = 0; i < n; i++){
|
||||
var v = G.scores[side][i];
|
||||
var a = (G.inning - 1) === i ? 'active-inn' : '';
|
||||
c += '<td class="inning-cell ' + a + '" onclick="editScore(\'' + side + '\',' + i + ',event)">' + (v === null ? '' : v) + '</td>';
|
||||
}
|
||||
c += '<td class="add-inn-cell"></td>';
|
||||
c += '<td class="total-cell">' + G.rhe[side][0] + '</td>';
|
||||
c += '<td class="total-cell">' + G.rhe[side][1] + '</td>';
|
||||
c += '<td class="total-cell">' + G.rhe[side][2] + '</td>';
|
||||
c += '</tr>';
|
||||
body += c;
|
||||
});
|
||||
body += '</tbody>';
|
||||
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 + ': <span class="abs-tally-won">' + won + '✓</span> / <span class="abs-tally-lost">' + lost + '✕</span>');
|
||||
});
|
||||
|
||||
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 '<button type="button" class="' + (_fieldView === o[0] ? 'on' : '') + '" aria-pressed="' + (_fieldView === o[0]) + '" onclick="setFieldView(\'' + o[0] + '\')">' + o[1] + '</button>';
|
||||
}).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 = '<svg viewBox="' + VB.join(' ') + '" role="group" aria-label="' + (F ? 'Field' : 'Infield') + '">';
|
||||
if(F){
|
||||
var fair = [[0, 0]].concat(F.w);
|
||||
s += '<defs><clipPath id="ifFair"><polygon points="' + pts(fair) + '"/></clipPath></defs>';
|
||||
s += '<rect x="' + VB[0] + '" y="' + VB[1] + '" width="' + VB[2] + '" height="' + VB[3] + '" fill="var(--field-foul)"/>';
|
||||
s += '<polygon points="' + pts(fair) + '" fill="var(--field-dirt)"/>';
|
||||
s += '<polygon points="' + pts([[0, 0]].concat(fieldTrackLine(F.w, F.t))) + '" fill="var(--field-grass)"/>';
|
||||
} else {
|
||||
s += '<defs><clipPath id="ifFair"><polygon points="' + ifP(0, 0) + ' ' + ifP(lpX, -lpX) + ' ' + ifP(rpX, rpX) + '"/></clipPath></defs>';
|
||||
s += '<rect x="' + VB[0] + '" y="' + VB[1] + '" width="' + VB[2] + '" height="' + VB[3] + '" fill="var(--field-foul)"/>';
|
||||
s += '<polygon points="' + ifP(0, 0) + ' ' + ifP(lpX, -lpX) + ' ' + ifP(rpX, rpX) + '" fill="var(--field-grass)"/>';
|
||||
}
|
||||
s += '<circle cx="0" cy="-60.5" r="95" fill="var(--field-dirt)" clip-path="url(#ifFair)"/>';
|
||||
s += '<polygon points="' + ifP(0, 13) + ' ' + ifP(50.6, 63.64) + ' ' + ifP(0, 114.28) + ' ' + ifP(-50.6, 63.64) + '" fill="var(--field-grass)"/>';
|
||||
s += '<circle cx="0" cy="0" r="13" fill="var(--field-dirt)"/>';
|
||||
s += '<circle cx="0" cy="-60.5" r="9" fill="var(--field-dirt)"/><rect x="-1.5" y="-61" width="3" height="1" fill="var(--field-chalk)"/>';
|
||||
if(F){
|
||||
var lp = F.w[0], rp = F.w[F.w.length - 1];
|
||||
s += '<line x1="0" y1="0" x2="' + lp[0] + '" y2="' + (-lp[1]) + '" stroke="var(--field-chalk)" stroke-width="' + (0.8 * k) + '"/>';
|
||||
s += '<line x1="0" y1="0" x2="' + rp[0] + '" y2="' + (-rp[1]) + '" stroke="var(--field-chalk)" stroke-width="' + (0.8 * k) + '"/>';
|
||||
s += '<polyline points="' + pts(F.w) + '" fill="none" stroke="var(--field-wall)" stroke-width="' + (2.2 * k) + '" stroke-linejoin="round" stroke-linecap="round"/>';
|
||||
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 += '<text x="' + (-Math.sin(a) * d).toFixed(1) + '" y="' + (-Math.cos(a) * d).toFixed(1) + '" text-anchor="middle" dominant-baseline="central" font-size="' + (9 * k) + '" font-weight="700" fill="var(--field-chalk)" opacity=".9">' + sg[1] + '</text>';
|
||||
});
|
||||
} else {
|
||||
s += '<line x1="0" y1="0" x2="' + lpX + '" y2="' + lpX + '" stroke="var(--field-chalk)" stroke-width="1"/>';
|
||||
s += '<line x1="0" y1="0" x2="' + rpX + '" y2="' + (-rpX) + '" stroke="var(--field-chalk)" stroke-width="1"/>';
|
||||
}
|
||||
var b = F ? Math.max(7, 3.2 * k) : 7;
|
||||
// home plate: point toward the catcher, flat edge toward the pitcher
|
||||
s += '<polygon points="' + ifP(-b / 2, b * 0.9) + ' ' + ifP(b / 2, b * 0.9) + ' ' + ifP(b / 2, b * 0.4) + ' ' + ifP(0, 0) + ' ' + ifP(-b / 2, b * 0.4) + '" fill="var(--field-chalk)"/>';
|
||||
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 += '<g class="if-base" data-base="' + (i + 1) + '" role="button" tabindex="0" aria-label="' + esc(label) + '">';
|
||||
s += '<circle cx="' + q[0] + '" cy="' + (-q[1]) + '" r="' + Math.max(24, 16 * k) + '" fill="transparent"/>';
|
||||
s += '<rect x="' + (q[0] - b / 2) + '" y="' + (-q[1] - b / 2) + '" width="' + b + '" height="' + b + '" fill="var(--field-chalk)" transform="rotate(45 ' + q[0] + ' ' + (-q[1]) + ')"/>';
|
||||
if(occ){
|
||||
var r = 11 * k;
|
||||
s += '<circle cx="' + q[0] + '" cy="' + (-q[1]) + '" r="' + r + '" fill="var(--amber)" stroke="var(--surface)" stroke-width="' + (2 * k) + '"/>';
|
||||
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 += '<rect x="' + lx + '" y="' + ly + '" width="' + tw + '" height="' + th + '" rx="' + th / 2 + '" fill="var(--surface)" opacity=".92"/>';
|
||||
s += '<text x="' + (lx + tw / 2) + '" y="' + (ly + th / 2) + '" text-anchor="middle" dominant-baseline="central" font-size="' + t + '" font-weight="600" fill="var(--text)">' + esc(name) + '</text>';
|
||||
}
|
||||
}
|
||||
s += '</g>';
|
||||
});
|
||||
return s + '</svg>';
|
||||
}
|
||||
|
||||
// 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 = '<option value="">— Select pitcher —</option>';
|
||||
pitchers.forEach(function(p){
|
||||
var label = (p.jersey ? '#'+p.jersey+' ' : '') + p.name;
|
||||
html += '<option value="'+esc(p.name)+'"'+(p.name===selectedName?' selected':'')+'>'+label+'</option>';
|
||||
});
|
||||
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]?'<img src="'+TEAM_LOGOS[tName]+'" style="width:20px;height:20px;object-fit:contain;vertical-align:middle;margin-right:6px;" alt="" />':'';
|
||||
var html='<div class="ph">'+logo+'<span>'+tName+'</span><span class="ph-hint">tap row to set active</span></div>';
|
||||
pp.forEach(function(p,i){
|
||||
var a=p.active;
|
||||
var opts = pitcherOpts(side, p.name);
|
||||
html+='<div class="prow'+(a?' active-p':'')+'" data-action="set-active-p" data-side="'+side+'" data-pidx="'+i+'">';
|
||||
html+='<span class="p-dot'+(a?'':' hidden')+'"></span>';
|
||||
if(opts !== null){
|
||||
html+='<select class="p-name-sel" data-action="set-p-name" data-side="'+side+'" data-pidx="'+i+'">'+opts+'</select>';
|
||||
} else {
|
||||
html+='<input class="p-name" value="'+esc(p.name)+'" placeholder="Pitcher '+(i+1)+'" data-action="set-p-name" data-side="'+side+'" data-pidx="'+i+'" />';
|
||||
}
|
||||
html+='<span class="pc'+pitchCountClass(p.pitches)+'" id="'+side+'pc'+i+'">'+p.pitches+'</span>';
|
||||
html+='<div class="p-line" id="'+side+'pl'+i+'" data-action="edit-p-line" data-side="'+side+'" data-pidx="'+i+'" role="button" tabindex="0" title="Tap to edit this pitching line">'+pitchingLine(p)+'</div>';
|
||||
html+='<div class="padj"><button class="pb" data-action="adj-p" data-side="'+side+'" data-pidx="'+i+'" data-dir="-1">−</button><button class="pb" data-action="adj-p" data-side="'+side+'" data-pidx="'+i+'" data-dir="1">+</button></div>';
|
||||
html+='</div>';
|
||||
});
|
||||
html+='<div class="add-p" data-action="add-p" data-side="'+side+'"><span style="font-size:16px;margin-right:4px">+</span>Add pitcher</div>';
|
||||
var chk = staffOutsCheck(side);
|
||||
if(chk) html+='<div class="p-warn">⚠ Innings pitched add up to '+fmtIP(chk.credited)+', but this team has recorded '+fmtIP(chk.expected)+'. Tap a pitching line to fix it.</div>';
|
||||
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('<span title="Pitches-strikes">' + p.pitches + '-' + pitchStrikes(p) + '</span>');
|
||||
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 = '<div class="rp-modal" role="dialog" aria-modal="true" aria-labelledby="pleTitle">';
|
||||
html += '<div class="rp-hdr"><h3 id="pleTitle">' + esc(p.name || 'Pitcher ' + (idx + 1)) + ' <span class="rp-hdr-sub">— ' + esc(team(side)) + '</span></h3>'
|
||||
+ '<button class="inn-popover-close" style="position:static" onclick="closePitchLineEditor()" aria-label="Close">×</button></div>';
|
||||
html += '<div class="rp-body"><div class="ple-grid">';
|
||||
PLE_FIELDS.forEach(function(f){
|
||||
var v = f.k === 'outs' ? fmtIP(p.outs || 0) : (p[f.k] || 0);
|
||||
html += '<label>' + f.label + '<input id="ple_' + f.k + '" value="' + v + '" inputmode="' + (f.k === 'outs' ? 'decimal' : 'numeric') + '" autocomplete="off"'
|
||||
+ ' onkeydown="if(event.key===\'Enter\'){event.preventDefault();savePitchLineEditor();}else if(event.key===\'Escape\'){event.preventDefault();closePitchLineEditor();}" /></label>';
|
||||
});
|
||||
html += '</div>';
|
||||
html += '<div class="pe-note">IP uses baseball notation: 5.1 = 5⅓ innings, 5.2 = 5⅔.'
|
||||
+ (chk ? ' This team has recorded <b>' + fmtIP(chk.expected) + '</b> innings of outs so far; its pitchers are credited with ' + fmtIP(chk.credited) + '.' : '')
|
||||
+ ' Pitch counts are changed with − / + on the row.</div>';
|
||||
html += '<div class="pe-actions"><button class="pe-cancel" onclick="closePitchLineEditor()">Cancel</button>'
|
||||
+ '<button class="rp-confirm" onclick="savePitchLineEditor()">Save</button></div>';
|
||||
html += '</div></div>';
|
||||
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);
|
||||
}
|
||||
@@ -1,916 +0,0 @@
|
||||
// Output: PDF box score, Share final image, season stats, team pickers and the stadium photo.
|
||||
// Loaded as a plain script; files share one global scope (see index.html for the order).
|
||||
|
||||
function exportPDF(){
|
||||
var away = document.getElementById('teamAway').value || 'Away';
|
||||
var home = document.getElementById('teamHome').value || 'Home';
|
||||
var awayLogo = TEAM_LOGOS[away] ? '<img src="'+TEAM_LOGOS[away]+'" style="width:36px;height:36px;object-fit:contain;vertical-align:middle;margin-right:8px;" />' : '';
|
||||
var homeLogo = TEAM_LOGOS[home] ? '<img src="'+TEAM_LOGOS[home]+'" style="width:36px;height:36px;object-fit:contain;vertical-align:middle;margin-left:8px;" />' : '';
|
||||
var badge = postseasonBadge();
|
||||
document.getElementById('printHeader').innerHTML = (badge ? '<div>' + badge + '</div>' : '') + awayLogo + away + ' vs ' + home + homeLogo;
|
||||
|
||||
// Build subheader: score, date, venue
|
||||
var subParts = [];
|
||||
var awayR = G.rhe.away[0], homeR = G.rhe.home[0];
|
||||
if(G.log.length > 0) subParts.push('Final: ' + awayR + ' – ' + homeR);
|
||||
if(G.notes && G.notes.date){
|
||||
try {
|
||||
var dp = G.notes.date.split('-');
|
||||
var dateObj = new Date(dp[0], dp[1]-1, dp[2]);
|
||||
subParts.push(dateObj.toLocaleDateString('en-US', {weekday:'long', year:'numeric', month:'long', day:'numeric'}));
|
||||
} catch(e){ subParts.push(G.notes.date); }
|
||||
}
|
||||
if(G.notes && G.notes.venue) subParts.push(G.notes.venue);
|
||||
if(G.notes && G.notes.attendance) subParts.push('Att: ' + G.notes.attendance);
|
||||
document.getElementById('printSub').textContent = subParts.join(' • ');
|
||||
|
||||
// Hide empty game-info rows for cleaner print
|
||||
var giRows = document.querySelectorAll('.gi-row');
|
||||
giRows.forEach(function(row){
|
||||
var inputs = row.querySelectorAll('input, select, textarea');
|
||||
var hasValue = false;
|
||||
inputs.forEach(function(inp){
|
||||
if(inp.value && inp.value.trim() && inp.value !== '—') hasValue = true;
|
||||
});
|
||||
// Also check if a weather button is selected in this row
|
||||
var weatherBtns = row.querySelectorAll('.gi-weather-btn.sel');
|
||||
if(weatherBtns.length > 0) hasValue = true;
|
||||
row.classList.toggle('gi-row-empty', !hasValue);
|
||||
});
|
||||
|
||||
// Build box score table
|
||||
buildPrintBoxScore();
|
||||
renderScorecard();
|
||||
|
||||
window.print();
|
||||
|
||||
// Clean up: remove gi-row-empty class
|
||||
giRows.forEach(function(row){ row.classList.remove('gi-row-empty'); });
|
||||
}
|
||||
|
||||
function buildPrintBoxScore(){
|
||||
var el = document.getElementById('printBoxScore');
|
||||
if(!el) return;
|
||||
|
||||
var html = '';
|
||||
['away','home'].forEach(function(side){
|
||||
var tName = team(side);
|
||||
var logo = TEAM_LOGOS[tName] ? '<img src="'+TEAM_LOGOS[tName]+'" style="width:14px;height:14px;object-fit:contain;vertical-align:middle;margin-right:4px;" />' : '';
|
||||
|
||||
html += '<table style="margin-bottom:6px">';
|
||||
html += '<tr><td class="bs-team-hdr" colspan="11">' + logo + tName + ' — Batting</td></tr>';
|
||||
html += '<tr><th style="text-align:left;padding-left:6px;min-width:100px">Player</th><th>Pos</th><th>AB</th><th>H</th><th>R</th><th>2B</th><th>3B</th><th>HR</th><th>BB</th><th>K</th><th>RBI</th></tr>';
|
||||
|
||||
var totals = {ab:0,h:0,r:0,d:0,t:0,hr:0,bb:0,k:0,rbi:0};
|
||||
|
||||
for(var i=0;i<9;i++){
|
||||
var sl = G.lineup[side][i];
|
||||
// Starter row
|
||||
var sh = sl.hits;
|
||||
var sAB = abFor(sh);
|
||||
var sH = sh.s + sh.d + sh.t + sh.hr;
|
||||
var sK = sh.kl + sh.ks;
|
||||
var sBB = sh.bb + sh.ibb;
|
||||
var sR = sh.r || 0;
|
||||
var sRBI = sh.rbi || 0;
|
||||
var sName = sl.name || 'Player ' + (i+1);
|
||||
var sPos = sl.pos || '—';
|
||||
var dimClass = sl.subs.length > 0 ? ' style="opacity:.5"' : '';
|
||||
|
||||
html += '<tr'+dimClass+'><td style="text-align:left;padding-left:6px">' + esc(sName) + '</td>';
|
||||
html += '<td>'+sPos+'</td><td>'+sAB+'</td><td>'+sH+'</td><td>'+sR+'</td><td>'+sh.d+'</td><td>'+sh.t+'</td><td>'+sh.hr+'</td><td>'+sBB+'</td><td>'+sK+'</td><td>'+sRBI+'</td></tr>';
|
||||
|
||||
totals.ab += sAB; totals.h += sH; totals.r += sR; totals.d += sh.d; totals.t += sh.t; totals.hr += sh.hr; totals.bb += sBB; totals.k += sK; totals.rbi += sRBI;
|
||||
|
||||
// Sub rows
|
||||
sl.subs.forEach(function(sub, si){
|
||||
var subH = sub.hits || mkHits();
|
||||
var subAB = abFor(subH);
|
||||
var subHits = subH.s + subH.d + subH.t + subH.hr;
|
||||
var subK = subH.kl + subH.ks;
|
||||
var subBB = subH.bb + subH.ibb;
|
||||
var subR = subH.r || 0;
|
||||
var subRBI = subH.rbi || 0;
|
||||
var subName = sub.name || 'Sub';
|
||||
var subPos = sub.pos || '—';
|
||||
var isLast = si === sl.subs.length - 1;
|
||||
var subDim = !isLast ? ' style="opacity:.5"' : '';
|
||||
|
||||
html += '<tr'+subDim+'><td style="text-align:left;padding-left:16px;font-style:italic">↳ ' + esc(subName) + '</td>';
|
||||
html += '<td>'+subPos+'</td><td>'+subAB+'</td><td>'+subHits+'</td><td>'+subR+'</td><td>'+subH.d+'</td><td>'+subH.t+'</td><td>'+subH.hr+'</td><td>'+subBB+'</td><td>'+subK+'</td><td>'+subRBI+'</td></tr>';
|
||||
|
||||
totals.ab += subAB; totals.h += subHits; totals.r += subR; totals.d += subH.d; totals.t += subH.t; totals.hr += subH.hr; totals.bb += subBB; totals.k += subK; totals.rbi += subRBI;
|
||||
});
|
||||
}
|
||||
|
||||
html += '<tr class="bs-totals"><td style="text-align:left;padding-left:6px">TOTALS</td><td></td>';
|
||||
html += '<td>'+totals.ab+'</td><td>'+totals.h+'</td><td>'+totals.r+'</td><td>'+totals.d+'</td><td>'+totals.t+'</td><td>'+totals.hr+'</td><td>'+totals.bb+'</td><td>'+totals.k+'</td><td>'+totals.rbi+'</td></tr>';
|
||||
var risp = rispLine(side);
|
||||
html += '<tr><td colspan="11" style="text-align:left;padding-left:6px;font-weight:400">With RISP: ' + risp.h + '-for-' + risp.ab + ' · Left on base: ' + teamLOB(side) + '</td></tr>';
|
||||
html += '</table>';
|
||||
|
||||
// Pitching line
|
||||
html += '<table style="margin-bottom:10px">';
|
||||
html += '<tr><td class="bs-team-hdr" colspan="9">' + logo + tName + ' — Pitching</td></tr>';
|
||||
html += '<tr><th style="text-align:left;padding-left:6px;min-width:100px">Pitcher</th><th>IP</th><th>H</th><th>R</th><th>ER</th><th>BB</th><th>K</th><th>HR</th><th>P-S</th></tr>';
|
||||
G.pitchers[side].forEach(function(p){
|
||||
var pName = p.name || '—';
|
||||
var activeMarker = p.active ? ' ●' : '';
|
||||
html += '<tr><td style="text-align:left;padding-left:6px">' + esc(pName) + activeMarker + '</td>';
|
||||
html += '<td>'+fmtIP(p.outs)+'</td><td>'+p.h+'</td><td>'+p.r+'</td><td>'+p.er+'</td><td>'+p.bb+'</td><td>'+p.k+'</td><td>'+p.hr+'</td><td>'+p.pitches+'-'+pitchStrikes(p)+'</td></tr>';
|
||||
});
|
||||
html += '</table>';
|
||||
});
|
||||
|
||||
el.innerHTML = html;
|
||||
}
|
||||
|
||||
function buildTeamOptions(selectedVal) {
|
||||
return MLB_TEAMS.map(function(t){
|
||||
return '<option value="'+t+'"'+(t===selectedVal?' selected':'')+'>'+t+'</option>';
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function populateTeamDropdowns() {
|
||||
var awayEl = document.getElementById('teamAway');
|
||||
var homeEl = document.getElementById('teamHome');
|
||||
awayEl.innerHTML = buildTeamOptions('— Select Team —');
|
||||
homeEl.innerHTML = buildTeamOptions('— Select Team —');
|
||||
}
|
||||
|
||||
// "Game #" picker sits next to Game type; only shown for a postseason round
|
||||
function renderSeriesGamePicker(){
|
||||
var el = document.getElementById('giSeriesGame');
|
||||
if(!el) return;
|
||||
var ps = POSTSEASON[G.notes && G.notes.gameType];
|
||||
if(!ps){ el.style.display = 'none'; el.innerHTML = ''; return; }
|
||||
var cur = String(G.notes.seriesGame || '');
|
||||
var html = '<option value="">Game —</option>';
|
||||
for(var n = 1; n <= ps.maxGames; n++){
|
||||
html += '<option value="' + n + '"' + (cur === String(n) ? ' selected' : '') + '>Game ' + n + '</option>';
|
||||
}
|
||||
el.innerHTML = html;
|
||||
el.style.display = '';
|
||||
}
|
||||
|
||||
// The round's logo for this game: the official logo for that year when the app
|
||||
// bundles one (it already says e.g. "2026 ALDS"), otherwise the league logo.
|
||||
// The round's logo for a game's info (the current game's by default)
|
||||
function postseasonLogo(notes){
|
||||
var n = notes || G.notes || {};
|
||||
var ps = POSTSEASON[n.gameType];
|
||||
if(!ps) return null;
|
||||
var yr = (n.date || '').slice(0, 4) || String(new Date().getFullYear());
|
||||
var official = ps.official && ps.official[yr];
|
||||
return { ps: ps, yr: yr, src: official || ps.logo, official: !!official, label: yr + ' ' + ps.label };
|
||||
}
|
||||
|
||||
function postseasonBadge(){
|
||||
var pl = postseasonLogo();
|
||||
if(!pl) return '';
|
||||
var gameNo = G.notes.seriesGame ? 'Game ' + G.notes.seriesGame : '';
|
||||
if(pl.official){
|
||||
return '<span class="ps-badge ps-badge-official"><img src="' + pl.src + '" alt="' + esc(pl.label) + '" />' + gameNo + '</span>';
|
||||
}
|
||||
return '<span class="ps-badge"><img src="' + pl.src + '" alt="" />' + pl.label + (gameNo ? ' · ' + gameNo : '') + '</span>';
|
||||
}
|
||||
|
||||
// ── Postseason series ──
|
||||
// Saved postseason games grouped into series (year + round + the two teams),
|
||||
// newest first. The series score counts games scored through the final out.
|
||||
function teamShort(name){
|
||||
var m = /(Red Sox|White Sox|Blue Jays)$/.exec(name || '');
|
||||
return m ? m[1] : String(name || '').split(' ').pop();
|
||||
}
|
||||
|
||||
function psSeriesList(){
|
||||
var map = {}, list = [];
|
||||
ssGames().forEach(function(x){
|
||||
var n = x.g.notes || {}, ps = POSTSEASON[n.gameType];
|
||||
if(!ps) return;
|
||||
var pl = postseasonLogo(n);
|
||||
var teams = [x.away, x.home].sort();
|
||||
var key = pl.yr + '|' + n.gameType + '|' + teams.join('|');
|
||||
var s = map[key];
|
||||
if(!s){
|
||||
s = map[key] = { key: key, label: pl.label, logo: pl.src, maxGames: ps.maxGames, teams: teams, wins: {}, games: [], lastDate: '' };
|
||||
s.wins[teams[0]] = 0; s.wins[teams[1]] = 0;
|
||||
list.push(s);
|
||||
}
|
||||
var as = x.g.rhe.away[0] || 0, hs = x.g.rhe.home[0] || 0, final = ssIsFinal(x.g);
|
||||
var winner = final && as !== hs ? (as > hs ? x.away : x.home) : '';
|
||||
if(winner) s.wins[winner]++;
|
||||
s.games.push({ id: x.id, num: parseInt(n.seriesGame, 10) || 0, date: n.date || '', away: x.away, home: x.home,
|
||||
as: as, hs: hs, final: final, winner: winner, current: !!x.current });
|
||||
if((n.date || '') > s.lastDate) s.lastDate = n.date;
|
||||
});
|
||||
list.forEach(function(s){
|
||||
s.games.sort(function(a, b){ return (a.num || 99) - (b.num || 99) || a.date.localeCompare(b.date); });
|
||||
var a = s.teams[0], b = s.teams[1], wa = s.wins[a], wb = s.wins[b];
|
||||
s.leader = wa === wb ? '' : wa > wb ? a : b;
|
||||
s.clinched = Math.max(wa, wb) >= Math.ceil(s.maxGames / 2);
|
||||
// Every game from Game 1 on is here (only the latest may still be going): the score is the real series score
|
||||
var n = s.games.length;
|
||||
s.complete = s.games.every(function(g, i){ return g.num === i + 1 && (g.final || i === n - 1); });
|
||||
});
|
||||
list.sort(function(x, y){ return y.lastDate.localeCompare(x.lastDate); });
|
||||
return list;
|
||||
}
|
||||
|
||||
function psSeriesStatus(s){
|
||||
var a = s.teams[0], b = s.teams[1];
|
||||
if(!s.wins[a] && !s.wins[b]) return 'No finished games yet';
|
||||
var hi = s.leader || a, lo = hi === a ? b : a;
|
||||
var score = s.wins[hi] + '–' + s.wins[lo];
|
||||
var text = !s.leader ? 'Tied ' + score : teamShort(hi) + (s.clinched ? ' win ' : ' lead ') + score;
|
||||
return text + (s.complete || s.clinched ? '' : ' in games you scored');
|
||||
}
|
||||
|
||||
// The "Postseason" section at the top of My Games
|
||||
function psSeriesHtml(){
|
||||
var list = psSeriesList();
|
||||
if(!list.length) return '';
|
||||
var html = '<div class="ps-series-wrap"><div class="ps-series-title">🏆 Postseason</div>';
|
||||
list.forEach(function(s){
|
||||
html += '<div class="ps-series">'
|
||||
+ '<div class="ps-series-hdr"><img class="ps-series-logo" src="' + s.logo + '" alt="" /><span class="ps-series-round">' + esc(s.label) + '</span>'
|
||||
+ '<span class="ps-series-teams">' + s.teams.map(function(t){
|
||||
var logo = TEAM_LOGOS[t];
|
||||
return (logo ? '<img class="gm-card-logo" src="' + logo + '" alt="" />' : '') + esc(teamShort(t));
|
||||
}).join(' <span class="ps-series-vs">vs</span> ') + '</span></div>'
|
||||
+ '<div class="ps-series-status">' + esc(psSeriesStatus(s)) + '</div><div class="ps-series-games">';
|
||||
var last = 0;
|
||||
s.games.forEach(function(g){
|
||||
// Gaps in the numbering: games not scored
|
||||
for(var k = last + 1; g.num && k < g.num; k++) html += '<span class="ps-game ps-game-missing">G' + k + ' · not scored</span>';
|
||||
if(g.num) last = g.num;
|
||||
var lbl = (g.num ? 'G' + g.num : g.date || 'Game') + ' · ';
|
||||
if(g.final && g.winner) lbl += teamShort(g.winner) + ' ' + Math.max(g.as, g.hs) + '–' + Math.min(g.as, g.hs);
|
||||
else lbl += teamShort(g.away) + ' ' + g.as + ', ' + teamShort(g.home) + ' ' + g.hs + (g.final ? '' : ' · unfinished');
|
||||
if(g.current) html += '<span class="ps-game ps-game-active" title="Open now">' + esc(lbl) + '</span>';
|
||||
else html += '<button class="ps-game" onclick="gmLoadGame(\'' + g.id + '\')">' + esc(lbl) + '</button>';
|
||||
});
|
||||
html += '</div></div>';
|
||||
});
|
||||
return html + '</div>';
|
||||
}
|
||||
|
||||
function teamLogoImg(side, cls){
|
||||
var url = TEAM_LOGOS[team(side)];
|
||||
return url ? '<img class="' + cls + '" src="' + url + '" alt="" />' : '';
|
||||
}
|
||||
|
||||
function renderStadium(teamName){
|
||||
var wrap = document.getElementById('stadiumWrap');
|
||||
if(!wrap) return;
|
||||
var ph = STADIUM_PHOTOS[teamName], sd = STADIUMS[teamName];
|
||||
if(!ph){ wrap.innerHTML = ''; return; }
|
||||
var venue = (sd && sd.name) || teamName;
|
||||
wrap.innerHTML = '<figure class="stadium-photo">'
|
||||
+ '<img src="' + esc(ph.img) + '" alt="' + esc(venue) + '" decoding="async" onerror="this.parentNode.classList.add(\'stadium-photo-off\')" />'
|
||||
+ '<figcaption><span class="stadium-name">' + esc(venue) + '</span>'
|
||||
+ '<a class="stadium-credit" href="' + esc(ph.page) + '" target="_blank" rel="noopener">Photo: ' + esc(ph.by) + ' · ' + esc(ph.lic) + '</a></figcaption>'
|
||||
+ '</figure>';
|
||||
}
|
||||
|
||||
// ══ Shareable final ══
|
||||
// Draws the game as a PNG (score, line score, batting and pitching lines)
|
||||
// for the share sheet. Always light-themed — it's meant to be posted.
|
||||
var SF_W = 1080, SF_PAD = 48;
|
||||
|
||||
var SF_C = { bg:'#ffffff', ink:'#1a1a1a', muted:'#888780', line:'#e3e1d9', head:'#f5f4f0', accent:'#185FA5' };
|
||||
|
||||
var SF_FONT = '-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif';
|
||||
|
||||
var _sf = null;
|
||||
|
||||
// { blob, url, filename }
|
||||
|
||||
// "New York Yankees" → "Yankees", "Toronto Blue Jays" → "Blue Jays"
|
||||
function teamShort(name){
|
||||
var two = /(Red Sox|White Sox|Blue Jays)$/.exec(name);
|
||||
return two ? two[1] : name.split(' ').pop();
|
||||
}
|
||||
|
||||
function sfLoadImg(url){
|
||||
return new Promise(function(resolve){
|
||||
if(!url) return resolve(null);
|
||||
var im = new Image();
|
||||
im.crossOrigin = 'anonymous'; // MLB serves logos with CORS, so the canvas stays exportable
|
||||
im.onload = function(){ resolve(im); };
|
||||
im.onerror = function(){ resolve(null); };
|
||||
setTimeout(function(){ resolve(null); }, 5000); // offline: draw without logos
|
||||
im.src = url;
|
||||
});
|
||||
}
|
||||
|
||||
function sfContain(ctx, im, x, y, w, h){
|
||||
if(!im) return;
|
||||
var iw = im.naturalWidth || w, ih = im.naturalHeight || h;
|
||||
var s = Math.min(w / iw, h / ih), dw = iw * s, dh = ih * s;
|
||||
ctx.drawImage(im, x + (w - dw) / 2, y + (h - dh) / 2, dw, dh);
|
||||
}
|
||||
|
||||
// Text cut to fit with an ellipsis
|
||||
function sfFit(ctx, text, maxW){
|
||||
text = String(text);
|
||||
if(ctx.measureText(text).width <= maxW) return text;
|
||||
while(text.length > 1 && ctx.measureText(text + '…').width > maxW) text = text.slice(0, -1);
|
||||
return text + '…';
|
||||
}
|
||||
|
||||
function sfText(ctx, text, x, y, opts){
|
||||
opts = opts || {};
|
||||
ctx.font = (opts.weight || 400) + ' ' + (opts.size || 22) + 'px ' + SF_FONT;
|
||||
ctx.fillStyle = opts.color || SF_C.ink;
|
||||
ctx.textAlign = opts.align || 'left';
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.fillText(opts.maxW ? sfFit(ctx, text, opts.maxW) : String(text), x, y);
|
||||
}
|
||||
|
||||
// Every player who appeared, starters then their subs, plus team totals
|
||||
function sfBatting(side){
|
||||
var rows = [], tot = { ab:0, r:0, h:0, rbi:0, bb:0, k:0 };
|
||||
G.lineup[side].forEach(function(sl, i){
|
||||
var players = [{ name: sl.name || 'Batter ' + (i + 1), pos: sl.pos, h: sl.hits, sub: false }]
|
||||
.concat(sl.subs.map(function(s){ return { name: s.name || 'Sub', pos: s.subType === 'pr' ? 'PR' : s.pos, h: s.hits || mkHits(), sub: true }; }));
|
||||
players.forEach(function(p){
|
||||
var h = p.h;
|
||||
var r = { name: p.name, pos: p.pos && p.pos !== '—' ? p.pos : '', sub: p.sub,
|
||||
ab: abFor(h), r: h.r || 0, h: h.s + h.d + h.t + h.hr, rbi: h.rbi || 0,
|
||||
bb: (h.bb || 0) + (h.ibb || 0), k: (h.kl || 0) + (h.ks || 0) };
|
||||
rows.push(r);
|
||||
['ab', 'r', 'h', 'rbi', 'bb', 'k'].forEach(function(k){ tot[k] += r[k]; });
|
||||
});
|
||||
});
|
||||
return { rows: rows, tot: tot };
|
||||
}
|
||||
|
||||
// Pitchers who were used (or at least named)
|
||||
function sfPitching(side){
|
||||
return G.pitchers[side].filter(function(p){ return p.pitches || p.outs || p.name; });
|
||||
}
|
||||
|
||||
function sfStatus(){
|
||||
if(G.log.some(function(l){ return l.tag === 'Final'; })){
|
||||
return 'FINAL' + (G.inning > 9 || G.totalInnings > 9 ? '/' + G.inning : '');
|
||||
}
|
||||
return (G.half === 'top' ? 'TOP ' : 'BOT ') + G.inning;
|
||||
}
|
||||
|
||||
function buildFinalImage(){
|
||||
var away = team('away'), home = team('home');
|
||||
var bat = { away: sfBatting('away'), home: sfBatting('home') };
|
||||
var pit = { away: sfPitching('away'), home: sfPitching('home') };
|
||||
var ps = POSTSEASON[G.notes && G.notes.gameType];
|
||||
var pl = postseasonLogo();
|
||||
return Promise.all([sfLoadImg(TEAM_LOGOS[away]), sfLoadImg(TEAM_LOGOS[home]), sfLoadImg(pl ? pl.src : null)]).then(function(imgs){
|
||||
var logo = { away: imgs[0], home: imgs[1] }, psLogo = imgs[2];
|
||||
var n = Math.max(9, G.totalInnings);
|
||||
var batRows = Math.max(bat.away.rows.length, bat.home.rows.length);
|
||||
var pitRows = Math.max(pit.away.length, pit.home.length, 1);
|
||||
var RH = 34;
|
||||
var H = SF_PAD + 44 + 24 + 150 + 30 + 46 * 3 + 44 + 44 + RH * batRows + 40 + 36 + 44 + RH * pitRows + 30 + 40 + SF_PAD;
|
||||
|
||||
var scale = 2; // crisp on phones/retina
|
||||
var cv = document.createElement('canvas');
|
||||
cv.width = SF_W * scale; cv.height = H * scale;
|
||||
var ctx = cv.getContext('2d');
|
||||
ctx.scale(scale, scale);
|
||||
ctx.fillStyle = SF_C.bg;
|
||||
ctx.fillRect(0, 0, SF_W, H);
|
||||
|
||||
var x0 = SF_PAD, x1 = SF_W - SF_PAD, y = SF_PAD;
|
||||
|
||||
// ── Top line: postseason badge · date · venue
|
||||
var meta = [];
|
||||
if(G.notes && G.notes.date){
|
||||
try {
|
||||
var dp = G.notes.date.split('-');
|
||||
meta.push(new Date(dp[0], dp[1] - 1, dp[2]).toLocaleDateString('en-US', { weekday:'short', month:'short', day:'numeric', year:'numeric' }));
|
||||
} catch(e){ meta.push(G.notes.date); }
|
||||
}
|
||||
if(G.notes && G.notes.venue) meta.push(G.notes.venue);
|
||||
var bx = x0;
|
||||
if(pl){
|
||||
var gameNo = G.notes.seriesGame ? 'Game ' + G.notes.seriesGame : '';
|
||||
if(pl.official && psLogo){
|
||||
// The official logo carries the year and round itself; just add the game
|
||||
sfContain(ctx, psLogo, bx, y - 10, 90, 60); bx += 102;
|
||||
if(gameNo) sfText(ctx, gameNo.toUpperCase(), bx, y + 20, { size:22, weight:800, color:SF_C.ink });
|
||||
} else {
|
||||
if(psLogo){ sfContain(ctx, psLogo, bx, y, 40, 40); bx += 50; }
|
||||
sfText(ctx, (pl.label + (gameNo ? ' · ' + gameNo : '')).toUpperCase(), bx, y + 20, { size:22, weight:800, color:SF_C.ink });
|
||||
}
|
||||
}
|
||||
if(meta.length) sfText(ctx, meta.join(' · '), x1, y + 20, { size:20, color:SF_C.muted, align:'right', maxW: ps ? 480 : x1 - x0 });
|
||||
y += 44 + 24;
|
||||
|
||||
// ── Score: logo, name and runs for each team, status in the middle
|
||||
var aR = G.rhe.away[0], hR = G.rhe.home[0], final = sfStatus().indexOf('FINAL') === 0;
|
||||
var mid = SF_W / 2;
|
||||
[['away', away, aR, hR], ['home', home, hR, aR]].forEach(function(t){
|
||||
var left = t[0] === 'away', won = final && t[2] > t[3];
|
||||
var lx = left ? x0 : x1 - 120;
|
||||
sfContain(ctx, logo[t[0]], lx, y + 15, 120, 120);
|
||||
var nx = left ? x0 + 140 : x1 - 140;
|
||||
sfText(ctx, teamShort(t[1]), nx, y + 60, { size:40, weight:800, align: left ? 'left' : 'right', maxW: 250, color: SF_C.ink });
|
||||
sfText(ctx, t[1].replace(teamShort(t[1]), '').trim() || ' ', nx, y + 102, { size:20, color:SF_C.muted, align: left ? 'left' : 'right', maxW: 250 });
|
||||
sfText(ctx, t[2], left ? mid - 70 : mid + 70, y + 75, { size:96, weight:800, align: left ? 'right' : 'left', color: final && !won ? SF_C.muted : SF_C.ink });
|
||||
});
|
||||
// status pill
|
||||
ctx.font = '800 20px ' + SF_FONT;
|
||||
var st = sfStatus(), pw = ctx.measureText(st).width + 28;
|
||||
ctx.fillStyle = final ? SF_C.ink : SF_C.accent;
|
||||
sfRound(ctx, mid - pw / 2, y + 58, pw, 34, 17); ctx.fill();
|
||||
sfText(ctx, st, mid, y + 76, { size:20, weight:800, color:'#ffffff', align:'center' });
|
||||
y += 150 + 30;
|
||||
|
||||
// ── Line score
|
||||
var teamW = 200, rheW = 64, innW = (x1 - x0 - teamW - rheW * 3) / n;
|
||||
ctx.fillStyle = SF_C.head; ctx.fillRect(x0, y, x1 - x0, 46);
|
||||
for(var c = 1; c <= n; c++) sfText(ctx, c, x0 + teamW + innW * (c - 0.5), y + 23, { size:20, weight:600, color:SF_C.muted, align:'center' });
|
||||
['R', 'H', 'E'].forEach(function(k, i){ sfText(ctx, k, x1 - rheW * (3 - i) + rheW / 2, y + 23, { size:20, weight:700, color:SF_C.muted, align:'center' }); });
|
||||
['away', 'home'].forEach(function(side, r){
|
||||
var ry = y + 46 * (r + 1);
|
||||
sfLine(ctx, x0, ry, x1, ry);
|
||||
sfContain(ctx, logo[side], x0 + 6, ry + 7, 32, 32);
|
||||
sfText(ctx, teamShort(team(side)), x0 + 48, ry + 23, { size:22, weight:700, maxW: teamW - 56 });
|
||||
for(var c = 1; c <= n; c++){
|
||||
var v = G.scores[side][c - 1];
|
||||
sfText(ctx, v === null || v === undefined ? '' : v, x0 + teamW + innW * (c - 0.5), ry + 23, { size:22, align:'center' });
|
||||
}
|
||||
G.rhe[side].forEach(function(v, i){ sfText(ctx, v, x1 - rheW * (3 - i) + rheW / 2, ry + 23, { size:22, weight:800, align:'center' }); });
|
||||
});
|
||||
sfLine(ctx, x0, y + 46 * 3, x1, y + 46 * 3);
|
||||
sfLine(ctx, x1 - rheW * 3, y, x1 - rheW * 3, y + 46 * 3);
|
||||
y += 46 * 3 + 44;
|
||||
|
||||
// ── Batting and pitching, away on the left, home on the right
|
||||
var colW = (x1 - x0 - 40) / 2;
|
||||
var BAT_COLS = ['AB', 'R', 'H', 'RBI', 'BB', 'K'], BAT_KEYS = ['ab', 'r', 'h', 'rbi', 'bb', 'k'];
|
||||
var PIT_COLS = ['IP', 'H', 'R', 'ER', 'BB', 'K'];
|
||||
var statW = 44;
|
||||
var yBat = y;
|
||||
['away', 'home'].forEach(function(side, ci){
|
||||
var cx = x0 + ci * (colW + 40), sx = cx + colW - statW * BAT_COLS.length;
|
||||
var yy = yBat;
|
||||
sfText(ctx, teamShort(team(side)) + ' batting', cx, yy + 20, { size:22, weight:800 });
|
||||
BAT_COLS.forEach(function(h, i){ sfText(ctx, h, sx + statW * (i + 0.5), yy + 20, { size:17, weight:700, color:SF_C.muted, align:'center' }); });
|
||||
yy += 44;
|
||||
sfLine(ctx, cx, yy - 4, cx + colW, yy - 4);
|
||||
bat[side].rows.forEach(function(r){
|
||||
var nm = shortName(r.name) + (r.pos ? ' ' + r.pos : '');
|
||||
sfText(ctx, (r.sub ? '↳ ' : '') + nm, cx + (r.sub ? 14 : 0), yy + RH / 2, { size: r.sub ? 18 : 20, weight: r.sub ? 400 : 500, color: r.sub ? '#444' : SF_C.ink, maxW: sx - cx - (r.sub ? 22 : 8) });
|
||||
BAT_KEYS.forEach(function(k, i){ sfText(ctx, r[k], sx + statW * (i + 0.5), yy + RH / 2, { size:20, align:'center', color: r[k] ? SF_C.ink : SF_C.muted }); });
|
||||
yy += RH;
|
||||
});
|
||||
yy = yBat + 44 + RH * batRows;
|
||||
sfLine(ctx, cx, yy + 2, cx + colW, yy + 2);
|
||||
sfText(ctx, 'Totals', cx, yy + 20, { size:20, weight:800 });
|
||||
BAT_KEYS.forEach(function(k, i){ sfText(ctx, bat[side].tot[k], sx + statW * (i + 0.5), yy + 20, { size:20, weight:800, align:'center' }); });
|
||||
var risp = rispLine(side);
|
||||
sfText(ctx, 'With RISP: ' + risp.h + '-for-' + risp.ab + ' · Left on base: ' + teamLOB(side), cx, yy + 52, { size:18, color:SF_C.muted });
|
||||
|
||||
var yp = yBat + 44 + RH * batRows + 40 + 36;
|
||||
sfText(ctx, teamShort(team(side)) + ' pitching', cx, yp + 20, { size:22, weight:800 });
|
||||
PIT_COLS.forEach(function(h, i){ sfText(ctx, h, sx + statW * (i + 0.5), yp + 20, { size:17, weight:700, color:SF_C.muted, align:'center' }); });
|
||||
yp += 44;
|
||||
sfLine(ctx, cx, yp - 4, cx + colW, yp - 4);
|
||||
pit[side].forEach(function(p){
|
||||
sfText(ctx, shortName(p.name || 'Pitcher'), cx, yp + RH / 2, { size:20, weight:500, maxW: sx - cx - 8 });
|
||||
[fmtIP(p.outs || 0), p.h || 0, p.r || 0, p.er || 0, p.bb || 0, p.k || 0].forEach(function(v, i){
|
||||
sfText(ctx, v, sx + statW * (i + 0.5), yp + RH / 2, { size:20, align:'center' });
|
||||
});
|
||||
yp += RH;
|
||||
});
|
||||
});
|
||||
|
||||
// ── Footer
|
||||
sfText(ctx, 'Scored live with Baseball Scorecard', SF_W / 2, H - SF_PAD + 6, { size:17, color:SF_C.muted, align:'center' });
|
||||
|
||||
return new Promise(function(resolve, reject){
|
||||
cv.toBlob(function(blob){ blob ? resolve(blob) : reject(new Error('Couldn\'t create the image.')); }, 'image/png');
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function sfLine(ctx, ax, ay, bx2, by){
|
||||
ctx.strokeStyle = SF_C.line; ctx.lineWidth = 1.5;
|
||||
ctx.beginPath(); ctx.moveTo(ax, ay); ctx.lineTo(bx2, by); ctx.stroke();
|
||||
}
|
||||
|
||||
function sfRound(ctx, x, y, w, h, r){
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(x + r, y); ctx.lineTo(x + w - r, y); ctx.quadraticCurveTo(x + w, y, x + w, y + r);
|
||||
ctx.lineTo(x + w, y + h - r); ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
|
||||
ctx.lineTo(x + r, y + h); ctx.quadraticCurveTo(x, y + h, x, y + h - r);
|
||||
ctx.lineTo(x, y + r); ctx.quadraticCurveTo(x, y, x + r, y);
|
||||
ctx.closePath();
|
||||
}
|
||||
|
||||
function sfFilename(){
|
||||
var d = (G.notes && G.notes.date) || new Date().toISOString().slice(0, 10);
|
||||
return (teamShort(team('away')) + '-at-' + teamShort(team('home')) + '-' + d).replace(/\s+/g, '-') + '.png';
|
||||
}
|
||||
|
||||
// Preview with Share / Save / Copy
|
||||
function openShareFinal(){
|
||||
closeShareFinal();
|
||||
var ov = document.createElement('div');
|
||||
ov.className = 'gm-overlay';
|
||||
ov.id = 'sfOverlay';
|
||||
ov.addEventListener('click', function(e){ if(e.target === ov) closeShareFinal(); });
|
||||
ov.innerHTML = '<div class="gm-modal sf-modal" role="dialog" aria-modal="true" aria-labelledby="sfTitle">'
|
||||
+ '<div class="gm-hdr"><h3 id="sfTitle">🖼 Share final</h3><button class="games-modal-close" onclick="closeShareFinal()" aria-label="Close">×</button></div>'
|
||||
+ '<div class="gm-body"><div class="mlb-msg" id="sfBody">Drawing the scorecard…</div></div></div>';
|
||||
document.body.appendChild(ov);
|
||||
buildFinalImage().then(function(blob){
|
||||
if(!document.getElementById('sfOverlay')) return;
|
||||
_sf = { blob: blob, url: URL.createObjectURL(blob), filename: sfFilename() };
|
||||
var file = new File([blob], _sf.filename, { type:'image/png' });
|
||||
var canShare = !!(navigator.canShare && navigator.canShare({ files:[file] }));
|
||||
var canCopy = !!(navigator.clipboard && window.ClipboardItem);
|
||||
var el = document.getElementById('sfBody');
|
||||
el.className = 'sf-body';
|
||||
el.innerHTML = '<img class="sf-img" src="' + _sf.url + '" alt="Scorecard image: ' + esc(team('away')) + ' ' + G.rhe.away[0] + ', ' + esc(team('home')) + ' ' + G.rhe.home[0] + '" />'
|
||||
+ '<div class="sf-acts">'
|
||||
+ (canShare ? '<button class="mlb-use" onclick="shareFinalImage()">Share…</button>' : '')
|
||||
+ '<button class="' + (canShare ? 'mlb-keep' : 'mlb-use') + '" onclick="saveFinalImage()">Save image</button>'
|
||||
+ (canCopy ? '<button class="mlb-keep" onclick="copyFinalImage()">Copy image</button>' : '')
|
||||
+ '</div>';
|
||||
}).catch(function(err){
|
||||
var el = document.getElementById('sfBody');
|
||||
if(el){ el.className = 'mlb-msg mlb-err'; el.textContent = (err && err.message) || 'Couldn\'t create the image.'; }
|
||||
});
|
||||
}
|
||||
|
||||
function closeShareFinal(){
|
||||
var ov = document.getElementById('sfOverlay');
|
||||
if(ov) ov.remove();
|
||||
if(_sf && _sf.url) URL.revokeObjectURL(_sf.url);
|
||||
_sf = null;
|
||||
}
|
||||
|
||||
function shareFinalImage(){
|
||||
if(!_sf) return;
|
||||
var file = new File([_sf.blob], _sf.filename, { type:'image/png' });
|
||||
navigator.share({ files:[file] }).catch(function(err){
|
||||
if(!err || err.name !== 'AbortError') saveFinalImage();
|
||||
});
|
||||
}
|
||||
|
||||
function saveFinalImage(){
|
||||
if(!_sf) return;
|
||||
var a = document.createElement('a');
|
||||
a.href = _sf.url;
|
||||
a.download = _sf.filename;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
}
|
||||
|
||||
function copyFinalImage(){
|
||||
if(!_sf) return;
|
||||
navigator.clipboard.write([new ClipboardItem({ 'image/png': _sf.blob })])
|
||||
.then(function(){ kbFlash('Image copied', '#1D9E75'); })
|
||||
.catch(function(){ kbFlash('Couldn\'t copy — use Save image', '#BA7517'); });
|
||||
}
|
||||
|
||||
// ══ Season stats ══
|
||||
// Totals across every saved game (My Games) plus the one in progress:
|
||||
// batting, pitching and a game list, filtered by team, attendance and game type.
|
||||
var SS_PREFS_KEY = 'baseball_scorecard_stats_prefs';
|
||||
|
||||
var _ss = { team: 'all', attended: 'all', type: 'all', tab: 'batting', sort: {} };
|
||||
|
||||
try { Object.assign(_ss, JSON.parse(localStorage.getItem(SS_PREFS_KEY) || '{}')); } catch(e){}
|
||||
|
||||
function ssSavePrefs(){
|
||||
try { localStorage.setItem(SS_PREFS_KEY, JSON.stringify({ team:_ss.team, attended:_ss.attended, type:_ss.type, tab:_ss.tab, sort:_ss.sort })); } catch(e){}
|
||||
}
|
||||
|
||||
// ── At-bat bar extras ──
|
||||
// The batter in your other saved games (cached until My Games changes), and
|
||||
// their career line against the pitcher on the mound (MLB, once per matchup).
|
||||
var _abHist = { sig: null, by: {} };
|
||||
|
||||
function abHistory(teamName, name){
|
||||
var activeId = gmGetActiveId();
|
||||
// The open game saves on every pitch and isn't counted: leave it out, so scoring doesn't recompute this
|
||||
var sig = gmGetIndex().filter(function(e){ return e.id !== activeId; }).map(function(e){ return e.id + '@' + e.savedAt; }).join() + '|' + activeId;
|
||||
if(_abHist.sig !== sig){
|
||||
var others = ssGames().filter(function(x){ return !x.current && x.id !== activeId; });
|
||||
_abHist = { sig: sig, by: {} };
|
||||
ssBattingRows(others).forEach(function(r){ _abHist.by[r.team + '|' + mlbNormName(r.name)] = r; });
|
||||
}
|
||||
return _abHist.by[teamName + '|' + mlbNormName(name)] || null;
|
||||
}
|
||||
|
||||
var _abVs = {}; // 'batterId|pitcherId' → MLB's career totals, 'loading', or { failedAt }
|
||||
|
||||
function rosterId(side, name){
|
||||
var n = mlbNormName(name), hit = (ROSTERS[side] || []).filter(function(p){ return mlbNormName(p.name) === n; })[0];
|
||||
return hit && hit.id;
|
||||
}
|
||||
|
||||
function abVsPitcher(bSide, bName, pName){
|
||||
var bid = rosterId(bSide, bName), pid = rosterId(bSide === 'home' ? 'away' : 'home', pName);
|
||||
if(!bid || !pid) return null;
|
||||
var key = bid + '|' + pid, v = _abVs[key];
|
||||
if(v === undefined || (v && v.failedAt && Date.now() - v.failedAt > 300000)){
|
||||
_abVs[key] = 'loading';
|
||||
mlbFetchJSON(MLB_API + '/people/' + bid + '/stats?stats=vsPlayer&opposingPlayerId=' + pid + '&group=hitting').then(function(d){
|
||||
var tot = (d.stats || []).filter(function(s){ return s.type && s.type.displayName === 'vsPlayerTotal'; })[0];
|
||||
var st = (tot && tot.splits && tot.splits[0] && tot.splits[0].stat) || {};
|
||||
_abVs[key] = { pa: st.plateAppearances || 0, ab: st.atBats || 0, h: st.hits || 0, hr: st.homeRuns || 0, bb: st.baseOnBalls || 0, k: st.strikeOuts || 0 };
|
||||
renderAtBatBar();
|
||||
}, function(){ _abVs[key] = { failedAt: Date.now() }; });
|
||||
return null;
|
||||
}
|
||||
return v && v.pa !== undefined ? v : null;
|
||||
}
|
||||
|
||||
// "7-for-25 · 2 HR · 3 BB"
|
||||
function abLine(h, ab, hr, bb){
|
||||
return h + '-for-' + ab + (hr ? ' · ' + hr + ' HR' : '') + (bb ? ' · ' + bb + ' BB' : '');
|
||||
}
|
||||
|
||||
function abExtrasHtml(bSide, bName, pName){
|
||||
var parts = [], hist = abHistory(team(bSide), bName), vs = abVsPitcher(bSide, bName, pName);
|
||||
if(hist) parts.push('<span title="In your other saved games">📒 Your scorecards: ' + esc(abLine(hist.h, hist.ab, hist.hr, hist.bb)) + ' · ' + hist.g + ' game' + (hist.g === 1 ? '' : 's') + '</span>');
|
||||
if(vs) parts.push('<span title="Career, from MLB">vs ' + esc(shortName(pName)) + ': ' + (vs.pa ? esc(abLine(vs.h, vs.ab, vs.hr, vs.bb)) : 'first meeting') + '</span>');
|
||||
return parts.length ? '<div class="atbat-extra">' + parts.join('') + '</div>' : '';
|
||||
}
|
||||
|
||||
function ssTeamLabel(v, fallback){ return (!v || v === '— Select Team —') ? fallback : v; }
|
||||
|
||||
// Every game with plays: saved slots, with the live game taken from memory
|
||||
function ssGames(){
|
||||
var activeId = gmGetActiveId(), out = [];
|
||||
gmGetIndex().forEach(function(e){
|
||||
if(e.id === activeId) return;
|
||||
var payload = null;
|
||||
try { payload = JSON.parse(localStorage.getItem(GM_GAME_PREFIX + e.id) || 'null'); } catch(x){}
|
||||
if(!payload || !payload.G || payload.syncCopy) return; // sync conflict copies don't count twice
|
||||
var g = migrateGame(payload.G);
|
||||
if(!g.log.length && !g.pas.length) return;
|
||||
out.push({ id: e.id, g: g, away: ssTeamLabel(payload.teamAway, 'Away'), home: ssTeamLabel(payload.teamHome, 'Home') });
|
||||
});
|
||||
if(G.log.length || G.pas.length) out.push({ id: activeId || '', g: G, away: team('away'), home: team('home'), current: true });
|
||||
return out;
|
||||
}
|
||||
|
||||
function ssIsFinal(g){ return g.log.some(function(l){ return l.tag === 'Final'; }); }
|
||||
|
||||
function ssTypeOf(g){
|
||||
var t = (g.notes && g.notes.gameType) || '';
|
||||
return POSTSEASON[t] ? 'post' : t || 'unset';
|
||||
}
|
||||
|
||||
function ssFiltered(){
|
||||
return ssGames().filter(function(x){
|
||||
if(_ss.team !== 'all' && x.away !== _ss.team && x.home !== _ss.team) return false;
|
||||
if(_ss.attended === 'yes' && !(x.g.notes && x.g.notes.attended)) return false;
|
||||
if(_ss.type !== 'all' && ssTypeOf(x.g) !== _ss.type) return false;
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
// Which player batted in a PA of game g (starter or sub), without touching G
|
||||
function ssPaPlayer(g, pa){
|
||||
var sl = g.lineup[pa.side][pa.slot], who = pa.who;
|
||||
if(who === undefined){
|
||||
var at = pa.inn * 2 + (pa.half === 'bot' ? 1 : 0); who = -1;
|
||||
sl.subs.forEach(function(sub, si){ if(sub.inning * 2 + (sub.half === 'bot' ? 1 : 0) <= at) who = si; });
|
||||
}
|
||||
return who >= 0 && sl.subs[who] ? sl.subs[who].name : sl.name;
|
||||
}
|
||||
|
||||
function ssBatting(games){
|
||||
return ssBattingRows(games).filter(function(r){ return _ss.team === 'all' || r.team === _ss.team; });
|
||||
}
|
||||
|
||||
// Batting totals per player (team + name) across the given games
|
||||
function ssBattingRows(games){
|
||||
var by = {};
|
||||
games.forEach(function(x){
|
||||
var seen = {};
|
||||
['away', 'home'].forEach(function(side){
|
||||
var tm = x[side];
|
||||
x.g.lineup[side].forEach(function(sl){
|
||||
[{ name: sl.name, h: sl.hits }].concat(sl.subs.map(function(s){ return { name: s.name, h: s.hits || mkHits() }; })).forEach(function(p){
|
||||
if(!p.name) return;
|
||||
var h = p.h, pa = abFor(h) + (h.bb || 0) + (h.ibb || 0) + (h.hbp || 0) + (h.ci || 0) + (h.sf || 0) + (h.sac || 0);
|
||||
var k = tm + '|' + mlbNormName(p.name);
|
||||
var r = by[k] = by[k] || { name: p.name, team: tm, g: 0, ab: 0, r: 0, h: 0, d: 0, t: 0, hr: 0, rbi: 0, bb: 0, k: 0, sb: 0, hbp: 0, sf: 0, rh: 0, rab: 0 };
|
||||
if(pa > 0 && !seen[k]){ r.g++; seen[k] = true; }
|
||||
r.ab += abFor(h); r.r += h.r || 0; r.h += h.s + h.d + h.t + h.hr; r.d += h.d; r.t += h.t; r.hr += h.hr;
|
||||
r.rbi += h.rbi || 0; r.bb += (h.bb || 0) + (h.ibb || 0); r.k += (h.kl || 0) + (h.ks || 0); r.sb += h.sb || 0;
|
||||
r.hbp += h.hbp || 0; r.sf += h.sf || 0;
|
||||
});
|
||||
});
|
||||
});
|
||||
x.g.pas.forEach(function(pa){
|
||||
if(!pa.risp || !paIsAB(pa.res)) return;
|
||||
var r = by[x[pa.side] + '|' + mlbNormName(ssPaPlayer(x.g, pa))];
|
||||
if(!r) return;
|
||||
r.rab++;
|
||||
if(paIsHit(pa.res)) r.rh++;
|
||||
});
|
||||
});
|
||||
return Object.keys(by).map(function(k){
|
||||
var r = by[k], singles = r.h - r.d - r.t - r.hr, obpDen = r.ab + r.bb + r.hbp + r.sf;
|
||||
r.avg = r.ab ? r.h / r.ab : null;
|
||||
r.obp = obpDen ? (r.h + r.bb + r.hbp) / obpDen : null;
|
||||
r.slg = r.ab ? (singles + 2 * r.d + 3 * r.t + 4 * r.hr) / r.ab : null;
|
||||
return r;
|
||||
}).filter(function(r){ return r.g > 0; });
|
||||
}
|
||||
|
||||
function ssPitching(games){
|
||||
var by = {};
|
||||
games.forEach(function(x){
|
||||
['away', 'home'].forEach(function(side){
|
||||
var tm = x[side];
|
||||
x.g.pitchers[side].forEach(function(p){
|
||||
if(!p.name || !(p.pitches || p.outs)) return;
|
||||
var k = tm + '|' + mlbNormName(p.name);
|
||||
var r = by[k] = by[k] || { name: p.name, team: tm, g: 0, outs: 0, h: 0, r: 0, er: 0, bb: 0, k: 0, hr: 0, pitches: 0 };
|
||||
r.g++; r.outs += p.outs || 0; r.h += p.h || 0; r.r += p.r || 0; r.er += p.er || 0;
|
||||
r.bb += p.bb || 0; r.k += p.k || 0; r.hr += p.hr || 0; r.pitches += p.pitches || 0;
|
||||
});
|
||||
});
|
||||
});
|
||||
return Object.keys(by).map(function(k){
|
||||
var r = by[k], ip = r.outs / 3;
|
||||
r.era = ip ? r.er * 9 / ip : null;
|
||||
r.whip = ip ? (r.bb + r.h) / ip : null;
|
||||
return r;
|
||||
}).filter(function(r){ return _ss.team === 'all' || r.team === _ss.team; });
|
||||
}
|
||||
|
||||
// ".250" style; "—" when there's nothing to divide by
|
||||
function ssRate(v){ return v === null ? '—' : v.toFixed(3).replace(/^0/, ''); }
|
||||
|
||||
function ssDec(v){ return v === null ? '—' : v.toFixed(2); }
|
||||
|
||||
var SS_BAT_COLS = [
|
||||
['name', 'Player'], ['team', 'Team'], ['g', 'G'], ['ab', 'AB'], ['r', 'R'], ['h', 'H'], ['d', '2B'], ['t', '3B'], ['hr', 'HR'],
|
||||
['rbi', 'RBI'], ['bb', 'BB'], ['k', 'K'], ['sb', 'SB'], ['avg', 'AVG'], ['obp', 'OBP'], ['slg', 'SLG'], ['rab', 'RISP']
|
||||
];
|
||||
|
||||
var SS_PIT_COLS = [
|
||||
['name', 'Pitcher'], ['team', 'Team'], ['g', 'G'], ['outs', 'IP'], ['h', 'H'], ['r', 'R'], ['er', 'ER'], ['bb', 'BB'],
|
||||
['k', 'K'], ['hr', 'HR'], ['era', 'ERA'], ['whip', 'WHIP'], ['pitches', 'P']
|
||||
];
|
||||
|
||||
function ssSorted(rows, tab, def){
|
||||
var s = _ss.sort[tab] || def, key = s.key, dir = s.dir;
|
||||
return rows.slice().sort(function(a, b){
|
||||
var va = a[key], vb = b[key];
|
||||
if(typeof va === 'string' || typeof vb === 'string') return dir * String(va).localeCompare(String(vb));
|
||||
if(va === null) return 1;
|
||||
if(vb === null) return -1;
|
||||
return dir * (va - vb) || String(a.name).localeCompare(String(b.name));
|
||||
});
|
||||
}
|
||||
|
||||
function ssSetSort(tab, key){
|
||||
var cur = _ss.sort[tab];
|
||||
var lowFirst = key === 'name' || key === 'team' || key === 'era' || key === 'whip';
|
||||
_ss.sort[tab] = { key: key, dir: cur && cur.key === key ? -cur.dir : (lowFirst ? 1 : -1) };
|
||||
ssSavePrefs();
|
||||
renderSeasonStats();
|
||||
}
|
||||
|
||||
function ssHeader(cols, tab, def){
|
||||
var s = _ss.sort[tab] || def;
|
||||
return '<tr>' + cols.map(function(c){
|
||||
if(c[0] === 'team' && _ss.team !== 'all') return '';
|
||||
var on = s.key === c[0];
|
||||
return '<th' + (c[0] === 'name' ? ' class="ss-name"' : '') + ' aria-sort="' + (on ? (s.dir > 0 ? 'ascending' : 'descending') : 'none') + '">'
|
||||
+ '<button onclick="ssSetSort(\'' + tab + '\',\'' + c[0] + '\')">' + c[1] + (on ? (s.dir > 0 ? ' ▲' : ' ▼') : '') + '</button></th>';
|
||||
}).join('') + '</tr>';
|
||||
}
|
||||
|
||||
function openSeasonStats(){
|
||||
closeSeasonStats();
|
||||
clearTimeout(_saveTimer);
|
||||
_doSave();
|
||||
var ov = document.createElement('div');
|
||||
ov.className = 'gm-overlay';
|
||||
ov.id = 'ssOverlay';
|
||||
ov.addEventListener('click', function(e){ if(e.target === ov) closeSeasonStats(); });
|
||||
document.body.appendChild(ov);
|
||||
renderSeasonStats();
|
||||
}
|
||||
|
||||
function closeSeasonStats(){
|
||||
var ov = document.getElementById('ssOverlay');
|
||||
if(ov) ov.remove();
|
||||
}
|
||||
|
||||
function ssSet(field, value){
|
||||
_ss[field] = value;
|
||||
ssSavePrefs();
|
||||
renderSeasonStats();
|
||||
}
|
||||
|
||||
function ssOpenGame(id){
|
||||
closeSeasonStats();
|
||||
if(id && id !== gmGetActiveId()) gmLoadGame(id);
|
||||
}
|
||||
|
||||
function renderSeasonStats(){
|
||||
var ov = document.getElementById('ssOverlay');
|
||||
if(!ov) return;
|
||||
var all = ssGames();
|
||||
var teams = {};
|
||||
all.forEach(function(x){ teams[x.away] = true; teams[x.home] = true; });
|
||||
delete teams.Away; delete teams.Home;
|
||||
if(_ss.team !== 'all' && !teams[_ss.team]) _ss.team = 'all';
|
||||
var games = ssFiltered();
|
||||
|
||||
var html = '<div class="gm-modal ss-modal" role="dialog" aria-modal="true" aria-labelledby="ssTitle">';
|
||||
html += '<div class="gm-hdr"><h3 id="ssTitle">📊 Season stats</h3><button class="games-modal-close" onclick="closeSeasonStats()" aria-label="Close">×</button></div>';
|
||||
html += '<div class="gm-body">';
|
||||
|
||||
// Filters
|
||||
html += '<div class="ss-filters">';
|
||||
html += '<label>Team <select onchange="ssSet(\'team\', this.value)"><option value="all">All teams</option>'
|
||||
+ Object.keys(teams).sort().map(function(t){ return '<option value="' + esc(t) + '"' + (_ss.team === t ? ' selected' : '') + '>' + esc(t) + '</option>'; }).join('') + '</select></label>';
|
||||
html += '<label>Games <select onchange="ssSet(\'attended\', this.value)"><option value="all">All games</option><option value="yes"' + (_ss.attended === 'yes' ? ' selected' : '') + '>Games I attended</option></select></label>';
|
||||
var types = [['all', 'All types'], ['post', 'Postseason'], ['regular', 'Regular season'], ['spring', 'Spring training'], ['unset', 'Not set']];
|
||||
html += '<label>Type <select onchange="ssSet(\'type\', this.value)">' + types.map(function(t){ return '<option value="' + t[0] + '"' + (_ss.type === t[0] ? ' selected' : '') + '>' + t[1] + '</option>'; }).join('') + '</select></label>';
|
||||
html += '</div>';
|
||||
|
||||
// Summary: games, and the record when a team is picked
|
||||
var finals = games.filter(function(x){ return ssIsFinal(x.g); });
|
||||
var sum = games.length + ' game' + (games.length === 1 ? '' : 's') + ' scored';
|
||||
if(finals.length < games.length) sum += ' · ' + (games.length - finals.length) + ' not final';
|
||||
var att = games.filter(function(x){ return x.g.notes && x.g.notes.attended; }).length;
|
||||
if(att) sum += ' · ' + att + ' attended';
|
||||
var rec = '';
|
||||
if(_ss.team !== 'all' && finals.length){
|
||||
var w = 0, l = 0, rf = 0, ra = 0;
|
||||
finals.forEach(function(x){
|
||||
var mine = x.away === _ss.team ? 'away' : 'home', theirs = mine === 'away' ? 'home' : 'away';
|
||||
var a = x.g.rhe[mine][0], b = x.g.rhe[theirs][0];
|
||||
rf += a; ra += b;
|
||||
if(a > b) w++; else if(b > a) l++;
|
||||
});
|
||||
rec = '<div class="ss-record"><b>' + w + '-' + l + '</b> <span>' + esc(_ss.team) + ' record · ' + rf + ' run' + (rf === 1 ? '' : 's') + ' scored, ' + ra + ' allowed</span></div>';
|
||||
}
|
||||
html += '<div class="ss-sum">' + rec + '<div>' + sum + '</div></div>';
|
||||
|
||||
// Tabs
|
||||
html += '<div class="ss-tabs" role="tablist">' + [['batting', 'Batting'], ['pitching', 'Pitching'], ['games', 'Games']].map(function(t){
|
||||
return '<button role="tab" aria-selected="' + (_ss.tab === t[0]) + '" class="sc-tab' + (_ss.tab === t[0] ? ' sel' : '') + '" onclick="ssSet(\'tab\',\'' + t[0] + '\')">' + t[1] + '</button>';
|
||||
}).join('') + '</div>';
|
||||
|
||||
if(!games.length){
|
||||
html += '<div class="mlb-msg">No games match these filters yet.</div>';
|
||||
} else if(_ss.tab === 'batting'){
|
||||
var rows = ssSorted(ssBatting(games), 'batting', { key: 'ab', dir: -1 });
|
||||
html += '<div class="ss-scroll"><table class="ss-table"><thead>' + ssHeader(SS_BAT_COLS, 'batting', { key: 'ab', dir: -1 }) + '</thead><tbody>';
|
||||
rows.forEach(function(r){
|
||||
html += '<tr><td class="ss-name">' + esc(r.name) + '</td>' + (_ss.team === 'all' ? '<td class="ss-team">' + esc(teamShort(r.team)) + '</td>' : '')
|
||||
+ [r.g, r.ab, r.r, r.h, r.d, r.t, r.hr, r.rbi, r.bb, r.k, r.sb].map(function(v){ return '<td>' + v + '</td>'; }).join('')
|
||||
+ '<td><b>' + ssRate(r.avg) + '</b></td><td>' + ssRate(r.obp) + '</td><td>' + ssRate(r.slg) + '</td>'
|
||||
+ '<td>' + (r.rab ? r.rh + '-' + r.rab : '—') + '</td></tr>';
|
||||
});
|
||||
html += '</tbody></table></div><div class="mlb-foot">RISP: hits-at bats with a runner on 2nd or 3rd, for plate appearances where it was recorded.</div>';
|
||||
} else if(_ss.tab === 'pitching'){
|
||||
var prow = ssSorted(ssPitching(games), 'pitching', { key: 'outs', dir: -1 });
|
||||
html += '<div class="ss-scroll"><table class="ss-table"><thead>' + ssHeader(SS_PIT_COLS, 'pitching', { key: 'outs', dir: -1 }) + '</thead><tbody>';
|
||||
prow.forEach(function(r){
|
||||
html += '<tr><td class="ss-name">' + esc(r.name) + '</td>' + (_ss.team === 'all' ? '<td class="ss-team">' + esc(teamShort(r.team)) + '</td>' : '')
|
||||
+ '<td>' + r.g + '</td><td>' + fmtIP(r.outs) + '</td>'
|
||||
+ [r.h, r.r, r.er, r.bb, r.k, r.hr].map(function(v){ return '<td>' + v + '</td>'; }).join('')
|
||||
+ '<td><b>' + ssDec(r.era) + '</b></td><td>' + ssDec(r.whip) + '</td><td>' + r.pitches + '</td></tr>';
|
||||
});
|
||||
html += '</tbody></table></div>';
|
||||
} else {
|
||||
var list = games.slice().sort(function(a, b){ return String(b.g.notes.date || '').localeCompare(String(a.g.notes.date || '')); });
|
||||
html += '<div class="ss-scroll"><table class="ss-table ss-games"><thead><tr><th class="ss-name">Date</th><th class="ss-name">Game</th><th>Score</th><th>Type</th><th></th></tr></thead><tbody>';
|
||||
list.forEach(function(x){
|
||||
var g = x.g, ps = POSTSEASON[g.notes.gameType], fin = ssIsFinal(g);
|
||||
var score = g.rhe.away[0] + '-' + g.rhe.home[0];
|
||||
var res = '';
|
||||
if(fin && _ss.team !== 'all'){
|
||||
var me = x.away === _ss.team ? 'away' : 'home', a = g.rhe[me][0], b = g.rhe[me === 'away' ? 'home' : 'away'][0];
|
||||
res = a > b ? '<span class="ss-w">W</span> ' : b > a ? '<span class="ss-l">L</span> ' : '';
|
||||
}
|
||||
var typeLabel = ps ? ps.label + (g.notes.seriesGame ? ' G' + g.notes.seriesGame : '') : ({ regular: 'Regular', spring: 'Spring', asg: 'All-Star', other: 'Other' })[g.notes.gameType] || '—';
|
||||
html += '<tr><td class="ss-name">' + esc(g.notes.date || '—') + '</td>'
|
||||
+ '<td class="ss-name">' + esc(teamShort(x.away)) + ' @ ' + esc(teamShort(x.home)) + (g.notes.attended ? ' <span class="ss-att">Attended</span>' : '') + (x.current ? ' <span class="ss-att">Open now</span>' : '') + '</td>'
|
||||
+ '<td>' + res + score + (fin ? '' : ' <span class="ss-live">' + (g.half === 'top' ? 'T' : 'B') + g.inning + '</span>') + '</td>'
|
||||
+ '<td>' + esc(typeLabel) + '</td>'
|
||||
+ '<td>' + (x.current ? '' : '<button class="mlb-keep" onclick="ssOpenGame(\'' + esc(x.id) + '\')">Open</button>') + '</td></tr>';
|
||||
});
|
||||
html += '</tbody></table></div>';
|
||||
}
|
||||
html += '</div></div>';
|
||||
ov.innerHTML = html;
|
||||
}
|
||||
@@ -1,550 +0,0 @@
|
||||
// The scorecard grid, its cell editor and the inning popover.
|
||||
// Loaded as a plain script; files share one global scope (see index.html for the order).
|
||||
|
||||
// ── Per-inning batter tracking ──
|
||||
// Records which batters had plate appearances in each half-inning.
|
||||
// Key format: "T1", "B1", "T2", "B2", etc.
|
||||
// outsOnPlay: total outs the play makes (DP=2, TP=3); the batter is credited
|
||||
// with the last of them, as on a standard 6-4-3.
|
||||
function logBatter(side, batterIdx, result, outsOnPlay){
|
||||
var key = (G.half === 'top' ? 'T' : 'B') + G.inning;
|
||||
if(!G.batterLog[side][key]) G.batterLog[side][key] = [];
|
||||
var nm = curName(side, batterIdx);
|
||||
G.batterLog[side][key].push(nm + ' — ' + result);
|
||||
|
||||
var isOut = paIsOut(result), id = newPaId();
|
||||
// The result line ("Díaz — Single") was just logged: point it at this PA
|
||||
if(G.log[0] && !G.log[0].paId && G.log[0].text.indexOf(nm) >= 0) G.log[0].paId = id;
|
||||
G.pas.push({
|
||||
id: id,
|
||||
side: side, slot: batterIdx, inn: G.inning, half: G.half, res: result,
|
||||
reached: paReachFor(result),
|
||||
out: isOut ? Math.min(3, G.outs + (outsOnPlay || 1)) : 0,
|
||||
pIdx: activePIdx(side === 'home' ? 'away' : 'home'),
|
||||
who: G.lineup[side][batterIdx].subs.length - 1, // -1 = starter, else sub index
|
||||
risp: !!(G.bases[1] || G.bases[2]), // runner on 2nd or 3rd when the PA ended
|
||||
unearned: result[0] === 'E' || result === 'CI'
|
||||
});
|
||||
scheduleScorecardRender();
|
||||
}
|
||||
|
||||
// ── Scorecard grid ──
|
||||
// Batters down, innings across; one diamond per plate appearance.
|
||||
// Follows the batting team each half-inning; tapping a tab overrides until the
|
||||
// next half starts.
|
||||
var scView = null, _scHalfSeen = null;
|
||||
|
||||
var _scRenderScheduled = false;
|
||||
|
||||
function scheduleScorecardRender(){
|
||||
if(_scRenderScheduled) return;
|
||||
_scRenderScheduled = true;
|
||||
var schedule = window.requestAnimationFrame || function(cb){ return setTimeout(cb, 0); };
|
||||
schedule(function(){
|
||||
_scRenderScheduled = false;
|
||||
renderScorecard();
|
||||
});
|
||||
}
|
||||
|
||||
function setScorecardView(side){
|
||||
scView = side;
|
||||
_scHalfSeen = G.inning + G.half; // stick with this tab until the half changes
|
||||
renderScorecard();
|
||||
haptic(5);
|
||||
}
|
||||
|
||||
// Display notation for a stored result: "G6-3" → "6-3", "G3" → "3U", "FC6-4" → "FC"
|
||||
function paLabel(res){
|
||||
var m = /^G(\d(?:-\d)+)$/.exec(res);
|
||||
if(m) return m[1];
|
||||
m = /^G(\d)$/.exec(res);
|
||||
if(m) return m[1] + 'U';
|
||||
if(/^FC/.test(res)) return 'FC';
|
||||
if(res === '1B+E' || res === '2B+E' || res === '3B+E' || res === 'HR+E') return res.slice(0, 2);
|
||||
return res;
|
||||
}
|
||||
|
||||
function paLabelClass(res){
|
||||
if(paIsHit(res)) return ' sc-hit';
|
||||
if(res === 'K' || res === 'ꓘ') return ' sc-k';
|
||||
if(res === 'BB' || res === 'IBB' || res === 'HBP') return ' sc-walk';
|
||||
if(res[0] === 'E' || res === 'CI') return ' sc-err';
|
||||
return '';
|
||||
}
|
||||
|
||||
// Corners of the diamond: home → 1B → 2B → 3B → home
|
||||
var SC_PTS = [[20,37],[37,20],[20,3],[3,20],[20,37]];
|
||||
|
||||
function paCellHtml(pa){
|
||||
var svg = '<svg class="sc-dia" viewBox="0 0 40 40" aria-hidden="true">'
|
||||
+ '<polygon class="sc-dia-bg" points="20,37 37,20 20,3 3,20"/>';
|
||||
for(var k = 0; k < pa.reached && k < 4; k++){
|
||||
svg += '<line class="sc-path" x1="' + SC_PTS[k][0] + '" y1="' + SC_PTS[k][1]
|
||||
+ '" x2="' + SC_PTS[k+1][0] + '" y2="' + SC_PTS[k+1][1] + '"/>';
|
||||
}
|
||||
svg += '</svg>';
|
||||
var label = paLabel(pa.res);
|
||||
var desc = label + (pa.reached === 4 ? ', scored' : pa.reached > 0 ? ', reached ' + ['','1st','2nd','3rd'][pa.reached] : '')
|
||||
+ (pa.out ? ', out ' + pa.out + (pa.outOnBases ? ' on the bases' : '') : '');
|
||||
return '<div class="sc-pa' + (pa.reached === 4 ? ' sc-scored' : '') + '" role="button" tabindex="0" data-pa="' + G.pas.indexOf(pa)
|
||||
+ '" title="' + esc(desc) + ' — tap to edit" aria-label="' + esc(desc) + ', edit">'
|
||||
+ svg
|
||||
+ '<span class="sc-res' + paLabelClass(pa.res) + '">' + esc(label) + '</span>'
|
||||
+ (pa.out ? '<span class="sc-outn">' + pa.out + '</span>' : '')
|
||||
+ '</div>';
|
||||
}
|
||||
|
||||
// Same at-bat definition as the printed box score
|
||||
// At-bats as officially scored: reaching on an error counts (roe), walks/HBP/sacrifices don't
|
||||
function abFor(h){ return h.s + h.d + h.t + h.hr + h.kl + h.ks + h.fo + h.go + h.fc + (h.roe || 0); }
|
||||
|
||||
function scorecardTableHtml(side){
|
||||
var n = G.totalInnings;
|
||||
var bySlotInn = {};
|
||||
G.pas.forEach(function(pa){
|
||||
if(pa.side !== side) return;
|
||||
var key = pa.slot + '-' + pa.inn;
|
||||
(bySlotInn[key] = bySlotInn[key] || []).push(pa);
|
||||
});
|
||||
var batSide = batting();
|
||||
var curIdx = abIdx(side);
|
||||
|
||||
var html = '<table class="sc-table' + (side === scView ? ' sc-active' : '') + '">';
|
||||
html += '<caption class="sc-print-hdr">' + teamLogoImg(side, 'sc-hdr-logo') + esc(team(side)) + '</caption>';
|
||||
html += '<thead><tr><th class="sc-name">' + teamLogoImg(side, 'sc-hdr-logo') + esc(team(side)) + '</th>';
|
||||
for(var c = 1; c <= n; c++) html += '<th>' + c + '</th>';
|
||||
html += '<th class="sc-tot sc-tot-first">AB</th><th class="sc-tot">R</th><th class="sc-tot">H</th><th class="sc-tot">RBI</th></tr></thead><tbody>';
|
||||
|
||||
for(var i = 0; i < 9; i++){
|
||||
var sl = G.lineup[side][i];
|
||||
html += '<tr><td class="sc-name"><div class="sc-pname">' + esc(sl.name || 'Batter ' + (i + 1))
|
||||
+ (sl.pos && sl.pos !== '—' ? '<span class="sc-ppos">' + esc(sl.pos) + '</span>' : '') + '</div>';
|
||||
sl.subs.forEach(function(sub){
|
||||
html += '<div class="sc-psub">↳ ' + esc(sub.name || 'Sub') + ' <span class="sc-ppos">'
|
||||
+ esc(sub.subType === 'pr' ? 'PR' : sub.pos) + ' ' + (sub.half === 'top' ? 'T' : 'B') + sub.inning + '</span></div>';
|
||||
});
|
||||
html += '</td>';
|
||||
for(var c = 1; c <= n; c++){
|
||||
var cur = side === batSide && i === curIdx && c === G.inning;
|
||||
html += '<td class="sc-cell' + (cur ? ' sc-cur' : '') + '">';
|
||||
(bySlotInn[i + '-' + c] || []).forEach(function(pa){ html += paCellHtml(pa); });
|
||||
html += '</td>';
|
||||
}
|
||||
var t = {ab:0, r:0, h:0, rbi:0};
|
||||
[sl.hits].concat(sl.subs.map(function(sub){ return sub.hits || mkHits(); })).forEach(function(h){
|
||||
t.ab += abFor(h); t.r += h.r || 0; t.h += h.s + h.d + h.t + h.hr; t.rbi += h.rbi || 0;
|
||||
});
|
||||
html += '<td class="sc-tot sc-tot-first">' + t.ab + '</td><td class="sc-tot">' + t.r + '</td><td class="sc-tot">' + t.h + '</td><td class="sc-tot">' + t.rbi + '</td></tr>';
|
||||
}
|
||||
html += '</tbody>';
|
||||
|
||||
// Per-inning R / H / LOB. LOB only once that half-inning is over.
|
||||
var half = side === 'away' ? 'top' : 'bot';
|
||||
var final = G.log.some(function(l){ return l.tag === 'Final'; });
|
||||
var hits = [], lob = [], hTot = 0, lobTot = 0;
|
||||
for(var c = 1; c <= n; c++){
|
||||
var inHalf = G.pas.filter(function(pa){ return pa.side === side && pa.inn === c; });
|
||||
var h = inHalf.filter(function(pa){ return paIsHit(pa.res); }).length;
|
||||
var done = final || c < G.inning || (c === G.inning && half === 'top' && G.half === 'bot');
|
||||
var l = inHalf.filter(function(pa){ return pa.reached >= 1 && pa.reached <= 3 && !pa.out; }).length;
|
||||
hits.push(inHalf.length ? h : '');
|
||||
lob.push(done && inHalf.length ? l : '');
|
||||
hTot += h;
|
||||
if(done) lobTot += l;
|
||||
}
|
||||
html += '<tfoot>';
|
||||
html += '<tr><td class="sc-name">Runs</td>' + G.scores[side].slice(0, n).map(function(v){ return '<td>' + (v === null ? '' : v) + '</td>'; }).join('')
|
||||
+ '<td class="sc-tot sc-tot-first" colspan="4">' + G.rhe[side][0] + '</td></tr>';
|
||||
html += '<tr><td class="sc-name">Hits</td>' + hits.map(function(v){ return '<td>' + v + '</td>'; }).join('')
|
||||
+ '<td class="sc-tot sc-tot-first" colspan="4">' + hTot + '</td></tr>';
|
||||
html += '<tr><td class="sc-name">Left on base</td>' + lob.map(function(v){ return '<td>' + v + '</td>'; }).join('')
|
||||
+ '<td class="sc-tot sc-tot-first" colspan="4">' + lobTot + '</td></tr>';
|
||||
var rispCells = [];
|
||||
for(var c2 = 1; c2 <= n; c2++){
|
||||
var rl = rispLine(side, c2);
|
||||
rispCells.push(rl.ab ? rl.h + '-' + rl.ab : '');
|
||||
}
|
||||
var rt = rispLine(side);
|
||||
html += '<tr><td class="sc-name" title="Hits-at bats with a runner on 2nd or 3rd">With RISP</td>' + rispCells.map(function(v){ return '<td>' + v + '</td>'; }).join('')
|
||||
+ '<td class="sc-tot sc-tot-first" colspan="4">' + rt.h + '-for-' + rt.ab + '</td></tr>';
|
||||
html += '</tfoot></table>';
|
||||
return html;
|
||||
}
|
||||
|
||||
function renderScorecard(){
|
||||
_scRenderScheduled = false;
|
||||
var wrap = document.getElementById('scorecard');
|
||||
if(!wrap) return;
|
||||
setupScorecardDelegation();
|
||||
var halfKey = G.inning + G.half;
|
||||
if(_scHalfSeen !== halfKey || !scView){ _scHalfSeen = halfKey; scView = batting(); }
|
||||
|
||||
var html = '<div class="sc-tabs" role="tablist">';
|
||||
['away','home'].forEach(function(side){
|
||||
html += '<button class="sc-tab' + (side === scView ? ' sel' : '') + '" role="tab" aria-selected="' + (side === scView)
|
||||
+ '" onclick="setScorecardView(\'' + side + '\')">' + teamLogoImg(side, 'sc-tab-logo') + esc(team(side)) + '</button>';
|
||||
});
|
||||
html += postseasonBadge() + '</div><div class="sc-scroll">' + scorecardTableHtml('away') + scorecardTableHtml('home') + '</div>';
|
||||
|
||||
// Keep horizontal scroll position across re-renders
|
||||
var oldScroll = wrap.querySelector('.sc-scroll');
|
||||
var left = oldScroll ? oldScroll.scrollLeft : 0;
|
||||
wrap.innerHTML = html;
|
||||
wrap.querySelector('.sc-scroll').scrollLeft = left;
|
||||
}
|
||||
|
||||
// ── Scorecard cell editor ──
|
||||
// Corrects a recorded plate appearance after the fact: the result (batter,
|
||||
// pitcher and team hit/error totals follow), how far the runner got, and the
|
||||
// out number. It deliberately doesn't replay the game — runners on base, the
|
||||
// current outs and runs stay as they are.
|
||||
|
||||
// Result "types" offered in the editor. fielders: true → needs a fielder string.
|
||||
var PE_TYPES = [
|
||||
{t:'1B'}, {t:'2B'}, {t:'3B'}, {t:'HR'},
|
||||
{t:'BB'}, {t:'IBB'}, {t:'HBP'}, {t:'CI'},
|
||||
{t:'K'}, {t:'ꓘ', label:'ꓘ'},
|
||||
{t:'F', label:'Fly', fielders:true}, {t:'G', label:'Ground', fielders:true},
|
||||
{t:'SF', fielders:true}, {t:'SAC'}, {t:'FC', fielders:true}, {t:'E', fielders:true},
|
||||
{t:'Out'}
|
||||
];
|
||||
|
||||
// Split a stored result into editor parts: "G6-3" → {t:'G', f:'6-3'}, "1B+E" → {t:'1B', plusE:true}
|
||||
function peParse(res){
|
||||
var m = /^(1B|2B|3B|HR)(\+E)?$/.exec(res);
|
||||
if(m) return {t:m[1], f:'', plusE:!!m[2]};
|
||||
m = /^(SF|FC|F|G|E)([\d-]*)$/.exec(res);
|
||||
if(m) return {t:m[1], f:m[2], plusE:false};
|
||||
return {t:res, f:'', plusE:false};
|
||||
}
|
||||
|
||||
function peCompose(st){
|
||||
var type = PE_TYPES.filter(function(x){ return x.t === st.t; })[0];
|
||||
if(type && type.fielders) return st.t + (st.f || '').replace(/[^\d-]/g, '');
|
||||
if(/^(1B|2B|3B|HR)$/.test(st.t) && st.plusE) return st.t + '+E';
|
||||
return st.t;
|
||||
}
|
||||
|
||||
// The batter / pitcher / team counters a result contributes to
|
||||
function paStatKeys(res){
|
||||
var k = {bat:[], pit:[], teamHit:false, teamErr:false};
|
||||
var hit = /^(1B|2B|3B|HR)/.exec(res);
|
||||
if(hit){
|
||||
k.bat.push({'1B':'s','2B':'d','3B':'t','HR':'hr'}[hit[1]]);
|
||||
k.pit.push('h'); k.teamHit = true;
|
||||
if(hit[1] === 'HR') k.pit.push('hr');
|
||||
if(/\+E$/.test(res)){ k.bat.push('err'); k.teamErr = true; }
|
||||
}
|
||||
else if(res === 'K'){ k.bat.push('ks'); k.pit.push('k'); }
|
||||
else if(res === 'ꓘ'){ k.bat.push('kl'); k.pit.push('k'); }
|
||||
else if(res === 'BB'){ k.bat.push('bb'); k.pit.push('bb'); }
|
||||
else if(res === 'IBB'){ k.bat.push('ibb'); k.pit.push('bb'); }
|
||||
else if(res === 'HBP') k.bat.push('hbp');
|
||||
else if(res === 'CI'){ k.bat.push('ci'); k.teamErr = true; } // catcher's interference: an error on the catcher
|
||||
else if(/^SF/.test(res)) k.bat.push('sf');
|
||||
else if(res === 'SAC') k.bat.push('sac');
|
||||
else if(/^FC/.test(res)) k.bat.push('fc');
|
||||
else if(/^E/.test(res)){ k.bat.push('err'); k.bat.push('roe'); k.teamErr = true; }
|
||||
else if(/^F\d/.test(res)) k.bat.push('fo');
|
||||
else if(/^G\d/.test(res)) k.bat.push('go');
|
||||
return k;
|
||||
}
|
||||
|
||||
// Hits object of the player who batted in this PA (starter or a sub).
|
||||
// PAs recorded before `who` existed: the last sub in by that half-inning.
|
||||
function paHits(pa){
|
||||
var sl = G.lineup[pa.side][pa.slot];
|
||||
var who = pa.who;
|
||||
if(who === undefined){
|
||||
var at = pa.inn * 2 + (pa.half === 'bot' ? 1 : 0);
|
||||
who = -1;
|
||||
sl.subs.forEach(function(sub, si){
|
||||
if(sub.inning * 2 + (sub.half === 'bot' ? 1 : 0) <= at) who = si;
|
||||
});
|
||||
}
|
||||
var p = who >= 0 ? sl.subs[who] : null;
|
||||
return p ? (p.hits = p.hits || mkHits()) : sl.hits;
|
||||
}
|
||||
|
||||
// Add (sign = 1) or remove (sign = -1) a PA's result from every counter.
|
||||
function applyPaStats(pa, sign){
|
||||
var k = paStatKeys(pa.res);
|
||||
var h = paHits(pa);
|
||||
k.bat.forEach(function(key){ h[key] = Math.max(0, (h[key] || 0) + sign); });
|
||||
var fSide = pa.side === 'home' ? 'away' : 'home';
|
||||
var p = G.pitchers[fSide][pa.pIdx] || G.pitchers[fSide][0];
|
||||
k.pit.forEach(function(key){ p[key] = Math.max(0, (p[key] || 0) + sign); });
|
||||
if(k.teamHit) G.rhe[pa.side][1] = Math.max(0, G.rhe[pa.side][1] + sign);
|
||||
if(k.teamErr) G.rhe[fSide][2] = Math.max(0, G.rhe[fSide][2] + sign);
|
||||
}
|
||||
|
||||
// Keep the inning popover's batter list in step: entries are pushed in the
|
||||
// same order as G.pas, so match by position within the half-inning.
|
||||
function paBatterLogIdx(pa){
|
||||
var n = 0;
|
||||
for(var i = 0; i < G.pas.length && G.pas[i] !== pa; i++){
|
||||
var q = G.pas[i];
|
||||
if(q.side === pa.side && q.inn === pa.inn && q.half === pa.half) n++;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
var _peState = null;
|
||||
|
||||
// {idx, t, f, plusE, reached, out}
|
||||
|
||||
function openPaEditor(idx){
|
||||
var pa = G.pas[idx];
|
||||
if(!pa) return;
|
||||
var parts = peParse(pa.res);
|
||||
_peState = {idx:idx, t:parts.t, f:parts.f, plusE:parts.plusE, reached:pa.reached, out:pa.out || 0, risp:pa.risp};
|
||||
renderPaEditor();
|
||||
}
|
||||
|
||||
function closePaEditor(){
|
||||
_peState = null;
|
||||
var el = document.getElementById('peOverlay');
|
||||
if(el) el.remove();
|
||||
}
|
||||
|
||||
function peSet(field, val){
|
||||
if(!_peState) return;
|
||||
var wasOut = paIsOut(peCompose(_peState));
|
||||
_peState[field] = val;
|
||||
if(field === 't'){
|
||||
// Follow the new result with sensible defaults; still adjustable below.
|
||||
var res = peCompose(_peState), isOut = paIsOut(res);
|
||||
if(isOut && !wasOut){ _peState.reached = 0; }
|
||||
else if(!isOut && wasOut){ _peState.reached = paReachFor(res); _peState.out = 0; }
|
||||
}
|
||||
renderPaEditor();
|
||||
haptic(5);
|
||||
}
|
||||
|
||||
function peFieldersInput(el){
|
||||
if(!_peState) return;
|
||||
_peState.f = el.value.replace(/[^\d-]/g, '');
|
||||
var prev = document.getElementById('pePreview');
|
||||
if(prev) prev.innerHTML = 'Scored as <b>' + esc(paLabel(peCompose(_peState))) + '</b>';
|
||||
}
|
||||
|
||||
function renderPaEditor(){
|
||||
if(!_peState) return;
|
||||
var st = _peState, pa = G.pas[st.idx];
|
||||
var ov = document.getElementById('peOverlay');
|
||||
var refocus = document.activeElement && document.activeElement.id === 'peFielders';
|
||||
if(!ov){
|
||||
ov = document.createElement('div');
|
||||
ov.className = 'rp-overlay';
|
||||
ov.id = 'peOverlay';
|
||||
ov.addEventListener('click', function(e){ if(e.target === ov) closePaEditor(); });
|
||||
document.body.appendChild(ov);
|
||||
}
|
||||
var who = curNameForPa(pa);
|
||||
var type = PE_TYPES.filter(function(x){ return x.t === st.t; })[0];
|
||||
var isHit = /^(1B|2B|3B|HR)$/.test(st.t);
|
||||
|
||||
var html = '<div class="rp-modal" role="dialog" aria-modal="true" aria-labelledby="peTitle">';
|
||||
html += '<div class="rp-hdr"><h3 id="peTitle">' + esc(who) + ' <span class="rp-hdr-sub">— ' + (pa.half === 'top' ? 'Top' : 'Bottom') + ' ' + pa.inn + '</span></h3>'
|
||||
+ '<button class="inn-popover-close" style="position:static" onclick="closePaEditor()" aria-label="Close">×</button></div>';
|
||||
html += '<div class="rp-body">';
|
||||
|
||||
html += '<div class="pe-field"><div class="pe-label">Result</div><div class="rp-opts">';
|
||||
PE_TYPES.forEach(function(x){
|
||||
html += '<button class="rp-opt' + (st.t === x.t ? ' sel' : '') + '" onclick="peSet(\'t\',\'' + x.t + '\')">' + esc(x.label || x.t) + '</button>';
|
||||
});
|
||||
html += '</div>';
|
||||
if(type && type.fielders){
|
||||
html += '<div class="pe-fielders"><label for="peFielders">Fielders</label><input id="peFielders" inputmode="numeric" placeholder="' + (st.t === 'G' || st.t === 'FC' ? 'e.g. 6-3' : 'e.g. 8') + '" value="' + esc(st.f) + '" oninput="peFieldersInput(this)" onkeydown="if(event.key===\'Escape\'){event.preventDefault();closePaEditor();}else if(event.key===\'Enter\'){event.preventDefault();savePaEditor();}" /></div>';
|
||||
}
|
||||
if(isHit){
|
||||
html += '<div class="pe-fielders"><button class="rp-opt' + (st.plusE ? ' sel' : '') + '" onclick="peSet(\'plusE\',' + !st.plusE + ')">+ error on the play</button></div>';
|
||||
}
|
||||
html += '<div class="pe-preview" id="pePreview">Scored as <b>' + esc(paLabel(peCompose(st))) + '</b></div></div>';
|
||||
|
||||
html += '<div class="pe-field"><div class="pe-label">Got to</div><div class="rp-opts">';
|
||||
['Didn\'t reach','1st','2nd','3rd','Scored'].forEach(function(lbl, r){
|
||||
html += '<button class="rp-opt' + (st.reached === r ? (r === 4 ? ' sel-score' : ' sel') : '') + '" onclick="peSet(\'reached\',' + r + ')">' + lbl + '</button>';
|
||||
});
|
||||
html += '</div></div>';
|
||||
|
||||
html += '<div class="pe-field"><div class="pe-label">Runner on 2nd or 3rd</div><div class="rp-opts">';
|
||||
[[true, 'Yes'], [false, 'No']].forEach(function(o){
|
||||
html += '<button class="rp-opt' + (st.risp === o[0] ? ' sel' : '') + '" onclick="peSet(\'risp\',' + o[0] + ')">' + o[1] + '</button>';
|
||||
});
|
||||
if(st.risp === undefined) html += '<span class="pe-preview" style="margin:0 0 0 4px;align-self:center">Not recorded</span>';
|
||||
html += '</div></div>';
|
||||
|
||||
html += '<div class="pe-field"><div class="pe-label">Out number</div><div class="rp-opts">';
|
||||
['None','1','2','3'].forEach(function(lbl, o){
|
||||
html += '<button class="rp-opt' + (st.out === o ? (o ? ' sel-out' : ' sel') : '') + '" onclick="peSet(\'out\',' + o + ')">' + lbl + '</button>';
|
||||
});
|
||||
html += '</div></div>';
|
||||
|
||||
html += '<div class="pe-note">Updates the scorecard and the batter/pitcher stats. Runners, outs and runs aren\'t replayed — fix those on the field or with Undo.</div>';
|
||||
html += '<div class="pe-actions"><button class="pe-remove" onclick="removePaFromEditor()">Remove</button>'
|
||||
+ '<button class="pe-cancel" onclick="closePaEditor()">Cancel</button>'
|
||||
+ '<button class="rp-confirm" onclick="savePaEditor()">Save</button></div>';
|
||||
html += '</div></div>';
|
||||
ov.innerHTML = html;
|
||||
|
||||
var f = document.getElementById('peFielders');
|
||||
if(refocus && f){ f.focus(); f.setSelectionRange(f.value.length, f.value.length); }
|
||||
}
|
||||
|
||||
function savePaEditor(){
|
||||
if(!_peState) return;
|
||||
var st = _peState, pa = G.pas[st.idx];
|
||||
var newRes = peCompose(st);
|
||||
var type = PE_TYPES.filter(function(x){ return x.t === st.t; })[0];
|
||||
if(type && type.fielders && !st.f){
|
||||
var f = document.getElementById('peFielders');
|
||||
if(f) f.focus();
|
||||
kbFlash('Enter the fielder(s), e.g. ' + (st.t === 'G' ? '6-3' : '8'), '#BA7517');
|
||||
return;
|
||||
}
|
||||
saveState();
|
||||
if(st.risp !== undefined) pa.risp = st.risp;
|
||||
correctPa(pa, newRes, st.reached, st.out, 'Scorecard edit');
|
||||
closePaEditor();
|
||||
renderAll();
|
||||
saveToStorage();
|
||||
}
|
||||
|
||||
// Change a recorded PA's result / bases / out number, keeping batter, pitcher
|
||||
// and team totals and the inning popover in step. Caller takes the undo
|
||||
// snapshot and re-renders. Shared by the cell editor and the MLB check.
|
||||
function correctPa(pa, newRes, reached, out, logPrefix){
|
||||
var oldRes = pa.res;
|
||||
if(newRes !== oldRes){
|
||||
var bi = paBatterLogIdx(pa);
|
||||
applyPaStats(pa, -1);
|
||||
pa.res = newRes;
|
||||
pa.unearned = newRes[0] === 'E';
|
||||
applyPaStats(pa, 1);
|
||||
var key = (pa.half === 'top' ? 'T' : 'B') + pa.inn;
|
||||
var list = G.batterLog[pa.side][key];
|
||||
if(list && list[bi] !== undefined){
|
||||
var cut = list[bi].lastIndexOf(' — ');
|
||||
if(cut >= 0) list[bi] = list[bi].slice(0, cut + 3) + newRes;
|
||||
}
|
||||
}
|
||||
pa.reached = reached;
|
||||
pa.out = out;
|
||||
if(!out) pa.outOnBases = false;
|
||||
else if(!paIsOut(newRes)) pa.outOnBases = true;
|
||||
addLog(logPrefix + ': ' + curNameForPa(pa) + ' (' + (pa.half === 'top' ? 'T' : 'B') + pa.inn + ') '
|
||||
+ (newRes !== oldRes ? paLabel(oldRes) + ' → ' + paLabel(newRes) : paLabel(newRes) + ' — bases/out corrected'), 'Edit', 't-info');
|
||||
}
|
||||
|
||||
function removePaFromEditor(){
|
||||
if(!_peState) return;
|
||||
saveState();
|
||||
removePa(_peState.idx, 'Scorecard edit');
|
||||
closePaEditor();
|
||||
renderAll();
|
||||
saveToStorage();
|
||||
}
|
||||
|
||||
// Remove a PA and back its result out of every total. Caller snapshots/renders.
|
||||
function removePa(idx, logPrefix){
|
||||
var pa = G.pas[idx];
|
||||
applyPaStats(pa, -1);
|
||||
var bi = paBatterLogIdx(pa);
|
||||
var key = (pa.half === 'top' ? 'T' : 'B') + pa.inn;
|
||||
var list = G.batterLog[pa.side][key];
|
||||
if(list && list[bi] !== undefined) list.splice(bi, 1);
|
||||
G.pas.splice(idx, 1);
|
||||
addLog(logPrefix + ': removed ' + curNameForPa(pa) + ' ' + paLabel(pa.res) + ' (' + (pa.half === 'top' ? 'T' : 'B') + pa.inn + ')', 'Edit', 't-info');
|
||||
}
|
||||
|
||||
function curNameForPa(pa){
|
||||
var sl = G.lineup[pa.side][pa.slot];
|
||||
var h = paHits(pa);
|
||||
for(var si = 0; si < sl.subs.length; si++){ if(sl.subs[si].hits === h) return sl.subs[si].name || 'Sub'; }
|
||||
return sl.name || 'Batter ' + (pa.slot + 1);
|
||||
}
|
||||
|
||||
// One delegated listener for every cell (the grid re-renders constantly)
|
||||
function setupScorecardDelegation(){
|
||||
var wrap = document.getElementById('scorecard');
|
||||
if(!wrap || wrap._peBound) return;
|
||||
wrap._peBound = true;
|
||||
function open(e){
|
||||
var cell = e.target.closest && e.target.closest('.sc-pa[data-pa]');
|
||||
if(!cell) return false;
|
||||
openPaEditor(parseInt(cell.dataset.pa, 10));
|
||||
return true;
|
||||
}
|
||||
wrap.addEventListener('click', open);
|
||||
wrap.addEventListener('keydown', function(e){
|
||||
if((e.key === 'Enter' || e.key === ' ') && open(e)) e.preventDefault();
|
||||
});
|
||||
}
|
||||
|
||||
function showInningPopover(innIdx, evt){
|
||||
hideInningPopover();
|
||||
var innNum = innIdx + 1;
|
||||
var topKey = 'T' + innNum;
|
||||
var botKey = 'B' + innNum;
|
||||
var awaySide = 'away';
|
||||
var homeSide = 'home';
|
||||
var topBatters = G.batterLog[awaySide][topKey] || [];
|
||||
var botBatters = G.batterLog[homeSide][botKey] || [];
|
||||
|
||||
if(topBatters.length === 0 && botBatters.length === 0) return;
|
||||
|
||||
var awayName = team('away');
|
||||
var homeName = team('home');
|
||||
|
||||
var html = '<button class="inn-popover-close" onclick="hideInningPopover()" aria-label="Close">×</button>';
|
||||
html += '<div class="inn-popover-title">Inning ' + innNum + '</div>';
|
||||
|
||||
if(topBatters.length > 0){
|
||||
html += '<div class="inn-popover-half">';
|
||||
html += '<div style="font-size:11px;font-weight:600;color:var(--blue);margin-bottom:2px">▲ ' + awayName + '</div>';
|
||||
topBatters.forEach(function(b){
|
||||
html += '<div class="inn-popover-batter">' + b + '</div>';
|
||||
});
|
||||
html += '</div>';
|
||||
}
|
||||
if(botBatters.length > 0){
|
||||
html += '<div class="inn-popover-half">';
|
||||
html += '<div style="font-size:11px;font-weight:600;color:var(--amber);margin-bottom:2px">▼ ' + homeName + '</div>';
|
||||
botBatters.forEach(function(b){
|
||||
html += '<div class="inn-popover-batter">' + b + '</div>';
|
||||
});
|
||||
html += '</div>';
|
||||
}
|
||||
|
||||
var pop = document.createElement('div');
|
||||
pop.className = 'inn-popover';
|
||||
pop.id = 'innPopover';
|
||||
pop.innerHTML = html;
|
||||
|
||||
// Position near the clicked cell
|
||||
var rect = evt.target.getBoundingClientRect();
|
||||
pop.style.position = 'fixed';
|
||||
pop.style.top = (rect.bottom + 4) + 'px';
|
||||
pop.style.left = Math.max(8, Math.min(rect.left, window.innerWidth - 230)) + 'px';
|
||||
|
||||
document.body.appendChild(pop);
|
||||
|
||||
// Close on outside click
|
||||
setTimeout(function(){
|
||||
document.addEventListener('click', closePopoverOutside);
|
||||
}, 10);
|
||||
}
|
||||
|
||||
function hideInningPopover(){
|
||||
var el = document.getElementById('innPopover');
|
||||
if(el) el.remove();
|
||||
document.removeEventListener('click', closePopoverOutside);
|
||||
}
|
||||
|
||||
function closePopoverOutside(e){
|
||||
var pop = document.getElementById('innPopover');
|
||||
if(pop && !pop.contains(e.target)){
|
||||
hideInningPopover();
|
||||
}
|
||||
}
|
||||
@@ -1,423 +0,0 @@
|
||||
// Sync across devices (Firebase: Firestore + email/password sign-in).
|
||||
// Each device keeps saving locally first; this file mirrors My Games to
|
||||
// users/{uid}/games/{gameId}. Changes are found by fingerprinting each saved
|
||||
// game, uploaded a few seconds after scoring pauses (right away when a game ends
|
||||
// or the app goes to the background), and other devices' changes arrive through
|
||||
// a live listener. If the same game changed on two devices, the newer version
|
||||
// wins and the other is kept in My Games as a copy. The Firebase libraries load
|
||||
// only on devices signed in to sync.
|
||||
|
||||
var SYNC_KEY = 'baseball_scorecard_sync';
|
||||
var SYNC_DELAY_MS = 4000;
|
||||
var SYNC_VENDOR = ['js/vendor/firebase/firebase-app-compat.js', 'js/vendor/firebase/firebase-auth-compat.js', 'js/vendor/firebase/firebase-firestore-compat.js'];
|
||||
var _sync = { ready: false, loading: null, user: null, db: null, unsub: null, timer: null, pushing: false, error: '', lastSync: 0, applying: false };
|
||||
|
||||
// ── Local sync state: per game, what was last uploaded / downloaded ──
|
||||
// One shared object, so concurrent uploads and downloads never overwrite each other's bookkeeping
|
||||
function syncState(){
|
||||
if(_sync.state) return _sync.state;
|
||||
var st = null;
|
||||
try { st = JSON.parse(localStorage.getItem(SYNC_KEY) || 'null'); } catch(e){}
|
||||
st = _sync.state = st || {};
|
||||
st.meta = st.meta || {}; // id → { sig, updatedAt, pushedSig, remoteUpdatedAt }
|
||||
if(!st.device) st.device = syncDefaultDevice();
|
||||
return st;
|
||||
}
|
||||
function syncSaveState(st){ try { localStorage.setItem(SYNC_KEY, JSON.stringify(st)); } catch(e){} }
|
||||
function syncDefaultDevice(){
|
||||
var ua = (navigator.userAgent || '') + ' ' + (navigator.platform || '');
|
||||
if(/iPad/.test(ua) || (/Macintosh/.test(ua) && navigator.maxTouchPoints > 1)) return 'iPad';
|
||||
if(/iPhone/.test(ua)) return 'iPhone';
|
||||
if(/Mac/.test(ua)) return 'Mac';
|
||||
if(/Android/.test(ua)) return 'Android';
|
||||
if(/Win/.test(ua)) return 'Windows';
|
||||
return 'This device';
|
||||
}
|
||||
function syncConfigured(){ return typeof FIREBASE_CONFIG !== 'undefined' && !!FIREBASE_CONFIG && !!FIREBASE_CONFIG.projectId; }
|
||||
|
||||
// Small, stable fingerprint of a saved game (djb2 over its JSON)
|
||||
function syncSig(str){
|
||||
var h = 5381;
|
||||
for(var i = 0; i < str.length; i++) h = ((h << 5) + h + str.charCodeAt(i)) | 0;
|
||||
return str.length + ':' + (h >>> 0).toString(36);
|
||||
}
|
||||
|
||||
// Every local game as { id, raw (payload JSON), entry (My Games summary) }
|
||||
function syncLocalGames(){
|
||||
clearTimeout(_saveTimer);
|
||||
_doSave();
|
||||
var activeId = gmGetActiveId();
|
||||
if(!activeId && G.log.length){ activeId = gmGenId(); gmSetActiveId(activeId); }
|
||||
if(activeId && G.log.length) gmSaveToSlot(activeId);
|
||||
var out = [];
|
||||
gmGetIndex().forEach(function(e){
|
||||
var raw = null;
|
||||
try { raw = localStorage.getItem(GM_GAME_PREFIX + e.id); } catch(x){}
|
||||
if(raw) out.push({ id: e.id, raw: raw, entry: e });
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
// ── Loading Firebase ──
|
||||
function syncLoadScript(src){
|
||||
return new Promise(function(resolve, reject){
|
||||
var s = document.createElement('script');
|
||||
s.src = src; s.onload = resolve; s.onerror = function(){ reject(new Error('Couldn\'t load ' + src)); };
|
||||
document.head.appendChild(s);
|
||||
});
|
||||
}
|
||||
function syncLoadFirebase(){
|
||||
if(window.firebase && firebase.firestore) return Promise.resolve();
|
||||
if(_sync.loading) return _sync.loading;
|
||||
_sync.loading = SYNC_VENDOR.reduce(function(p, src){ return p.then(function(){ return syncLoadScript(src); }); }, Promise.resolve());
|
||||
return _sync.loading;
|
||||
}
|
||||
|
||||
function syncStart(){
|
||||
if(!syncConfigured()) return Promise.resolve(false);
|
||||
return syncLoadFirebase().then(function(){
|
||||
if(!_sync.ready){
|
||||
if(!firebase.apps.length) firebase.initializeApp(FIREBASE_CONFIG);
|
||||
_sync.db = firebase.firestore();
|
||||
try { _sync.db.enablePersistence({ synchronizeTabs: true }).catch(function(){}); } catch(e){}
|
||||
firebase.auth().onAuthStateChanged(syncOnAuth);
|
||||
_sync.ready = true;
|
||||
}
|
||||
return true;
|
||||
}).catch(function(err){ _sync.error = (err && err.message) || 'Sync couldn\'t start.'; renderSyncStatus(); return false; });
|
||||
}
|
||||
|
||||
function syncOnAuth(user){
|
||||
_sync.user = user || null;
|
||||
if(_sync.unsub){ _sync.unsub(); _sync.unsub = null; }
|
||||
var st = syncState();
|
||||
if(user){
|
||||
st.enabled = true; st.email = user.email || st.email; st.uid = user.uid;
|
||||
syncSaveState(st);
|
||||
_sync.unsub = syncGamesRef().onSnapshot(syncOnSnapshot, function(err){ _sync.error = syncErrorText(err); renderSyncStatus(); });
|
||||
syncSoon(0);
|
||||
}
|
||||
renderSyncStatus();
|
||||
renderSyncPanel();
|
||||
}
|
||||
|
||||
function syncGamesRef(){ return _sync.db.collection('users').doc(_sync.user.uid).collection('games'); }
|
||||
|
||||
// ── Upload ──
|
||||
// Called after every save; batches changes a few seconds after scoring pauses
|
||||
function syncSoon(delay){
|
||||
if(!_sync.user) return;
|
||||
clearTimeout(_sync.timer);
|
||||
_sync.timer = setTimeout(syncPush, delay === undefined ? SYNC_DELAY_MS : delay);
|
||||
}
|
||||
|
||||
// Uploads every changed game. `_sync.pushing` only covers the scan (so the saves
|
||||
// it triggers don't reschedule); uploads still waiting on the network don't block
|
||||
// later syncs. Resolves when this round's uploads have reached the server.
|
||||
function syncPush(){
|
||||
if(!_sync.user || _sync.pushing || _sync.applying) return Promise.resolve({ uploaded: 0 });
|
||||
_sync.pushing = true;
|
||||
var st = syncState(), now = Date.now(), jobs = [];
|
||||
var games = syncLocalGames(), here = {};
|
||||
games.forEach(function(g){
|
||||
here[g.id] = true;
|
||||
var m = st.meta[g.id] = st.meta[g.id] || {};
|
||||
var sig = syncSig(g.raw);
|
||||
// updatedAt only ever grows: two edits queued in the same millisecond would
|
||||
// otherwise share a time, and the rules reject the second as not newer
|
||||
if(m.sig !== sig){ m.sig = sig; m.updatedAt = Math.max(now, (m.updatedAt || 0) + 1, (m.remoteUpdatedAt || 0) + 1); }
|
||||
if(m.pushedSig !== sig && m.inflightSig !== sig) jobs.push(syncUpload(g, m, st));
|
||||
});
|
||||
// Games that were synced but are gone here: deleted on this device
|
||||
Object.keys(st.meta).forEach(function(id){
|
||||
var m = st.meta[id];
|
||||
if(here[id] || m.deleted || !m.pushedSig) return;
|
||||
m.deleted = true; m.updatedAt = Math.max(now, (m.remoteUpdatedAt || 0) + 1);
|
||||
jobs.push(syncGamesRef().doc(id).set({ deleted: true, payload: null, updatedAt: m.updatedAt, device: st.device }).then(function(){
|
||||
m.remoteUpdatedAt = m.updatedAt; syncSaveState(st);
|
||||
}).catch(function(){}));
|
||||
});
|
||||
_sync.pushing = false;
|
||||
syncSaveState(st);
|
||||
renderSyncStatus();
|
||||
return Promise.all(jobs).then(function(){
|
||||
_sync.lastSync = Date.now();
|
||||
syncSaveState(st);
|
||||
renderSyncStatus();
|
||||
renderSyncPanel();
|
||||
return { uploaded: jobs.length };
|
||||
}, function(err){ renderSyncStatus(); renderSyncPanel(); throw err; });
|
||||
}
|
||||
|
||||
function syncUpload(g, m, st){
|
||||
var e = g.entry, sig = m.sig;
|
||||
var doc = {
|
||||
payload: g.raw, updatedAt: m.updatedAt, device: st.device, deleted: false,
|
||||
away: e.away || '', home: e.home || '', awayScore: e.awayScore || 0, homeScore: e.homeScore || 0,
|
||||
date: e.date || '', status: e.status || '', plays: e.plays || 0
|
||||
};
|
||||
m.inflightSig = sig;
|
||||
return syncGamesRef().doc(g.id).set(doc).then(function(){
|
||||
m.pushedSig = sig; m.remoteUpdatedAt = m.updatedAt; m.inflightSig = null;
|
||||
_sync.error = '';
|
||||
syncSaveState(st);
|
||||
}).catch(function(err){
|
||||
m.inflightSig = null;
|
||||
if(err && err.code === 'permission-denied'){
|
||||
// A newer version is already in the cloud: keep ours as a copy, take theirs
|
||||
return syncGamesRef().doc(g.id).get().then(function(snap){
|
||||
if(!snap.exists) return;
|
||||
var d = snap.data();
|
||||
if((m.remoteUpdatedAt || 0) >= (d.updatedAt || 0)) return; // the listener already handled it
|
||||
syncKeepCopyThenApply(g.id, d, st);
|
||||
});
|
||||
}
|
||||
_sync.error = syncErrorText(err);
|
||||
});
|
||||
}
|
||||
|
||||
// ── Download ──
|
||||
function syncOnSnapshot(snap){
|
||||
var st = syncState();
|
||||
_sync.cloud = _sync.cloud || {};
|
||||
snap.docChanges().forEach(function(ch){
|
||||
if(ch.type === 'removed') return;
|
||||
var id = ch.doc.id, d = ch.doc.data();
|
||||
_sync.cloud[id] = !d.deleted;
|
||||
if(ch.doc.metadata.hasPendingWrites) return;
|
||||
var m = st.meta[id] = st.meta[id] || {};
|
||||
if((d.updatedAt || 0) <= (m.remoteUpdatedAt || 0)) return; // nothing new
|
||||
var localChanged = m.sig && m.pushedSig !== m.sig;
|
||||
if(localChanged && (m.updatedAt || 0) >= (d.updatedAt || 0)) return; // ours is newer (or this is our own write)
|
||||
if(localChanged) syncKeepCopyThenApply(id, d, st);
|
||||
else syncApplyRemote(id, d, st);
|
||||
});
|
||||
_sync.lastSync = Date.now();
|
||||
syncSaveState(st);
|
||||
renderSyncStatus();
|
||||
renderSyncPanel();
|
||||
}
|
||||
|
||||
// The losing (older) local version becomes a copy in My Games; the cloud version takes its place
|
||||
function syncKeepCopyThenApply(id, d, st){
|
||||
var raw = null;
|
||||
try { raw = localStorage.getItem(GM_GAME_PREFIX + id); } catch(e){}
|
||||
if(raw){
|
||||
var copyId = gmGenId(), payload = JSON.parse(raw);
|
||||
payload.syncCopy = { of: id, device: st.device, at: Date.now() };
|
||||
try { localStorage.setItem(GM_GAME_PREFIX + copyId, JSON.stringify(payload)); } catch(e){}
|
||||
var index = gmGetIndex(), entry = index.filter(function(x){ return x.id === id; })[0] || {};
|
||||
var copyEntry = Object.assign({}, entry, { id: copyId, savedAt: new Date().toISOString() });
|
||||
copyEntry.status = 'Copy (' + st.device + ')';
|
||||
index.unshift(copyEntry);
|
||||
gmSaveIndex(index);
|
||||
kbFlash('Kept this device\'s version as a copy in My Games', '#BA7517');
|
||||
}
|
||||
syncApplyRemote(id, d, st);
|
||||
}
|
||||
|
||||
function syncApplyRemote(id, d, st){
|
||||
var m = st.meta[id] = st.meta[id] || {};
|
||||
_sync.applying = true;
|
||||
try {
|
||||
var index = gmGetIndex().filter(function(x){ return x.id !== id; });
|
||||
if(d.deleted){
|
||||
if(gmGetActiveId() === id){
|
||||
// Open here but deleted elsewhere: keep it open as a new, unsynced game
|
||||
gmSetActiveId(gmGenId());
|
||||
kbFlash('This game was deleted on another device — kept here as a new game', '#BA7517');
|
||||
}
|
||||
try { localStorage.removeItem(GM_GAME_PREFIX + id); } catch(e){}
|
||||
gmSaveIndex(index);
|
||||
m.deleted = true; m.sig = null; m.pushedSig = null;
|
||||
} else {
|
||||
try { localStorage.setItem(GM_GAME_PREFIX + id, d.payload); } catch(e){ warnSaveFailed(); }
|
||||
index.unshift({ id: id, away: d.away, home: d.home, awayScore: d.awayScore, homeScore: d.homeScore,
|
||||
date: d.date, status: d.status, plays: d.plays, savedAt: new Date(d.updatedAt).toISOString() });
|
||||
gmSaveIndex(index);
|
||||
m.sig = m.pushedSig = syncSig(d.payload); m.deleted = false;
|
||||
// The game open here was scored on another device: show its latest state
|
||||
if(gmGetActiveId() === id) gmLoadFromSlot(id);
|
||||
}
|
||||
m.updatedAt = m.remoteUpdatedAt = d.updatedAt || 0;
|
||||
} finally { _sync.applying = false; }
|
||||
if(document.getElementById('gmOverlay')) renderGameManagerContent();
|
||||
}
|
||||
|
||||
function syncErrorText(err){
|
||||
var c = err && err.code;
|
||||
if(c === 'unavailable') return 'Offline — changes will upload when you\'re back online.';
|
||||
if(c === 'permission-denied') return 'The sync database refused the change.';
|
||||
return (err && err.message) || 'Sync error.';
|
||||
}
|
||||
|
||||
// ── Sign in / out ──
|
||||
function syncSignIn(email, password){
|
||||
_sync.error = '';
|
||||
return syncStart().then(function(ok){
|
||||
if(!ok) throw new Error(_sync.error || 'Sync isn\'t set up yet.');
|
||||
return firebase.auth().signInWithEmailAndPassword(email, password);
|
||||
});
|
||||
}
|
||||
function syncSignOut(){
|
||||
var st = syncState();
|
||||
st.enabled = false;
|
||||
syncSaveState(st);
|
||||
if(_sync.ready) return firebase.auth().signOut();
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
// How many games have changes not uploaded yet
|
||||
function syncWaiting(){
|
||||
if(!_sync.user) return 0;
|
||||
var st = syncState(), n = 0;
|
||||
gmGetIndex().forEach(function(e){
|
||||
var raw = null;
|
||||
try { raw = localStorage.getItem(GM_GAME_PREFIX + e.id); } catch(x){}
|
||||
var m = st.meta[e.id];
|
||||
if(raw && (!m || m.pushedSig !== syncSig(raw))) n++;
|
||||
});
|
||||
return n;
|
||||
}
|
||||
|
||||
// Signed in to sync on this device (stays true offline and across restarts)
|
||||
function syncIsOn(){ return syncConfigured() && !!syncState().enabled; }
|
||||
|
||||
// Is this game's saved version already in the cloud? Lets the backup reminder stand down.
|
||||
function syncHasUploaded(id){
|
||||
if(!syncIsOn()) return false;
|
||||
var m = syncState().meta[id], raw = null;
|
||||
if(!m || !m.pushedSig) return false;
|
||||
try { raw = localStorage.getItem(GM_GAME_PREFIX + id); } catch(e){}
|
||||
return !!raw && syncSig(raw) === m.pushedSig;
|
||||
}
|
||||
|
||||
// ── Status pill (header) and Sync panel ──
|
||||
function renderSyncStatus(){
|
||||
renderBackupNudge(); // an upload finishing can settle the backup reminder
|
||||
var el = document.getElementById('syncPill');
|
||||
if(!el) return;
|
||||
var st = syncState();
|
||||
if(!syncConfigured() || !st.enabled){ el.hidden = true; return; }
|
||||
el.hidden = false;
|
||||
var waiting = syncWaiting(), online = navigator.onLine !== false, text, cls = '';
|
||||
if(!_sync.user) { text = '☁ Signing in…'; }
|
||||
else if(!online) { text = '☁ Offline' + (waiting ? ' · ' + waiting + ' waiting' : ''); cls = ' sync-warn'; }
|
||||
else if(_sync.pushing || waiting) { text = '☁ Syncing…'; }
|
||||
else { text = '☁ Synced'; cls = ' sync-ok'; }
|
||||
el.className = 'sync-pill' + cls;
|
||||
el.textContent = text;
|
||||
el.title = _sync.lastSync ? 'Last synced ' + new Date(_sync.lastSync).toLocaleTimeString([], { hour:'numeric', minute:'2-digit' }) : '';
|
||||
}
|
||||
|
||||
function openSyncPanel(){
|
||||
closeSyncPanel();
|
||||
var ov = document.createElement('div');
|
||||
ov.className = 'gm-overlay';
|
||||
ov.id = 'syncOverlay';
|
||||
ov.addEventListener('click', function(e){ if(e.target === ov) closeSyncPanel(); });
|
||||
document.body.appendChild(ov);
|
||||
renderSyncPanel();
|
||||
if(syncConfigured() && syncState().enabled) syncStart();
|
||||
}
|
||||
function closeSyncPanel(){ var ov = document.getElementById('syncOverlay'); if(ov) ov.remove(); }
|
||||
|
||||
function renderSyncPanel(){
|
||||
var ov = document.getElementById('syncOverlay');
|
||||
if(!ov) return;
|
||||
var st = syncState(), html = '<div class="gm-modal sync-modal" role="dialog" aria-modal="true" aria-labelledby="syncTitle">';
|
||||
html += '<div class="gm-hdr"><h3 id="syncTitle">☁ Sync</h3><button class="games-modal-close" onclick="closeSyncPanel()" aria-label="Close">×</button></div><div class="gm-body sync-body">';
|
||||
if(!syncConfigured()){
|
||||
html += '<p>Sync isn\'t set up for this app yet.</p>';
|
||||
} else if(_sync.user){
|
||||
var waiting = syncWaiting();
|
||||
var local = gmGetIndex().length, cloud = Object.keys(_sync.cloud || {}).filter(function(k){ return _sync.cloud[k]; }).length;
|
||||
html += '<p class="sync-line"><b>Signed in</b> as ' + esc(_sync.user.email || st.email || '') + '</p>'
|
||||
+ '<p class="sync-line">On this device: <b>' + local + '</b> game' + (local === 1 ? '' : 's') + ' · In the cloud: <b>' + cloud + '</b></p>'
|
||||
+ '<p class="sync-line">' + (waiting ? waiting + ' game' + (waiting === 1 ? '' : 's') + ' waiting to upload' : 'Everything on this device is uploaded')
|
||||
+ (_sync.lastSync ? ' · last synced ' + new Date(_sync.lastSync).toLocaleTimeString([], { hour:'numeric', minute:'2-digit' }) : '') + '</p>'
|
||||
+ (_sync.nowMsg ? '<p class="sync-ok-msg">' + esc(_sync.nowMsg) + '</p>' : '')
|
||||
+ (_sync.error ? '<p class="sync-err">' + esc(_sync.error) + '</p>' : '')
|
||||
+ '<label class="sync-field">This device\'s name <input id="syncDevice" value="' + esc(st.device) + '" onchange="syncRenameDevice(this.value)" /></label>'
|
||||
+ '<p class="sync-note">Games scored on any signed-in device show up in My Games and season stats everywhere. If the same game changes on two devices, the newer version wins and the other is kept as a copy.</p>'
|
||||
+ '<div class="pe-actions"><button class="pe-cancel" onclick="syncSignOut()">Sign out</button><button class="rp-confirm" id="syncNowBtn" onclick="syncNow()"' + (_sync.busyNow ? ' disabled' : '') + '>' + (_sync.busyNow ? 'Syncing…' : 'Sync now') + '</button></div>';
|
||||
} else {
|
||||
html += '<p class="sync-note">Sign in to keep My Games, season stats and backups the same on all your devices.</p>'
|
||||
+ '<form onsubmit="event.preventDefault(); syncSubmitSignIn();" class="sync-form">'
|
||||
+ '<label class="sync-field">Email <input id="syncEmail" type="email" autocomplete="username" required value="' + esc(st.email || '') + '" /></label>'
|
||||
+ '<label class="sync-field">Password <input id="syncPassword" type="password" autocomplete="current-password" required /></label>'
|
||||
+ (_sync.error ? '<p class="sync-err">' + esc(_sync.error) + '</p>' : '')
|
||||
+ '<div class="pe-actions"><button type="button" class="pe-cancel" onclick="closeSyncPanel()">Cancel</button><button type="submit" class="rp-confirm" id="syncSignInBtn">Sign in</button></div></form>';
|
||||
}
|
||||
html += '</div></div>';
|
||||
ov.innerHTML = html;
|
||||
}
|
||||
|
||||
// "Sync now": upload changes and say what happened (or that uploads are still queued)
|
||||
function syncNow(){
|
||||
if(_sync.busyNow) return;
|
||||
_sync.busyNow = true; _sync.nowMsg = ''; _sync.error = '';
|
||||
renderSyncPanel();
|
||||
var done = false;
|
||||
var finish = function(msg, err){
|
||||
if(done) return; done = true;
|
||||
_sync.busyNow = false;
|
||||
_sync.nowMsg = msg || '';
|
||||
if(err) _sync.error = err;
|
||||
renderSyncStatus(); renderSyncPanel();
|
||||
};
|
||||
setTimeout(function(){ finish('', 'Still uploading — the connection is slow. Uploads are queued and will finish on their own.'); }, 12000);
|
||||
syncPush().then(function(r){
|
||||
var t = new Date().toLocaleTimeString([], { hour:'numeric', minute:'2-digit' });
|
||||
var n = (r && r.uploaded) || 0;
|
||||
finish('✓ Synced at ' + t + (n ? ' — ' + n + ' game' + (n === 1 ? '' : 's') + ' uploaded' : ' — nothing new to upload'));
|
||||
}, function(err){ finish('', syncErrorText(err)); });
|
||||
}
|
||||
|
||||
function syncSubmitSignIn(){
|
||||
var email = (document.getElementById('syncEmail') || {}).value || '', pw = (document.getElementById('syncPassword') || {}).value || '';
|
||||
var btn = document.getElementById('syncSignInBtn');
|
||||
if(btn){ btn.disabled = true; btn.textContent = 'Signing in…'; }
|
||||
syncSignIn(email.trim(), pw).catch(function(err){
|
||||
var c = err && err.code;
|
||||
_sync.error = c === 'auth/invalid-credential' || c === 'auth/wrong-password' || c === 'auth/user-not-found' ? 'That email and password don\'t match.'
|
||||
: c === 'auth/network-request-failed' ? 'Couldn\'t reach the sign-in server — check your connection.'
|
||||
: (err && err.message) || 'Couldn\'t sign in.';
|
||||
renderSyncPanel();
|
||||
});
|
||||
}
|
||||
|
||||
function syncRenameDevice(name){
|
||||
var st = syncState();
|
||||
st.device = (name || '').trim() || syncDefaultDevice();
|
||||
syncSaveState(st);
|
||||
}
|
||||
|
||||
// ── Hooks ──
|
||||
// Every save schedules a sync; leaving the app or finishing a game syncs now
|
||||
var _syncOrigDoSave = _doSave;
|
||||
_doSave = function(){
|
||||
_syncOrigDoSave();
|
||||
// Saves made by sync itself (uploading, applying another device's change) don't reschedule
|
||||
if(!_sync.user || _sync.applying || _sync.pushing) return;
|
||||
var id = gmGetActiveId();
|
||||
if(id && id !== _sync.finalSent && G.log.some(function(l){ return l.tag === 'Final'; })){
|
||||
_sync.finalSent = id; // game just ended: upload now
|
||||
syncSoon(0);
|
||||
} else {
|
||||
syncSoon();
|
||||
}
|
||||
};
|
||||
var _syncOrigDeleteSlot = gmDeleteSlot;
|
||||
gmDeleteSlot = function(id){ _syncOrigDeleteSlot(id); syncSoon(); };
|
||||
|
||||
function syncInit(){
|
||||
if(_sync.inited) return;
|
||||
_sync.inited = true;
|
||||
document.addEventListener('visibilitychange', function(){ if(document.visibilityState === 'hidden' && _sync.user) syncPush(); });
|
||||
window.addEventListener('online', function(){ renderSyncStatus(); syncSoon(0); });
|
||||
window.addEventListener('offline', renderSyncStatus);
|
||||
renderSyncStatus();
|
||||
// Signed-in devices start syncing in the background once the scorecard is up
|
||||
if(syncConfigured() && syncState().enabled) setTimeout(syncStart, 0);
|
||||
}
|
||||
@@ -1,462 +0,0 @@
|
||||
// App shell: dialogs, keyboard shortcuts, event delegation, wake lock, and startup (loads last).
|
||||
// Loaded as a plain script; files share one global scope (see index.html for the order).
|
||||
|
||||
// ── Custom confirm / alert modals ──
|
||||
// Replaces native alert()/confirm() which steal focus and look jarring on iOS.
|
||||
// showConfirm returns Promise<boolean>; showAlert returns Promise<void>.
|
||||
// opts: { title, message, confirmLabel, cancelLabel, tone: 'warn'|'danger'|'info' }
|
||||
|
||||
function _cfClose(overlay, resolve, value){
|
||||
if(!overlay || !overlay.parentNode) return;
|
||||
document.removeEventListener('keydown', overlay._kbHandler, true);
|
||||
overlay.parentNode.removeChild(overlay);
|
||||
if(resolve) resolve(value);
|
||||
}
|
||||
|
||||
function _cfBuild(opts, onResolve){
|
||||
var tone = opts.tone || 'warn';
|
||||
var icon = tone === 'danger' ? '⚠' : tone === 'info' ? 'ⓘ' : '?';
|
||||
var title = esc(opts.title || '');
|
||||
var message = esc(opts.message || '').replace(/\n/g, '<br>');
|
||||
var confirmLabel = esc(opts.confirmLabel || 'OK');
|
||||
var cancelLabel = opts.cancelLabel === null ? null : esc(opts.cancelLabel || 'Cancel');
|
||||
var confirmClass = tone === 'danger' ? 'danger' : 'primary';
|
||||
|
||||
var overlay = document.createElement('div');
|
||||
overlay.className = 'cf-overlay';
|
||||
|
||||
var html = '<div class="cf-modal" role="dialog" aria-modal="true">';
|
||||
if(title){
|
||||
html += '<div class="cf-hdr">'
|
||||
+ '<div class="cf-icon ' + tone + '">' + icon + '</div>'
|
||||
+ '<div class="cf-title">' + title + '</div>'
|
||||
+ '</div>';
|
||||
}
|
||||
html += '<div class="cf-body' + (title ? ' with-icon' : '') + '">' + message + '</div>';
|
||||
html += '<div class="cf-btns">';
|
||||
if(cancelLabel !== null){
|
||||
html += '<button type="button" class="cf-btn" data-cf="cancel">' + cancelLabel + '</button>';
|
||||
}
|
||||
html += '<button type="button" class="cf-btn ' + confirmClass + '" data-cf="confirm">' + confirmLabel + '</button>';
|
||||
html += '</div></div>';
|
||||
overlay.innerHTML = html;
|
||||
|
||||
overlay.addEventListener('click', function(e){
|
||||
if(e.target === overlay){
|
||||
// Backdrop click = cancel (or OK if alert-only)
|
||||
_cfClose(overlay, onResolve, cancelLabel === null ? true : false);
|
||||
} else if(e.target.dataset && e.target.dataset.cf){
|
||||
_cfClose(overlay, onResolve, e.target.dataset.cf === 'confirm');
|
||||
}
|
||||
});
|
||||
|
||||
overlay._kbHandler = function(e){
|
||||
if(e.key === 'Escape'){
|
||||
e.preventDefault(); e.stopPropagation();
|
||||
_cfClose(overlay, onResolve, cancelLabel === null ? true : false);
|
||||
} else if(e.key === 'Enter'){
|
||||
e.preventDefault(); e.stopPropagation();
|
||||
_cfClose(overlay, onResolve, true);
|
||||
}
|
||||
};
|
||||
document.addEventListener('keydown', overlay._kbHandler, true);
|
||||
|
||||
document.body.appendChild(overlay);
|
||||
|
||||
// Focus the primary button for keyboard users
|
||||
setTimeout(function(){
|
||||
var btn = overlay.querySelector('[data-cf="confirm"]');
|
||||
if(btn) btn.focus();
|
||||
}, 0);
|
||||
|
||||
return overlay;
|
||||
}
|
||||
|
||||
function showConfirm(opts){
|
||||
return new Promise(function(resolve){
|
||||
_cfBuild(opts || {}, resolve);
|
||||
});
|
||||
}
|
||||
|
||||
function showAlert(opts){
|
||||
// opts can be a string for convenience
|
||||
if(typeof opts === 'string') opts = { message: opts };
|
||||
opts = opts || {};
|
||||
opts.cancelLabel = null;
|
||||
opts.confirmLabel = opts.confirmLabel || 'OK';
|
||||
opts.tone = opts.tone || 'info';
|
||||
return new Promise(function(resolve){
|
||||
_cfBuild(opts, function(){ resolve(); });
|
||||
});
|
||||
}
|
||||
|
||||
// ── Keyboard shortcuts ──
|
||||
var kbFlashTimer = null;
|
||||
|
||||
function kbFlash(msg, color){
|
||||
var el = document.getElementById('kbFlash');
|
||||
if(!el) return;
|
||||
el.textContent = msg;
|
||||
if(color) el.style.background = color;
|
||||
else el.style.background = '';
|
||||
el.classList.add('show');
|
||||
clearTimeout(kbFlashTimer);
|
||||
kbFlashTimer = setTimeout(function(){ el.classList.remove('show'); }, 900);
|
||||
}
|
||||
|
||||
function isEditing(){
|
||||
var ae = document.activeElement;
|
||||
if(!ae) return false;
|
||||
var tag = ae.tagName;
|
||||
return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || ae.isContentEditable;
|
||||
}
|
||||
|
||||
document.addEventListener('keydown', function(e){
|
||||
// Don't intercept when typing in inputs/selects
|
||||
if(isEditing()) return;
|
||||
// Don't intercept if a modal is open (except Escape to close it)
|
||||
if(document.getElementById('gamesOverlay')){
|
||||
if(e.key === 'Escape') closeTodaysGames();
|
||||
return;
|
||||
}
|
||||
if(document.getElementById('kbOverlay')){
|
||||
if(e.key === 'Escape') closeKBHelp();
|
||||
return;
|
||||
}
|
||||
if(document.getElementById('gmOverlay')){
|
||||
if(e.key === 'Escape') closeGameManager();
|
||||
return;
|
||||
}
|
||||
if(document.getElementById('peOverlay')){
|
||||
if(e.key === 'Escape') closePaEditor();
|
||||
return;
|
||||
}
|
||||
if(document.getElementById('pleOverlay')){
|
||||
if(e.key === 'Escape') closePitchLineEditor();
|
||||
return;
|
||||
}
|
||||
if(document.getElementById('mlbOverlay')){
|
||||
if(e.key === 'Escape') closeMlbCheck();
|
||||
return;
|
||||
}
|
||||
if(document.getElementById('sfOverlay')){
|
||||
if(e.key === 'Escape') closeShareFinal();
|
||||
return;
|
||||
}
|
||||
if(document.getElementById('ssOverlay')){
|
||||
if(e.key === 'Escape') closeSeasonStats();
|
||||
return;
|
||||
}
|
||||
if(document.getElementById('syncOverlay')){
|
||||
if(e.key === 'Escape') closeSyncPanel();
|
||||
return;
|
||||
}
|
||||
// If runner placement picker is open, only allow Escape (auto-advance)
|
||||
if(document.getElementById('rpOverlay')){
|
||||
if(e.key === 'Escape'){ rpAutoAdvance(); }
|
||||
return;
|
||||
}
|
||||
|
||||
var key = e.key.toLowerCase();
|
||||
var shift = e.shiftKey;
|
||||
|
||||
// ── Count ──
|
||||
if(key === 'b' && !shift){ e.preventDefault(); addBall(); kbFlash('Ball ' + G.balls, '#1D9E75'); return; }
|
||||
if(key === 's' && !shift){ e.preventDefault(); addStrike(); kbFlash('Strike', '#E24B4A'); return; }
|
||||
if(key === 'f' && !shift){ e.preventDefault(); addFoul(); kbFlash('Foul', '#534AB7'); return; }
|
||||
|
||||
// ── Hits ──
|
||||
if(key === '1' && !shift){ e.preventDefault(); recordHit(1); kbFlash('Single', '#0F6E56'); return; }
|
||||
if(key === '2' && !shift){ e.preventDefault(); recordHit(2); kbFlash('Double', '#185FA5'); return; }
|
||||
if(key === '3' && !shift){ e.preventDefault(); recordHit(3); kbFlash('Triple', '#534AB7'); return; }
|
||||
if(key === '4' && !shift){ e.preventDefault(); recordHit(4); kbFlash('Home Run!', '#E24B4A'); return; }
|
||||
|
||||
// ── Strikeouts ──
|
||||
if(key === 'k' && !shift){ e.preventDefault(); recordKO('swinging'); kbFlash('K Swinging', '#E24B4A'); return; }
|
||||
if(key === 'k' && shift){ e.preventDefault(); recordKO('looking'); kbFlash('ꓘ Looking', '#993C1D'); return; }
|
||||
|
||||
// ── Outs / special ──
|
||||
if(key === 'o' && !shift){ e.preventDefault(); manualOut(); kbFlash('Out ' + G.outs); return; }
|
||||
if(key === 'w' && !shift){ e.preventDefault(); recordHBP(); kbFlash('HBP', '#BA7517'); return; }
|
||||
if(key === 'w' && shift){ e.preventDefault(); recordIBB(); kbFlash('IBB', '#0F6E56'); return; }
|
||||
if(key === 'c' && shift){ e.preventDefault(); recordCI(); kbFlash('CI — catcher\'s interference', '#BA7517'); return; }
|
||||
|
||||
// ── Baserunning ──
|
||||
if(key === 'r' && !shift){ e.preventDefault(); addRun(); kbFlash('Run +1', '#185FA5'); return; }
|
||||
|
||||
// ── Undo ──
|
||||
if(key === 'z' && (e.ctrlKey || e.metaKey)){ e.preventDefault(); undoAction(); kbFlash('Undo'); return; }
|
||||
if(key === 'u' && !shift){ e.preventDefault(); undoAction(); kbFlash('Undo'); return; }
|
||||
|
||||
// ── Inning navigation ──
|
||||
if(key === 'arrowleft'){ e.preventDefault(); changeInning(-1); kbFlash('← Inn ' + G.inning); return; }
|
||||
if(key === 'arrowright'){ e.preventDefault(); changeInning(1); kbFlash('→ Inn ' + G.inning); return; }
|
||||
if(key === 'h' && !shift){ e.preventDefault(); toggleHalf(); var hLabel = G.half==='top'?'Top':'Bot'; kbFlash(hLabel + ' ' + G.inning); return; }
|
||||
|
||||
// ── Help ──
|
||||
if(key === '?' || (key === '/' && shift)){ e.preventDefault(); toggleKBHelp(); return; }
|
||||
if(key === 'escape'){ closeKBHelp(); closeRunnerPicker(); return; }
|
||||
});
|
||||
|
||||
function toggleKBHelp(){
|
||||
if(document.getElementById('kbOverlay')) { closeKBHelp(); return; }
|
||||
var overlay = document.createElement('div');
|
||||
overlay.className = 'kb-overlay';
|
||||
overlay.id = 'kbOverlay';
|
||||
overlay.onclick = function(e){ if(e.target === overlay) closeKBHelp(); };
|
||||
|
||||
var html = '<div class="kb-modal">'
|
||||
+ '<div class="kb-modal-hdr"><h3>⌨ Keyboard Shortcuts</h3><button class="kb-modal-close" onclick="closeKBHelp()" aria-label="Close">×</button></div>'
|
||||
+ '<div class="kb-modal-body">';
|
||||
|
||||
html += '<div class="kb-section"><div class="kb-section-title">Pitch Count</div>'
|
||||
+ '<div class="kb-row"><span>Ball</span><span class="kb-key">B</span></div>'
|
||||
+ '<div class="kb-row"><span>Strike</span><span class="kb-key">S</span></div>'
|
||||
+ '<div class="kb-row"><span>Foul</span><span class="kb-key">F</span></div>'
|
||||
+ '</div>';
|
||||
|
||||
html += '<div class="kb-section"><div class="kb-section-title">Hits</div>'
|
||||
+ '<div class="kb-row"><span>Single</span><span class="kb-key">1</span></div>'
|
||||
+ '<div class="kb-row"><span>Double</span><span class="kb-key">2</span></div>'
|
||||
+ '<div class="kb-row"><span>Triple</span><span class="kb-key">3</span></div>'
|
||||
+ '<div class="kb-row"><span>Home Run</span><span class="kb-key">4</span></div>'
|
||||
+ '</div>';
|
||||
|
||||
html += '<div class="kb-section"><div class="kb-section-title">Strikeouts</div>'
|
||||
+ '<div class="kb-row"><span>Strikeout swinging</span><span class="kb-key">K</span></div>'
|
||||
+ '<div class="kb-row"><span>Strikeout looking</span><span><span class="kb-key">Shift</span><span class="kb-key">K</span></span></div>'
|
||||
+ '</div>';
|
||||
|
||||
html += '<div class="kb-section"><div class="kb-section-title">Outs & Baserunning</div>'
|
||||
+ '<div class="kb-row"><span>Record out</span><span class="kb-key">O</span></div>'
|
||||
+ '<div class="kb-row"><span>Add run</span><span class="kb-key">R</span></div>'
|
||||
+ '<div class="kb-row"><span>Hit by pitch</span><span class="kb-key">W</span></div>'
|
||||
+ '<div class="kb-row"><span>Intentional walk</span><span><span class="kb-key">Shift</span><span class="kb-key">W</span></span></div>'
|
||||
+ '<div class="kb-row"><span>Catcher\'s interference</span><span><span class="kb-key">Shift</span><span class="kb-key">C</span></span></div>'
|
||||
+ '</div>';
|
||||
|
||||
html += '<div class="kb-section"><div class="kb-section-title">Navigation</div>'
|
||||
+ '<div class="kb-row"><span>Previous inning</span><span class="kb-key">←</span></div>'
|
||||
+ '<div class="kb-row"><span>Next inning</span><span class="kb-key">→</span></div>'
|
||||
+ '<div class="kb-row"><span>Switch half</span><span class="kb-key">H</span></div>'
|
||||
+ '<div class="kb-row"><span>Undo</span><span><span class="kb-key">U</span> or <span class="kb-key">Ctrl</span><span class="kb-key">Z</span></span></div>'
|
||||
+ '<div class="kb-row"><span>This help</span><span class="kb-key">?</span></div>'
|
||||
+ '</div>';
|
||||
|
||||
html += '</div></div>';
|
||||
overlay.innerHTML = html;
|
||||
document.body.appendChild(overlay);
|
||||
focusModalClose(overlay, '.kb-modal-close');
|
||||
}
|
||||
|
||||
function closeKBHelp(){
|
||||
var el = document.getElementById('kbOverlay');
|
||||
if(el) el.remove();
|
||||
}
|
||||
|
||||
// ── Event delegation ──
|
||||
// Single click/change handlers on container elements instead of per-element inline handlers.
|
||||
|
||||
function findAction(el, container){
|
||||
// Walk up from the clicked element to find the nearest data-action
|
||||
while(el && el !== container){
|
||||
if(el.dataset && el.dataset.action) return el;
|
||||
el = el.parentElement;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// init() runs again after Reset game, so each setup binds only once —
|
||||
// otherwise every tap fires twice (e.g. "Add pitcher" adding two).
|
||||
function setupLineupDelegation(side){
|
||||
var panel = document.getElementById(side+'Lineup');
|
||||
if(!panel || panel._bound) return;
|
||||
panel._bound = true;
|
||||
panel.addEventListener('click', function(e){
|
||||
var el = findAction(e.target, panel);
|
||||
if(!el) return;
|
||||
var act = el.dataset.action;
|
||||
var idx = parseInt(el.dataset.idx);
|
||||
if(act === 'at-bat') setAtBat(side, idx);
|
||||
else if(act === 'start-sub') startSub(side, idx);
|
||||
else if(act === 'confirm-sub') confirmSub(side, idx, el.dataset.subtype || 'ph');
|
||||
else if(act === 'cancel-sub') cancelSub(side, idx);
|
||||
});
|
||||
panel.addEventListener('change', function(e){
|
||||
var el = e.target;
|
||||
if(!el.dataset || !el.dataset.action) return;
|
||||
var act = el.dataset.action;
|
||||
var idx = parseInt(el.dataset.idx);
|
||||
if(act === 'set-pos') G.lineup[side][idx].pos = el.value;
|
||||
else if(act === 'set-name') G.lineup[side][idx].name = el.value;
|
||||
else if(act === 'select-player') onPlayerSelect(side, idx, el.value);
|
||||
else if(act === 'set-sub-pos') G.lineup[side][idx].subs[parseInt(el.dataset.sub)].pos = el.value;
|
||||
else if(act === 'set-sub-name') G.lineup[side][idx].subs[parseInt(el.dataset.sub)].name = el.value;
|
||||
saveToStorage();
|
||||
});
|
||||
}
|
||||
|
||||
function setupPitcherDelegation(side){
|
||||
var panel = document.getElementById(side+'PitcherPanel');
|
||||
if(!panel || panel._bound) return;
|
||||
panel._bound = true;
|
||||
panel.addEventListener('click', function(e){
|
||||
var el = findAction(e.target, panel);
|
||||
if(!el) return;
|
||||
var act = el.dataset.action;
|
||||
var pidx = parseInt(el.dataset.pidx);
|
||||
// Stop propagation from inputs/selects to prevent set-active-p firing
|
||||
if(act === 'set-p-name' || act === 'adj-p' || act === 'add-p' || act === 'edit-p-line') e.stopPropagation();
|
||||
if(act === 'edit-p-line') openPitchLineEditor(el.dataset.side, pidx);
|
||||
else if(act === 'set-active-p') setActivePitcher(el.dataset.side, pidx);
|
||||
else if(act === 'adj-p') adj(el.dataset.side, pidx, parseInt(el.dataset.dir));
|
||||
else if(act === 'add-p') addPitcher(el.dataset.side);
|
||||
});
|
||||
panel.addEventListener('keydown', function(e){
|
||||
var el = e.target;
|
||||
if((e.key === 'Enter' || e.key === ' ') && el.dataset && el.dataset.action === 'edit-p-line'){
|
||||
e.preventDefault();
|
||||
openPitchLineEditor(el.dataset.side, parseInt(el.dataset.pidx));
|
||||
}
|
||||
});
|
||||
panel.addEventListener('change', function(e){
|
||||
var el = e.target;
|
||||
if(!el.dataset || el.dataset.action !== 'set-p-name') return;
|
||||
var s = el.dataset.side;
|
||||
var pidx = parseInt(el.dataset.pidx);
|
||||
G.pitchers[s][pidx].name = el.value;
|
||||
renderPitchers(s);
|
||||
saveToStorage();
|
||||
});
|
||||
}
|
||||
|
||||
function setupFielderDelegation(){
|
||||
var fg = document.getElementById('fielderGrid');
|
||||
if(!fg || fg._bound) return;
|
||||
fg._bound = true;
|
||||
fg.addEventListener('click', function(e){
|
||||
var el = findAction(e.target, fg);
|
||||
if(!el || el.dataset.action !== 'sel-fielder') return;
|
||||
selectFielder(parseInt(el.dataset.num));
|
||||
});
|
||||
var tg = document.getElementById('throwToGrid');
|
||||
if(tg) tg.addEventListener('click', function(e){
|
||||
var el = findAction(e.target, tg);
|
||||
if(!el || el.dataset.action !== 'sel-throwto') return;
|
||||
selectThrowTo(parseInt(el.dataset.num));
|
||||
});
|
||||
}
|
||||
|
||||
// ── Screen wake lock: keep the screen on while a game is being scored ──
|
||||
// (iOS Safari 16.4+; silently does nothing where unsupported)
|
||||
var _wakeLock = null;
|
||||
|
||||
function acquireWakeLock(){
|
||||
if(!('wakeLock' in navigator)) return;
|
||||
if(document.visibilityState !== 'visible') return;
|
||||
if(_wakeLock) return;
|
||||
navigator.wakeLock.request('screen').then(function(lock){
|
||||
_wakeLock = lock;
|
||||
lock.addEventListener('release', function(){ _wakeLock = null; });
|
||||
}).catch(function(){ _wakeLock = null; });
|
||||
}
|
||||
|
||||
function releaseWakeLock(){
|
||||
if(_wakeLock){ _wakeLock.release().catch(function(){}); _wakeLock = null; }
|
||||
}
|
||||
|
||||
// Hold the lock while the game is live, drop it once it's final.
|
||||
// Called from _doSave, which runs after every state change.
|
||||
function syncWakeLock(){
|
||||
if(isGameOver()) releaseWakeLock();
|
||||
else acquireWakeLock();
|
||||
}
|
||||
|
||||
// The OS releases the lock whenever the app is backgrounded; re-acquire on return.
|
||||
document.addEventListener('visibilitychange', function(){
|
||||
if(document.visibilityState === 'visible') syncWakeLock();
|
||||
});
|
||||
|
||||
// Dark mode: show MLB's dark-background team logos (several regular ones are navy
|
||||
// or black). Applied to the page's images as they appear, so logos drawn anywhere
|
||||
// follow along; printing switches back to the regular ones for white paper.
|
||||
// (League and postseason logos have other paths and are left alone.)
|
||||
var LOGO_RE = /^(https:\/\/www\.mlbstatic\.com\/team-logos\/)(team-cap-on-dark\/)?(\d+\.svg)$/;
|
||||
var _logoPrinting = false;
|
||||
|
||||
function logoDarkWanted(){
|
||||
return !_logoPrinting && !!(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches);
|
||||
}
|
||||
|
||||
function fixLogo(img){
|
||||
var m = LOGO_RE.exec(img.getAttribute('src') || '');
|
||||
if(!m) return;
|
||||
var want = m[1] + (logoDarkWanted() ? 'team-cap-on-dark/' : '') + m[3];
|
||||
if(img.getAttribute('src') !== want) img.setAttribute('src', want);
|
||||
}
|
||||
|
||||
function fixLogosIn(root){
|
||||
if(root.tagName === 'IMG') fixLogo(root);
|
||||
if(root.querySelectorAll) Array.prototype.forEach.call(root.querySelectorAll('img'), fixLogo);
|
||||
}
|
||||
|
||||
function setupDarkLogos(){
|
||||
fixLogosIn(document.body);
|
||||
if(window.MutationObserver){
|
||||
new MutationObserver(function(muts){
|
||||
muts.forEach(function(m){
|
||||
if(m.type === 'attributes') fixLogo(m.target);
|
||||
else Array.prototype.forEach.call(m.addedNodes, function(n){ if(n.nodeType === 1) fixLogosIn(n); });
|
||||
});
|
||||
}).observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['src'] });
|
||||
}
|
||||
var mq = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)');
|
||||
if(mq && mq.addEventListener) mq.addEventListener('change', function(){ fixLogosIn(document.body); });
|
||||
window.addEventListener('beforeprint', function(){ _logoPrinting = true; fixLogosIn(document.body); });
|
||||
window.addEventListener('afterprint', function(){ _logoPrinting = false; fixLogosIn(document.body); });
|
||||
}
|
||||
|
||||
function init(){
|
||||
setupDarkLogos();
|
||||
populateTeamDropdowns();
|
||||
// Set up event delegation (once — containers are stable, only innerHTML changes)
|
||||
setupLineupDelegation('home');
|
||||
setupLineupDelegation('away');
|
||||
setupPitcherDelegation('home');
|
||||
setupPitcherDelegation('away');
|
||||
setupFielderDelegation();
|
||||
setupInfieldDelegation();
|
||||
// Migrate existing save data to multi-game system if needed
|
||||
gmEnsureActiveId();
|
||||
var restored = loadFromStorage();
|
||||
if(restored){
|
||||
// Re-fire team change to reload logos, rosters, stadium
|
||||
var away = document.getElementById('teamAway').value;
|
||||
var home = document.getElementById('teamHome').value;
|
||||
if(away && away !== '— Select Team —')fetchRoster('away', away);
|
||||
if(home && home !== '— Select Team —'){ fetchRoster('home', home); renderStadium(home); }
|
||||
onTeamChange();
|
||||
}
|
||||
renderAll();
|
||||
followInit();
|
||||
autoFillDate();
|
||||
restoreNotes();
|
||||
syncWakeLock();
|
||||
renderBackupNudge();
|
||||
syncInit();
|
||||
}
|
||||
|
||||
init();
|
||||
|
||||
// Ask the browser not to clear this site's storage on its own (iOS may evict
|
||||
// data from apps that go unused). Best effort — backups are still the safety net.
|
||||
if(navigator.storage && navigator.storage.persist){
|
||||
navigator.storage.persisted()
|
||||
.then(function(p){ return p || navigator.storage.persist(); })
|
||||
.catch(function(){});
|
||||
}
|
||||
|
||||
// Offline support: cache the app so it opens with no signal (e.g. at the ballpark).
|
||||
if('serviceWorker' in navigator){
|
||||
navigator.serviceWorker.register('sw.js').catch(function(){});
|
||||
}
|
||||
@@ -1,257 +0,0 @@
|
||||
This source code is licensed under Apache-2.0 apart from the protobuf library
|
||||
which is licensed under BSD-3-Clause, both licenses given below.
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
-------------------------------------------------------------------------------
|
||||
|
||||
For tslib.
|
||||
|
||||
file: [source code root]/packages/firebase
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||
PERFORMANCE OF THIS SOFTWARE.
|
||||
|
||||
------------------------------------------------------------------------------
|
||||
|
||||
For Google protobuf source.
|
||||
|
||||
file: [source code root]/packages/firestore/src/protos/google/protobuf/any.proto
|
||||
|
||||
// Protocol Buffers - Google's data interchange format
|
||||
// Copyright 2008 Google Inc. All rights reserved.
|
||||
// https://developers.google.com/protocol-buffers/
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are
|
||||
// met:
|
||||
//
|
||||
// * Redistributions of source code must retain the above copyright
|
||||
// notice, this list of conditions and the following disclaimer.
|
||||
// * Redistributions in binary form must reproduce the above
|
||||
// copyright notice, this list of conditions and the following disclaimer
|
||||
// in the documentation and/or other materials provided with the
|
||||
// distribution.
|
||||
// * Neither the name of Google Inc. nor the names of its
|
||||
// contributors may be used to endorse or promote products derived from
|
||||
// this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
@@ -1,9 +0,0 @@
|
||||
# Firebase JS SDK (compat builds)
|
||||
|
||||
`firebase-app-compat.js`, `firebase-auth-compat.js` and `firebase-firestore-compat.js` are the
|
||||
unmodified compat builds of the [Firebase JS SDK](https://github.com/firebase/firebase-js-sdk)
|
||||
version 12.19.0, from `https://www.gstatic.com/firebasejs/12.19.0/`. They're bundled so sync
|
||||
works offline (the service worker caches them). Copyright Google LLC, Apache License 2.0
|
||||
(see `LICENSE`).
|
||||
|
||||
The app loads them only on devices signed in to sync (see `js/sync.js`).
|
||||
@@ -1,8 +0,0 @@
|
||||
((e,t)=>{"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).firebase=t()})(this,function(){let F=()=>{},r=function(t){var r=[];let a=0;for(let n=0;n<t.length;n++){let e=t.charCodeAt(n);e<128?r[a++]=e:(e<2048?r[a++]=e>>6|192:(55296==(64512&e)&&n+1<t.length&&56320==(64512&t.charCodeAt(n+1))?(e=65536+((1023&e)<<10)+(1023&t.charCodeAt(++n)),r[a++]=e>>18|240,r[a++]=e>>12&63|128):r[a++]=e>>12|224,r[a++]=e>>6&63|128),r[a++]=63&e|128)}return r},M={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(r,e){if(!Array.isArray(r))throw Error("encodeByteArray takes an array as a parameter");this.init_();var a=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,n=[];for(let h=0;h<r.length;h+=3){var i=r[h],s=h+1<r.length,o=s?r[h+1]:0,c=h+2<r.length,l=c?r[h+2]:0;let e=(15&o)<<2|l>>6,t=63&l;c||(t=64,s)||(e=64),n.push(a[i>>2],a[(3&i)<<4|o>>4],a[e],a[t])}return n.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(r(e),t)},decodeString(r,a){if(this.HAS_NATIVE_SUPPORT&&!a)return atob(r);{var n=this.decodeStringToByteArray(r,a);var i=[];let e=0,t=0;for(;e<n.length;){var s,o,c,l=n[e++];l<128?i[t++]=String.fromCharCode(l):191<l&&l<224?(s=n[e++],i[t++]=String.fromCharCode((31&l)<<6|63&s)):239<l&&l<365?(s=((7&l)<<18|(63&n[e++])<<12|(63&n[e++])<<6|63&n[e++])-65536,i[t++]=String.fromCharCode(55296+(s>>10)),i[t++]=String.fromCharCode(56320+(1023&s))):(o=n[e++],c=n[e++],i[t++]=String.fromCharCode((15&l)<<12|(63&o)<<6|63&c))}return i.join("");return}},decodeStringToByteArray(e,t){this.init_();var r=t?this.charToByteMapWebSafe_:this.charToByteMap_,a=[];for(let c=0;c<e.length;){var n=r[e.charAt(c++)],i=c<e.length?r[e.charAt(c)]:0,s=++c<e.length?r[e.charAt(c)]:64,o=++c<e.length?r[e.charAt(c)]:64;if(++c,null==n||null==i||null==s||null==o)throw new z;a.push(n<<2|i>>4),64!==s&&(a.push(i<<4&240|s>>2),64!==o)&&a.push(s<<6&192|o)}return a},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),(this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e)>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class z extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}function x(e){var t=r(e);return M.encodeByteArray(t,!0)}let V=function(e){return x(e).replace(/\./g,"")},H=function(e){try{return M.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function c(e,t){if(!(t instanceof Object))return t;switch(t.constructor){case Date:return new Date(t.getTime());case Object:void 0===e&&(e={});break;case Array:e=[];break;default:return t}for(var r in t)t.hasOwnProperty(r)&&"__proto__"!==r&&(e[r]=c(e[r],t[r]));return e}function j(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}let $=()=>j().__FIREBASE_DEFAULTS__,W=()=>{var e;return"undefined"!=typeof process&&void 0!==process.env&&(e=process.env.__FIREBASE_DEFAULTS__)?JSON.parse(e):void 0},U=()=>{if("undefined"!=typeof document){let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}var t=e&&H(e[1]);return t&&JSON.parse(t)}},J=()=>{try{return F()||$()||W()||U()}catch(e){console.info("Unable to get __FIREBASE_DEFAULTS__ due to: "+e)}},l=()=>J()?.config;class G{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}wrapCallback(r){return(e,t)=>{e?this.reject(e):this.resolve(t),"function"==typeof r&&(this.promise.catch(()=>{}),1===r.length?r(e):r(e,t))}}}function K(){return"undefined"!=typeof WorkerGlobalScope&&"undefined"!=typeof self&&self instanceof WorkerGlobalScope}class i extends Error{constructor(e,t,r){super(t),this.code=e,this.customData=r,this.name="FirebaseError",Object.setPrototypeOf(this,i.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,a.prototype.create)}}class a{constructor(e,t,r){this.service=e,this.serviceName=t,this.errors=r}create(e,...t){var r=t[0]||{},a=this.service+"/"+e,n=this.errors[e],n=n?((r,a)=>{try{let e=0,t="";for(;e<r.length;){var n=r.indexOf("{$",e);if(-1===n){t+=r.substring(e);break}var i=r.indexOf("}",n+2);if(-1===i){t+=r.substring(e);breaLine truncated
|
||||
Warning: Firebase is already defined in the global scope. Please make sure
|
||||
Firebase library is only loaded once.
|
||||
`),$e=P.firebase.SDK_VERSION)&&0<=$e.indexOf("LITE")&&je.warn(`
|
||||
Warning: You are trying to load Firebase while using Firebase Performance standalone script.
|
||||
You should load Firebase Performance with this instance of Firebase to avoid loading duplicate code.
|
||||
`)}catch{}P=He;k("@firebase/app-compat","0.5.18",void 0);return P.registerVersion("firebase","12.19.0","app-compat-cdn"),P});
|
||||
//# sourceMappingURL=firebase-app-compat.js.map
|
||||
@@ -1,2 +0,0 @@
|
||||
((e,t)=>{"object"==typeof exports&&"undefined"!=typeof module?t(require("@firebase/app-compat"),require("@firebase/app")):"function"==typeof define&&define.amd?define(["@firebase/app-compat","@firebase/app"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).firebase,e.firebase.INTERNAL.modularAPIs)})(this,function(Hn,jn){try{!(function(){let t=()=>{},F={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(r,e){if(!Array.isArray(r))throw Error("encodeByteArray takes an array as a parameter");this.init_();var i=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,n=[];for(let h=0;h<r.length;h+=3){var s=r[h],a=h+1<r.length,o=a?r[h+1]:0,c=h+2<r.length,l=c?r[h+2]:0;let e=(15&o)<<2|l>>6,t=63&l;c||(t=64,a)||(e=64),n.push(i[s>>2],i[(3&s)<<4|o>>4],i[e],i[t])}return n.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray((t=>{var r=[];let i=0;for(let n=0;n<t.length;n++){let e=t.charCodeAt(n);e<128?r[i++]=e:(e<2048?r[i++]=e>>6|192:(55296==(64512&e)&&n+1<t.length&&56320==(64512&t.charCodeAt(n+1))?(e=65536+((1023&e)<<10)+(1023&t.charCodeAt(++n)),r[i++]=e>>18|240,r[i++]=e>>12&63|128):r[i++]=e>>12|224,r[i++]=e>>6&63|128),r[i++]=63&e|128)}return r})(e),t)},decodeString(r,i){if(this.HAS_NATIVE_SUPPORT&&!i)return atob(r);{var n=this.decodeStringToByteArray(r,i);var s=[];let e=0,t=0;for(;e<n.length;){var a,o,c,l=n[e++];l<128?s[t++]=String.fromCharCode(l):191<l&&l<224?(a=n[e++],s[t++]=String.fromCharCode((31&l)<<6|63&a)):239<l&&l<365?(a=((7&l)<<18|(63&n[e++])<<12|(63&n[e++])<<6|63&n[e++])-65536,s[t++]=String.fromCharCode(55296+(a>>10)),s[t++]=String.fromCharCode(56320+(1023&a))):(o=n[e++],c=n[e++],s[t++]=String.fromCharCode((15&l)<<12|(63&o)<<6|63&c))}return s.join("");return}},decodeStringToByteArray(e,t){this.init_();var r=t?this.charToByteMapWebSafe_:this.charToByteMap_,i=[];for(let c=0;c<e.length;){var n=r[e.charAt(c++)],s=c<e.length?r[e.charAt(c)]:0,a=++c<e.length?r[e.charAt(c)]:64,o=++c<e.length?r[e.charAt(c)]:64;if(++c,null==n||null==s||null==a||null==o)throw new V;i.push(n<<2|s>>4),64!==a&&(i.push(s<<4&240|a>>2),64!==o)&&i.push(a<<6&192|o)}return i},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),(this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e)>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class V extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}let x=function(e){try{return F.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};let W=()=>(()=>{if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")})().__FIREBASE_DEFAULTS__,H=()=>{var e;return"undefined"!=typeof process&&void 0!==process.env&&(e=process.env.__FIREBASE_DEFAULTS__)?JSON.parse(e):void 0},j=()=>{if("undefined"!=typeof document){let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}var t=e&&x(e[1]);return t&&JSON.parse(t)}},q=()=>{try{return t()||W()||H()||j()}catch(e){console.info("Unable to get __FIREBASE_DEFAULTS__ due to: "+e)}};var r;class z{constructor(){this.reject=()=>{},this.resolve=()=>{},this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}wrapCallback(r){return(e,t)=>{e?this.reject(e):this.resolve(t),"function"==typeof r&&(this.promise.catch(()=>{}),1===r.length?r(e):r(e,t))}}}function l(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function B(){var e=q()?.forceEnvironment;if("node"===e)return!0;if("browser"===e)return!1;try{return"[object process]"===Object.prototype.toString.call(global.process)}catch(e){return!1}}function G(){var e="object"==typeof chrome?chrome.runtime:"object"==typeof browser?browser.runtime:void 0;return"object"==typeof e&&void 0!==e.id}function K(){return"object"==typeof navigator&&"ReactNative"===navigator.product}function J(){var e=l();return 0<=e.indexOf("MSIE ")||0<=e.indexOf("Trident/")}function Y(){try{return"object"==typeof indexedDB}catch(e){return!1}}class h extends Error{constructor(e,t,r){super(t),this.code=e,this.customData=r,this.name="FirebaseError",Object.setPrototypeOf(this,h.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,$.prototype.create)}}class ${constructor(Line truncated
|
||||
//# sourceMappingURL=firebase-auth-compat.js.map
|
||||
@@ -1,9 +0,0 @@
|
||||
((e,t)=>{"object"==typeof exports&&"undefined"!=typeof module?t(require("@firebase/app-compat"),require("@firebase/app")):"function"==typeof define&&define.amd?define(["@firebase/app-compat","@firebase/app"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).firebase,e.firebase.INTERNAL.modularAPIs)})(this,function(Af,Sf){try{!(function(){let a=()=>{},B=function(t){var r=[];let n=0;for(let s=0;s<t.length;s++){let e=t.charCodeAt(s);e<128?r[n++]=e:(e<2048?r[n++]=e>>6|192:(55296==(64512&e)&&s+1<t.length&&56320==(64512&t.charCodeAt(s+1))?(e=65536+((1023&e)<<10)+(1023&t.charCodeAt(++s)),r[n++]=e>>18|240,r[n++]=e>>12&63|128):r[n++]=e>>12|224,r[n++]=e>>6&63|128),r[n++]=63&e|128)}return r},o={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",get ENCODED_VALS(){return this.ENCODED_VALS_BASE+"+/="},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+"-_."},HAS_NATIVE_SUPPORT:"function"==typeof atob,encodeByteArray(r,e){if(!Array.isArray(r))throw Error("encodeByteArray takes an array as a parameter");this.init_();var n=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,s=[];for(let l=0;l<r.length;l+=3){var i=r[l],a=l+1<r.length,B=a?r[l+1]:0,o=l+2<r.length,u=o?r[l+2]:0;let e=(15&B)<<2|u>>6,t=63&u;o||(t=64,a)||(e=64),s.push(n[i>>2],n[(3&i)<<4|B>>4],n[e],n[t])}return s.join("")},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(B(e),t)},decodeString(r,n){if(this.HAS_NATIVE_SUPPORT&&!n)return atob(r);{var s=this.decodeStringToByteArray(r,n);var i=[];let e=0,t=0;for(;e<s.length;){var a,B,o,u=s[e++];u<128?i[t++]=String.fromCharCode(u):191<u&&u<224?(a=s[e++],i[t++]=String.fromCharCode((31&u)<<6|63&a)):239<u&&u<365?(a=((7&u)<<18|(63&s[e++])<<12|(63&s[e++])<<6|63&s[e++])-65536,i[t++]=String.fromCharCode(55296+(a>>10)),i[t++]=String.fromCharCode(56320+(1023&a))):(B=s[e++],o=s[e++],i[t++]=String.fromCharCode((15&u)<<12|(63&B)<<6|63&o))}return i.join("");return}},decodeStringToByteArray(e,t){this.init_();var r=t?this.charToByteMapWebSafe_:this.charToByteMap_,n=[];for(let o=0;o<e.length;){var s=r[e.charAt(o++)],i=o<e.length?r[e.charAt(o)]:0,a=++o<e.length?r[e.charAt(o)]:64,B=++o<e.length?r[e.charAt(o)]:64;if(++o,null==s||null==i||null==a||null==B)throw new M;n.push(s<<2|i>>4),64!==a&&(n.push(i<<4&240|a>>2),64!==B)&&n.push(a<<6&192|B)}return n},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e<this.ENCODED_VALS.length;e++)this.byteToCharMap_[e]=this.ENCODED_VALS.charAt(e),this.charToByteMap_[this.byteToCharMap_[e]]=e,this.byteToCharMapWebSafe_[e]=this.ENCODED_VALS_WEBSAFE.charAt(e),(this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[e]]=e)>=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class M extends Error{constructor(){super(...arguments),this.name="DecodeBase64StringError"}}let H=function(e){var t=B(e);return o.encodeByteArray(t,!0)},V=function(e){return H(e).replace(/\./g,"")},U=function(e){try{return o.decodeString(e,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function q(){if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;throw new Error("Unable to locate global object.")}let J=()=>q().__FIREBASE_DEFAULTS__,K=()=>{var e;return"undefined"!=typeof process&&void 0!==process.env&&(e=process.env.__FIREBASE_DEFAULTS__)?JSON.parse(e):void 0},j=()=>{if("undefined"!=typeof document){let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}var t=e&&U(e[1]);return t&&JSON.parse(t)}},Q=()=>{try{return a()||J()||K()||j()}catch(e){console.info("Unable to get __FIREBASE_DEFAULTS__ due to: "+e)}};function z(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function Y(){var e=Q()?.forceEnvironment;if("node"===e)return 1;if("browser"!==e)try{return"[object process]"===Object.prototype.toString.call(global.process)}catch(e){}}function W(){return!Y()&&navigator.userAgent&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}function X(){return!Y()&&navigator.userAgent&&(navigator.userAgent.includes("Safari")||navigator.userAgent.includes("WebKit"))&&!navigator.userAgent.includes("Chrome")}class $ extends Error{constructor(e,t,r){super(t),this.code=e,this.customData=r,this.name="FirebaseError",Object.setPrototypeOf(this,$.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,Z.prototype.create)}}class Z{constructor(e,t,r){this.service=e,this.serviceName=t,this.errors=r}create(e,...t){var r=t[0]||{},n=this.service+"/"+e,s=this.errors[e],s=s?((r,n)=>{try{let e=0,t="";for(;e<r.length;){var s=r.indexOf("{$",e);if(-1===s){t+=r.substring(e);break}var i=r.indexOf("}",Line truncated
|
||||
Counted targets in ${a-l}ms
|
||||
Determined least recently used ${s} in `+(B-a)+"ms\n"+` Removed ${i} targets in `+(o-B)+"ms\n"+` Removed ${e} documents in `+(u-o)+"ms\n"+`Total Duration: ${u-l}ms`),k.resolve({didRun:!0,sequenceNumbersCollected:s,targetsRemoved:i,documentsRemoved:e})))}}function aB(e,t){return new iB(e,t)}let BB="firestore.googleapis.com";class oB{constructor(e){if(void 0===e.host){if(void 0!==e.ssl)throw new N(w.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host=BB,this.ssl=!0}else this.host=e.host,this.ssl=e.ssl??!0;if(this.isUsingEmulator=void 0!==e.emulatorOptions,this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.localCache=e.localCache,e._customHeaders&&(this._customHeaders={...e._customHeaders}),void 0===e.cacheSizeBytes)this.cacheSizeBytes=41943040;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes<1048576)throw new N(w.INVALID_ARGUMENT,"cacheSizeBytes must be at least 1048576");this.cacheSizeBytes=e.cacheSizeBytes}tr("experimentalForceLongPolling",e.experimentalForceLongPolling,"experimentalAutoDetectLongPolling",e.experimentalAutoDetectLongPolling),this.experimentalForceLongPolling=!!e.experimentalForceLongPolling,this.experimentalForceLongPolling?this.experimentalAutoDetectLongPolling=!1:void 0===e.experimentalAutoDetectLongPolling?this.experimentalAutoDetectLongPolling=!0:this.experimentalAutoDetectLongPolling=!!e.experimentalAutoDetectLongPolling,this.experimentalLongPollingOptions=Da(e.experimentalLongPollingOptions??{});var t=this.experimentalLongPollingOptions;if(void 0!==t.timeoutSeconds){if(isNaN(t.timeoutSeconds))throw new N(w.INVALID_ARGUMENT,`invalid long polling timeout: ${t.timeoutSeconds} (must not be NaN)`);if(t.timeoutSeconds<5)throw new N(w.INVALID_ARGUMENT,`invalid long polling timeout: ${t.timeoutSeconds} (minimum allowed value is 5)`);if(30<t.timeoutSeconds)throw new N(w.INVALID_ARGUMENT,`invalid long polling timeout: ${t.timeoutSeconds} (maximum allowed value is 30)`)}if(this.useFetchStreams=!!e.useFetchStreams,void 0!==e.grpcFlowControlWindow){if("number"!=typeof e.grpcFlowControlWindow||e.grpcFlowControlWindow<=0||2147483647<e.grpcFlowControlWindow||!Number.isInteger(e.grpcFlowControlWindow))throw new N(w.INVALID_ARGUMENT,"grpcFlowControlWindow must be a positive integer and cannot exceed 2147483647");this.grpcFlowControlWindow=e.grpcFlowControlWindow}}isEqual(e){return this.host===e.host&&this.ssl===e.ssl&&this.credentials===e.credentials&&this.cacheSizeBytes===e.cacheSizeBytes&&this.experimentalForceLongPolling===e.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===e.experimentalAutoDetectLongPolling&&(t=this.experimentalLongPollingOptions,r=e.experimentalLongPollingOptions,t.timeoutSeconds===r.timeoutSeconds)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams&&this.grpcFlowControlWindow===e.grpcFlowControlWindow&&((r,n)=>{if(r!==n){if(!r||!n)return!1;let e=Object.keys(r),t=Object.keys(n);if(e.length!==t.length)return!1;for(let t of e)if(r[t]!==n[t])return!1}return!0})(this._customHeaders,e._customHeaders);var t,r}}let uB=class{constructor(e,t,r,n){this._authCredentials=e,this._appCheckCredentials=t,this._databaseId=r,this._app=n,this.type="firestore-lite",this._persistenceKey="(lite)",this._settings=new oB({}),this._settingsFrozen=!1,this._emulatorOptions={},this._terminateTask="notTerminated"}get app(){if(this._app)return this._app;throw new N(w.FAILED_PRECONDITION,"Firestore was not initialized using the Firebase SDK. 'app' is not available")}get _initialized(){return this._settingsFrozen}get _terminated(){return"notTerminated"!==this._terminateTask}_setSettings(e){if(this._settingsFrozen)throw new N(w.FAILED_PRECONDITION,"Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.");this._settings=new oB(e),this._emulatorOptions=e.emulatorOptions||{},void 0!==e.credentials&&(this._authCredentials=(e=>{if(!e)return new ca;switch(e.type){case"firstParty":return new pa(e.sessionIndex||"0",e.iamToken||null,e.authTokenFactory||null);case"provider":return e.client;default:throw new N(w.INVALID_ARGUMENT,"makeAuthCredentialsProvider failed due to invalid credential type")}})(e.credentials))}_getSettings(){return this._settings}_getEmulatorOptions(){return this._emulatorOptions}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return"notTerminated"===this._terminateTask&&(this._terminateTask=this._terminate()),this._terminateTask}async _restart(){"notTerminated"===this._terminateTask?await this._terminate():this._terminateTask="notTerminated"}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return e=this,(t=Ga.get(e))&&(d("ComponentProvider","Removing Datastore"),Ga.delete(e),t.terminate()),Promise.resolve();var e,t}};function lB(n,e,t,s={}){n=S(n,uB);let r=ne(e),i=n._getSettin
Line truncated
|
||||
largestBatchId: ${this.largestBatchId},
|
||||
mutation: ${this.mutation.toString()}
|
||||
}`}}class Vh{constructor(e,t,r,n,s=L.min(),i=L.min(),a=Er.EMPTY_BYTE_STRING,B=null){this.target=e,this.targetId=t,this.purpose=r,this.sequenceNumber=n,this.snapshotVersion=s,this.lastLimboFreeSnapshotVersion=i,this.resumeToken=a,this.expectedCount=B}withSequenceNumber(e){return new Vh(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,t){return new Vh(this.target,this.targetId,this.purpose,this.sequenceNumber,t,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new Vh(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new Vh(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}}class Uh{constructor(e){this.$r=e}}function qh(e,t){var r,n=t.key,s={prefixPath:n.getCollectionPath().popLast().toArray(),collectionGroup:n.collectionGroup,documentId:n.path.lastSegment(),readTime:Jh(t.readTime),hasCommittedMutations:t.hasCommittedMutations};if(t.isFoundDocument())s.document={name:Li(e=e.$r,(r=t).key),fields:r.data.value.mapValue.fields,updateTime:Ti(e,r.version.toTimestamp()),createTime:Ti(e,r.createTime.toTimestamp())};else if(t.isNoDocument())s.noDocument={path:n.path.toArray(),readTime:Kh(t.version)};else{if(!t.isUnknownDocument())return T(57904,{document:t});s.unknownDocument={path:n.path.toArray(),version:Kh(t.version)}}return s}function Jh(e){var t=e.toTimestamp();return[t.seconds,t.nanoseconds]}function Kh(e){var t=e.toTimestamp();return{seconds:t.seconds,nanoseconds:t.nanoseconds}}function jh(e){var t=new l(e.seconds,e.nanoseconds);return L.fromTimestamp(t)}function Qh(t,r){let e=(r.baseMutations||[]).map(e=>qi(t.$r,e));for(let i=0;i<r.mutations.length-1;++i){let t=r.mutations[i];if(i+1<r.mutations.length&&void 0!==r.mutations[i+1].transform){let e=r.mutations[i+1];t.updateTransforms=e.transform.fieldTransforms,r.mutations.splice(i+1,1),++i}}let n=r.mutations.map(e=>qi(t.$r,e)),s=l.fromMillis(r.localWriteTimeMs);return new Il(r.batchId,s,e,n)}function zh(e,t){var r,n,s=jh(t.readTime),i=void 0!==t.lastLimboFreeSnapshotVersion?jh(t.lastLimboFreeSnapshotVersion):L.min(),a=void 0!==t.query.structuredPipeline?(r=t.query,e=e.$r,f(0<((n=r.structuredPipeline)?.pipeline?.stages??[]).length,1845),n=n?.pipeline?.stages.map(ec),new Io(e,n)):void 0!==t.query.documents?(r=t.query,f(1===(n=r.documents.length),1966,{count:n}),Hs(ks(Gi(r.documents[0])))):Hs(Qi(t.query));return new Vh(a,t.targetId,"TargetPurposeListen",t.lastListenSequenceNumber,s,i,Er.fromBase64String(t.resumeToken))}function Yh(e,t){var r=Kh(t.snapshotVersion),n=Kh(t.lastLimboFreeSnapshotVersion),s=Fs(t.target)?Yi(e.$r,t.target):As(t.target)?Ki(e.$r,t.target):ji(e.$r,t.target).Se,i=t.resumeToken.toBase64();return{targetId:t.targetId,canonicalId:wl(t.target),readTime:r,resumeToken:i,lastListenSequenceNumber:t.sequenceNumber,lastLimboFreeSnapshotVersion:n,query:s}}function Wh(e){var t=Qi({parent:e.parent,structuredQuery:e.structuredQuery});return"LAST"===e.limitType?Us(t,t.limit,"L"):t}function Xh(e,t){return new Hh(t.largestBatchId,qi(e.$r,t.overlayMutation))}function $h(e,t){var r=t.path.lastSegment();return[e,Nl(t.path.popLast()),r]}function Zh(e,t,r,n){return{indexId:e,uid:t,sequenceNumber:r,readTime:Kh(n.readTime),documentKey:Nl(n.documentKey.path),largestBatchId:n.largestBatchId}}function ec(e){switch(e.name){case"collection":return new go(e.args[0].referenceValue,{});case"collection_group":return new po(e.args[1].stringValue,{});case"database":return new fo({});case"documents":return new mo(e.args.map(e=>e.referenceValue),{});case"where":return new Do(tc(e.args[0]),{});case"limit":var t=e.args[0].integerValue??e.args[0].doubleValue;return new Eo("number"==typeof t?t:Number(t),{});case"sort":return new wo(e.args.map(e=>{return t=e.mapValue?.fields,new uo(tc(t.expression),t.direction?.stringValue,"orderingFromProto");var t}),{});default:throw new Error(`Stage type: ${e.name} not supported.`)}}function tc(e){return e.fieldReferenceValue?new eo(HB("_exprFromProto",e.fieldReferenceValue),"_exprFromProto"):e.functionValue?(t=e,new i(t.functionValue.name,t.functionValue.args?.map(tc)||[])):ro._fromProto(e);var t}class rc{constructor(e,t,r,n){this.userId=e,this.serializer=t,this.indexManager=r,this.referenceDelegate=n,this.Kr={}}static Qr(e,t,r,n){f(""!==e.uid,64387);var s=e.isAuthenticated()?e.uid:"";return new rc(s,t,r,n)}checkEmpty(e){let n=!0;var t=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return sc(e).Hn({index:Gl,range:t},(e,t,r)=>{n=!1,r.done()}).next(()=>n)}addMutationBatch(h,c,C,d){let g=ic(h),p=sc(h);return p.add({}).next(t=>{f("number"==typeof t,49019);let e=new Il(t,c,C,d),r=(s=this.serializer,i=this.userId,a=e,B=a.baseMutations.map(e=>Ui(s.$r,e)),o=a.mutations.map(e=>Ui(s.$r,e)),{use
Line truncated
|
||||
This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;this.Xo?(St(t),this.Xo=!1):d("OnlineStateTracker",t)}ia(){null!==this.Zo&&(this.Zo.cancel(),this.Zo=null)}}let ed="RemoteStore";class td{constructor(e,t,r,n,s){this.localStore=e,this.datastore=t,this.asyncQueue=r,this.remoteSyncer={},this.sa=[],this._a=new Map,this.oa=new Map,this.aa=new Map,this.ua=new Uc(1e3),this.ca=new Uc(1001),this.la=new Set,this.Ea=[],this.ha=s,this.ha.Qe(e=>{r.enqueueAndForget(async()=>{var e;hd(this)&&(d(ed,"Restarting streams for network reachability change."),(e=this).la.add(4),await nd(e),e.Ta.set("Unknown"),e.la.delete(4),await rd(e))})}),this.Ta=new ZC(r,n)}}async function rd(e){if(hd(e))for(var t of e.Ea)await t(!0)}async function nd(e){for(var t of e.Ea)await t(!1)}function sd(e,t){return e.oa.get(t)||void 0}function id(e,t){var r,n,s,i=e,a=sd(i,t.targetId);void 0!==a&&i._a.has(a)||(void 0!==(a=sd(e=i,r=t.targetId))&&e.aa.delete(a),n=e,a=(r%2!=0?n.ca:n.ua).next(),e.oa.set(r,a),e.aa.set(a,r),a=a,d(ed,"remoteStoreListen mapping SDK target ID to remote",t.targetId,a),s=new Vh(t.target,a,t.purpose,t.sequenceNumber,t.snapshotVersion,t.lastLimboFreeSnapshotVersion,t.resumeToken),i._a.set(a,s),ld(i)?ud(i):vd(i).Yt()&&Bd(i,s))}function ad(e,t){var r=e,n=vd(r),s=sd(r,t);d(ed,"remoteStoreUnlisten removing mapping of SDK target ID to remote",t,s),r._a.delete(s),r.oa.delete(t),r.aa.delete(s),n.Yt()&&od(r,s),0===r._a.size&&(n.Yt()?n.en():hd(r)&&r.Ta.set("Unknown"))}function Bd(e,t){if(e.Pa.J(t.targetId),0<t.resumeToken.approximateByteSize()||0<t.snapshotVersion.compareTo(L.min())){var r=e.aa.get(t.targetId);if(void 0===r)return d(ed,"SDK target ID not found for remote ID: "+t.targetId);r=e.remoteSyncer.getRemoteKeysForTarget(r).size;t=t.withExpectedCount(r)}vd(e).Pn(t)}function od(e,t){e.Pa.J(t),vd(e).In(t)}function ud(r){r.Pa=new mi({getRemoteKeysForTarget:e=>{var t=r.aa.get(e);return void 0!==t?r.remoteSyncer.getRemoteKeysForTarget(t):R()},ye:e=>r._a.get(e)||null,Ve:()=>r.datastore.serializer.databaseId}),vd(r).start(),r.Ta.ea()}function ld(e){return hd(e)&&!vd(e).Jt()&&0<e._a.size}function hd(e){return 0===e.la.size}function cd(e){e.Pa=void 0}async function Cd(t,e,r){if(t.Ta.set("Online"),e instanceof gi&&2===e.state&&e.cause)try{var n,s=t,i=e,a=i.cause;for(n of i.targetIds){if(s._a.has(n)){let e=s.aa.get(n);void 0!==e&&(await s.remoteSyncer.rejectListen(e,a),s.oa.delete(e),s.aa.delete(n)),s._a.delete(n)}s.Pa.removeTarget(n)}}catch(r){d(ed,"Failed to remove targets %s: %s ",e.targetIds.join(","),r),await dd(t,r)}else if(e instanceof Ci?t.Pa._e(e):e instanceof di?t.Pa.he(e):t.Pa.ue(e),!r.isEqual(L.min()))try{let e=await UC(t.localStore);0<=r.compareTo(e)&&(o=r,(u=(B=t).Pa.fe(o)).targetChanges.forEach((e,t)=>{var r;0<e.resumeToken.approximateByteSize()&&(r=B._a.get(t))&&B._a.set(t,r.withResumeToken(e.resumeToken,o))}),u.targetMismatches.forEach((e,t)=>{var r=B._a.get(e);r&&(B._a.set(e,r.withResumeToken(Er.EMPTY_BYTE_STRING,r.snapshotVersion)),od(B,e),r=new Vh(r.target,e,t,r.sequenceNumber),Bd(B,r))}),u=((n,e)=>{let s=new Map,i=(e.targetChanges.forEach((e,t)=>{var r=n.aa.get(t);void 0!==r&&s.set(r,e)}),new p(b));return e.targetMismatches.forEach((e,t)=>{var r=n.aa.get(e);void 0!==r&&(i=i.insert(r,t))}),new hi(e.snapshotVersion,s,i,e.documentUpdates,e.augmentedDocumentUpdates,e.resolvedLimboDocuments)})(B,u),await B.remoteSyncer.applyRemoteEvent(u))}catch(e){d(ed,"Failed to raise snapshot:",e),await dd(t,e)}var B,o,u}async function dd(e,t,r){if(!Wa(t))throw t;e.la.add(1),await nd(e),e.Ta.set("Offline"),r=r||(()=>UC(e.localStore)),e.asyncQueue.enqueueRetryable(async()=>{d(ed,"Retrying IndexedDB access"),await r(),e.la.delete(1),await rd(e)})}function gd(t,r){return r().catch(e=>dd(t,e,r))}async function pd(e){var t,r,n,s,i=e,a=wd(i);let B=0<i.sa.length?i.sa[i.sa.length-1].batchId:Rr;for(;hd(s=i)&&s.sa.length<10;)try{let e=await((e,t)=>{let r=e;return r.persistence.runTransaction("Get next mutation batch","readonly",e=>(void 0===t&&(t=Rr),r.mutationQueue.getNextMutationBatchAfterBatchId(e,t)))})(i.localStore,B);if(null===e){0===i.sa.length&&a.en();break}B=e.batchId,t=i,r=e,n=void 0,t.sa.push(r),(n=wd(t)).Yt()&&n.Rn&&n.An(r.mutations)}catch(e){await dd(i,e)}fd(i)&&md(i)}function fd(e){return hd(e)&&!wd(e).Jt()&&0<e.sa.length}function md(e){wd(e).start()}async function Dd(e,t){var r=e,n=(r.asyncQueue.verifyOperationInProgress(),d(ed,"RemoteStore received new credentials"),hd(r));r.la.add(3),await nd(r),n&&r.Ta.set("Unknown"),await r.remoteSyncer.handleCredentialChange(t),r.la.delete(3),await rd(r)}async function Ed(e,t){var r=e;t?(r.la.delete(2),await rd(r)):(r.la.add(2),await nd(r),r.Ta.set("Unknown"))}function vd(t){return t.Ia||(t.Ia=(e=t.datastore,r=t.asyncQueue,n={ct:(async function(e){e.Ta.set("Online")}).bind(null,t),Et:(async function(r){r._a.forEach((e,t)=>{Bd(r,e)})}).bind(null,t),Tt:(a
Line truncated
|
||||
`+JSON.stringify(e?.Ho)))},e=>this.metadata.reject(e))}close(){return this.da.cancel()}async getMetadata(){return this.metadata.promise}async pa(){return await this.getMetadata(),this.ma()}async ma(){var e,t,r=await this.ga();return null===r?null:(t=this.fa.decode(r),e=Number(t),isNaN(e)&&this.ya(`length string (${t}) is not valid number`),t=await this.wa(e),new XC(JSON.parse(t),r.length+e))}ba(){return this.buffer.findIndex(e=>e==="{".charCodeAt(0))}async ga(){for(;this.ba()<0&&!await this.Sa(););var e,t;return 0===this.buffer.length?null:((e=this.ba())<0&&this.ya("Reached the end of bundle when a length string is expected."),t=this.buffer.slice(0,e),this.buffer=this.buffer.slice(e),t)}async wa(e){for(;this.buffer.length<e;)await this.Sa()&&this.ya("Reached the end of bundle when more is expected.");var t=this.fa.decode(this.buffer.slice(0,e));return this.buffer=this.buffer.slice(e),t}ya(e){throw this.da.cancel(),new Error("Invalid bundle format: "+e)}async Sa(){var e,t=await this.da.read();return t.done||((e=new Uint8Array(this.buffer.length+t.value.length)).set(this.buffer),e.set(t.value,this.buffer.length),this.buffer=e),t.done}}let bd="IndexBackfiller";class Nd{constructor(e,t){this.asyncQueue=e,this.Da=t,this.task=null}start(){this.xa(15e3)}stop(){this.task&&(this.task.cancel(),this.task=null)}get started(){return null!==this.task}xa(e){d(bd,`Scheduled in ${e}ms`),this.task=this.asyncQueue.enqueueAfterDelay("index_backfill",e,async()=>{this.task=null;try{var e=await this.Da.Ca();d(bd,"Documents written: "+e)}catch(e){Wa(e)?d(bd,"Ignoring IndexedDB error during index backfill: ",e):await qa(e)}await this.xa(6e4)})}}class Fd{constructor(e,t){this.localStore=e,this.persistence=t}async Ca(t=50){return this.persistence.runTransaction("Backfill Indexes","readwrite-primary",e=>this.Fa(e,t))}Fa(e,t){let r=new Set,n=t,s=!0;return k.doWhile(()=>!0===s&&0<n,()=>this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next(t=>{if(null!==t&&!r.has(t))return d(bd,"Processing collection: "+t),this.Oa(e,t,n).next(e=>{n-=e,r.add(t)});s=!1})).next(()=>t-n)}Oa(n,s,e){return this.localStore.indexManager.getMinOffsetFromCollectionGroup(n,s).next(r=>this.localStore.localDocuments.getNextDocuments(n,s,r,e).next(e=>{let t=e.changes;return this.localStore.indexManager.updateIndexEntries(n,t).next(()=>this.Ma(r,e)).next(e=>(d(bd,"Updating offset: "+e),this.localStore.indexManager.updateCollectionGroup(n,s,e))).next(()=>t.size)}))}Ma(e,t){let n=e;return t.changes.forEach((e,t)=>{var r=ws(t);0<_s(r,n)&&(n=r)}),new ys(n.readTime,n.documentKey,Math.max(t.batchId,e.largestBatchId))}}let Ad="firestore_clients";function Sd(e,t){return Ad+`_${e}_`+t}let Od="firestore_mutations";function xd(e,t,r){let n=Od+`_${e}_`+r;return t.isAuthenticated()&&(n+="_"+t.uid),n}let Ld="firestore_targets";function Rd(e,t){return Ld+`_${e}_`+t}let kd="SharedClientState";class Gd{constructor(e,t,r,n){this.user=e,this.batchId=t,this.state=r,this.error=n}static Na(e,t,r){var n=JSON.parse(r);let s,i="object"==typeof n&&-1!==["pending","acknowledged","rejected"].indexOf(n.state)&&(void 0===n.error||"object"==typeof n.error);return i&&n.error&&(i="string"==typeof n.error.message&&"string"==typeof n.error.code)&&(s=new N(n.error.code,n.error.message)),i?new Gd(e,t,n.state,s):(St(kd,`Failed to parse mutation state for ID '${t}': `+r),null)}La(){var e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class Pd{constructor(e,t,r){this.targetId=e,this.state=t,this.error=r}static Na(e,t){var r=JSON.parse(t);let n,s="object"==typeof r&&-1!==["not-current","current","rejected"].indexOf(r.state)&&(void 0===r.error||"object"==typeof r.error);return s&&r.error&&(s="string"==typeof r.error.message&&"string"==typeof r.error.code)&&(n=new N(r.error.code,r.error.message)),s?new Pd(e,r.state,n):(St(kd,`Failed to parse target state for ID '${e}': `+t),null)}La(){var e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class Md{constructor(e,t){this.clientId=e,this.activeTargetIds=t}static Na(e,t){var r=JSON.parse(t);let n="object"==typeof r&&r.activeTargetIds instanceof Array,s=si;for(let i=0;n&&i<r.activeTargetIds.length;++i)n=Pr(r.activeTargetIds[i]),s=s.add(r.activeTargetIds[i]);return n?new Md(e,s):(St(kd,`Failed to parse client data for instance '${e}': `+t),null)}}class Hd{constructor(e,t){this.clientId=e,this.onlineState=t}static Na(e){var t=JSON.parse(e);return"object"==typeof t&&-1!==["Unknown","Online","Offline"].indexOf(t.onlineState)&&"string"==typeof t.clientId?new Hd(t.clientId,t.onlineState):(St(kd,"Failed to parse online state: "+e),null)}}class Vd{constructor(){this.activeTargetIds=si}Ba(e){this.activeTargetIds=this.activeTargetIds.add(e)}Ua(e){this.activeTargetIds=this.activeTargetIds.delete(e)}La(){var e={activeTargetIds:this.activeTargetIds.toArray(),updateTime
Line truncated
|
||||
//# sourceMappingURL=firebase-firestore-compat.js.map
|
||||
@@ -1,167 +0,0 @@
|
||||
// Presentation and navigation for the scorebook. All scoring uses the existing game model.
|
||||
var workspaceView = 'live';
|
||||
|
||||
function setWorkspaceView(view, focus){
|
||||
var views = ['live', 'scorecard', 'lineups', 'notes'];
|
||||
if(views.indexOf(view) < 0) return;
|
||||
workspaceView = view;
|
||||
document.querySelector('.app').dataset.view = view;
|
||||
document.getElementById('scoringPanel').hidden = view !== 'live';
|
||||
document.getElementById('scorecardPanel').hidden = view !== 'live' && view !== 'scorecard';
|
||||
document.getElementById('lineupsPanel').hidden = view !== 'lineups';
|
||||
document.getElementById('notesPanel').hidden = view !== 'notes';
|
||||
document.querySelectorAll('.view-tabs [role=tab]').forEach(function(tab){
|
||||
var selected = tab.dataset.view === view;
|
||||
tab.setAttribute('aria-selected', String(selected));
|
||||
tab.tabIndex = selected ? 0 : -1;
|
||||
if(selected && focus) tab.focus();
|
||||
});
|
||||
document.getElementById('workspace').setAttribute('aria-labelledby', 'tab-' + view);
|
||||
if(view === 'scorecard') scheduleScorecardRender();
|
||||
}
|
||||
|
||||
document.querySelector('.view-tabs').addEventListener('keydown', function(e){
|
||||
var tabs = ['live', 'scorecard', 'lineups', 'notes'];
|
||||
var index = tabs.indexOf(workspaceView);
|
||||
if(e.key === 'ArrowRight') index = (index + 1) % tabs.length;
|
||||
else if(e.key === 'ArrowLeft') index = (index + tabs.length - 1) % tabs.length;
|
||||
else if(e.key === 'Home') index = 0;
|
||||
else if(e.key === 'End') index = tabs.length - 1;
|
||||
else return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setWorkspaceView(tabs[index], true);
|
||||
});
|
||||
|
||||
function workspaceTeam(side){
|
||||
var selected = document.getElementById(side === 'away' ? 'teamAway' : 'teamHome').value;
|
||||
return TEAM_IDS[selected] ? selected : (side === 'away' ? 'Away team' : 'Home team');
|
||||
}
|
||||
|
||||
function toggleLineScore(){
|
||||
var open = document.querySelector('.scoreboard').classList.toggle('show-linescore');
|
||||
document.querySelector('.mobile-linescore').setAttribute('aria-expanded', String(open));
|
||||
}
|
||||
|
||||
function ordinalInning(n){
|
||||
var rem = n % 100;
|
||||
return n + ((rem >= 11 && rem <= 13) ? 'th' : ({1:'st',2:'nd',3:'rd'}[n % 10] || 'th'));
|
||||
}
|
||||
|
||||
function renderWorkspace(){
|
||||
if(!document.getElementById('matchup')) return;
|
||||
var away = workspaceTeam('away'), home = workspaceTeam('home');
|
||||
document.querySelector('.app').classList.toggle('has-plays', G.log.length > 0);
|
||||
setBoardCollapsed(boardOverride === null ? G.log.length > 0 : boardOverride); // auto-collapse once scoring starts
|
||||
setChromeHidden(chromeOverride === null ? G.log.length > 0 : chromeOverride); // auto-hide header + heading once scoring starts
|
||||
document.querySelector('.app').classList.toggle('has-matchup', !!(TEAM_IDS[away] && TEAM_IDS[home]));
|
||||
var half = G.half === 'top' ? 'Top' : 'Bottom';
|
||||
function teamMarkup(name, side){
|
||||
var badge = TEAM_LOGOS[name]
|
||||
? '<img src="' + TEAM_LOGOS[name] + '" alt="" />'
|
||||
: (side === 'away' ? 'A' : 'H');
|
||||
return '<div class="matchup-team"><div class="matchup-badge">' + badge + '</div><div class="matchup-name">' + esc(name) + '</div><div class="matchup-side">' + side.toUpperCase() + '</div></div>';
|
||||
}
|
||||
var matchup = teamMarkup(away, 'away') + '<div><div class="matchup-score">' + G.rhe.away[0] + '<em>:</em>' + G.rhe.home[0] + '</div><div class="matchup-inning">' + half.toUpperCase() + ' ' + G.inning + '</div></div>' + teamMarkup(home, 'home');
|
||||
// Avoid replacing logos on every pitch, preserving image loads and focus.
|
||||
var el = document.getElementById('matchup');
|
||||
if(el.dataset.markup !== matchup){ el.innerHTML = matchup; el.dataset.markup = matchup; }
|
||||
var occupied = G.bases.filter(Boolean).length;
|
||||
var bases = occupied === 3 ? 'Bases loaded' : occupied ? occupied + ' on base' : 'Bases empty';
|
||||
document.getElementById('boardSituation').textContent = half + ' of the ' + ordinalInning(G.inning) + ' · ' + G.outs + (G.outs === 1 ? ' out' : ' outs') + ' · ' + bases;
|
||||
document.getElementById('boardMini').textContent = away + ' ' + G.rhe.away[0] + ' · ' + G.rhe.home[0] + ' ' + home;
|
||||
document.getElementById('boardMiniInn').textContent = half + ' ' + G.inning;
|
||||
document.getElementById('boardStatus').textContent = G.mlbFollow ? 'FOLLOWING MLB LIVE' : G.log.length ? 'SCORING IN PROGRESS' : 'READY FOR FIRST PITCH';
|
||||
document.getElementById('liveFollowBtn').firstChild.textContent = G.mlbFollow ? 'Manage live follow ' : 'Follow MLB live ';
|
||||
document.getElementById('boardVenue').textContent = G.notes.venue || 'YOUR GAME. YOUR SCORECARD.';
|
||||
document.getElementById('setupTip').hidden = !!(TEAM_IDS[away] && TEAM_IDS[home]) || G.log.length > 0;
|
||||
document.querySelector('.linescore-title span').textContent = TEAM_IDS[away] && TEAM_IDS[home] ? 'Tap a score to edit' : 'Select your teams below';
|
||||
var rawDate = G.notes.date;
|
||||
var date = rawDate ? new Date(rawDate + 'T12:00:00') : new Date();
|
||||
document.getElementById('gameDate').textContent = Number.isNaN(date.getTime()) ? 'BASEBALL, ONE PLAY AT A TIME' : date.toLocaleDateString(undefined,{weekday:'long',month:'long',day:'numeric',year:'numeric'}).toUpperCase();
|
||||
// Outs are interactive controls as well as state indicators.
|
||||
for(var i = 0; i < 3; i++){
|
||||
var out = document.getElementById('o' + i);
|
||||
out.setAttribute('aria-pressed', String(i < G.outs));
|
||||
}
|
||||
}
|
||||
|
||||
// These small renders run for both manual scoring and MLB live updates.
|
||||
['renderScore', 'renderInn', 'renderOuts', 'renderCount', 'renderBases', 'restoreNotes', 'saveNotes', 'renderLog'].forEach(function(name){
|
||||
var original = window[name];
|
||||
window[name] = function(){
|
||||
var value = original.apply(this, arguments);
|
||||
renderWorkspace();
|
||||
return value;
|
||||
};
|
||||
});
|
||||
|
||||
for(var oi = 0; oi < 3; oi++){
|
||||
var outDot = document.getElementById('o' + oi);
|
||||
outDot.setAttribute('role', 'button');
|
||||
outDot.setAttribute('aria-label', 'Set outs to ' + (oi + 1));
|
||||
outDot.tabIndex = 0;
|
||||
outDot.addEventListener('keydown', function(e){
|
||||
if(e.key === 'Enter' || e.key === ' '){ e.preventDefault(); e.stopPropagation(); this.click(); }
|
||||
});
|
||||
}
|
||||
// Color theme: Auto (match the device) / Light / Dark, remembered per device.
|
||||
// The <head> applies a saved explicit choice before paint; this reflects it in
|
||||
// the control and handles clicks.
|
||||
function setTheme(mode){
|
||||
if(['auto', 'light', 'dark'].indexOf(mode) < 0) return;
|
||||
if(mode === 'auto') document.documentElement.removeAttribute('data-theme');
|
||||
else document.documentElement.setAttribute('data-theme', mode);
|
||||
try{ localStorage.setItem('sb-theme', mode); }catch(e){}
|
||||
document.querySelectorAll('[data-theme-set]').forEach(function(b){
|
||||
b.setAttribute('aria-pressed', String(b.dataset.themeSet === mode));
|
||||
});
|
||||
}
|
||||
document.querySelectorAll('[data-theme-set]').forEach(function(b){
|
||||
b.addEventListener('click', function(){ setTheme(b.dataset.themeSet); });
|
||||
});
|
||||
(function(){ var m = 'auto'; try{ m = localStorage.getItem('sb-theme') || 'auto'; }catch(e){} setTheme(m); })();
|
||||
|
||||
// Scoreboard collapse: it auto-folds to a slim score strip once scoring starts
|
||||
// (handled in renderWorkspace) so the scoring controls and scorecard lead. The
|
||||
// Collapse / Show board control overrides that for the session; a reload returns
|
||||
// to the automatic behavior.
|
||||
var boardOverride = null; // null = follow auto; true/false = manual this session
|
||||
function setBoardCollapsed(on){
|
||||
var sb = document.querySelector('.scoreboard');
|
||||
if(!sb) return;
|
||||
sb.classList.toggle('collapsed', on);
|
||||
var btn = sb.querySelector('.board-collapse');
|
||||
if(btn) btn.setAttribute('aria-expanded', String(!on));
|
||||
}
|
||||
function toggleScoreboard(){
|
||||
var sb = document.querySelector('.scoreboard');
|
||||
if(!sb) return;
|
||||
boardOverride = !sb.classList.contains('collapsed');
|
||||
setBoardCollapsed(boardOverride);
|
||||
}
|
||||
(function(){
|
||||
var bc = document.getElementById('boardCollapsed');
|
||||
if(bc) bc.addEventListener('keydown', function(e){ if(e.key === 'Enter' || e.key === ' '){ e.preventDefault(); toggleScoreboard(); } });
|
||||
})();
|
||||
|
||||
// Focus mode: hide the header + page heading during a game, revealed on demand.
|
||||
// Auto once scoring starts; the tab-row control overrides for the session and a
|
||||
// reload returns to automatic.
|
||||
var chromeOverride = null;
|
||||
function setChromeHidden(on){
|
||||
document.body.classList.toggle('game-focus', on);
|
||||
var btn = document.getElementById('focusToggle');
|
||||
if(btn){
|
||||
btn.setAttribute('aria-pressed', String(on));
|
||||
var lbl = btn.querySelector('.ft-label');
|
||||
if(lbl) lbl.textContent = on ? 'Show menu' : 'Hide top';
|
||||
}
|
||||
}
|
||||
function toggleFocus(){
|
||||
chromeOverride = !document.body.classList.contains('game-focus');
|
||||
setChromeHidden(chromeOverride);
|
||||
}
|
||||
|
||||
setWorkspaceView('live');
|
||||
renderWorkspace();
|
||||
@@ -1,23 +0,0 @@
|
||||
{
|
||||
"name": "Scorebook \u00b7 Baseball Scorecard",
|
||||
"short_name": "Scorebook",
|
||||
"description": "Digital baseball scorecard for tracking plays, lineups, and stats in real time.",
|
||||
"start_url": ".",
|
||||
"scope": ".",
|
||||
"display": "standalone",
|
||||
"orientation": "any",
|
||||
"background_color": "#f6f5ef",
|
||||
"theme_color": "#173e33",
|
||||
"icons": [
|
||||
{
|
||||
"src": "icon-192.png",
|
||||
"sizes": "192x192",
|
||||
"type": "image/png"
|
||||
},
|
||||
{
|
||||
"src": "icon-512.png",
|
||||
"sizes": "512x512",
|
||||
"type": "image/png"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,11 +1,15 @@
|
||||
{
|
||||
"name": "baseball-scorecard",
|
||||
"name": "baseballscorecard",
|
||||
"version": "1.0.0",
|
||||
"description": "A single-file baseball scorecard web app",
|
||||
"private": true,
|
||||
"description": "Live baseball scorecard web app (no build step). These dev dependencies are only for the tests.",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"test": "node --test tests/*.test.js"
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest"
|
||||
},
|
||||
"devDependencies": {
|
||||
"jsdom": "^24.1.3"
|
||||
"jsdom": "^25.0.1",
|
||||
"vitest": "^4.1.7"
|
||||
}
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
// Network-first service worker with a timeout: try GitHub Pages for the latest
|
||||
// version, but if it hasn't answered within NETWORK_TIMEOUT_MS (weak stadium
|
||||
// Wi-Fi) serve the cached copy instead. The network request keeps running in
|
||||
// the background and refreshes the cache, so the next open is up to date.
|
||||
// Fully offline, the cached copy is served right away.
|
||||
var CACHE = 'scorecard-v10';
|
||||
var NETWORK_TIMEOUT_MS = 3000;
|
||||
// The Firebase libraries (js/vendor/firebase) aren't precached: only signed-in
|
||||
// devices load them, and the fetch handler below caches them on first use.
|
||||
var ASSETS = [
|
||||
'./',
|
||||
'./index.html',
|
||||
'./css/app.css',
|
||||
'./css/scorebook.css',
|
||||
'./js/data.js',
|
||||
'./js/fields.js',
|
||||
'./js/game.js',
|
||||
'./js/scoring.js',
|
||||
'./js/render.js',
|
||||
'./js/scorecard.js',
|
||||
'./js/mlb.js',
|
||||
'./js/storage.js',
|
||||
'./js/reports.js',
|
||||
'./js/firebase-config.js',
|
||||
'./js/sync.js',
|
||||
'./js/follow.js',
|
||||
'./js/ui.js',
|
||||
'./js/workspace.js',
|
||||
'./assets/postseason/alds-2026.png',
|
||||
'./assets/postseason/nlds-2026.png',
|
||||
'./assets/postseason/alcs-2026.png',
|
||||
'./assets/postseason/nlcs-2026.png',
|
||||
'./assets/postseason/ws-2026.png',
|
||||
'./manifest.json',
|
||||
'./icon-192.png',
|
||||
'./icon-512.png',
|
||||
'./apple-touch-icon.png',
|
||||
'./favicon-32.png'
|
||||
];
|
||||
|
||||
self.addEventListener('install', function(e){
|
||||
e.waitUntil(
|
||||
caches.open(CACHE)
|
||||
.then(function(c){ return c.addAll(ASSETS); })
|
||||
.then(function(){ return self.skipWaiting(); })
|
||||
);
|
||||
});
|
||||
|
||||
self.addEventListener('activate', function(e){
|
||||
e.waitUntil(
|
||||
caches.keys().then(function(keys){
|
||||
// Only this app's caches: every app on kburchtree.cloud shares one cache store.
|
||||
return Promise.all(keys.filter(function(k){ return k.indexOf('scorecard-') === 0 && k !== CACHE; })
|
||||
.map(function(k){ return caches.delete(k); }));
|
||||
}).then(function(){ return self.clients.claim(); })
|
||||
);
|
||||
});
|
||||
|
||||
function fromCache(request){
|
||||
return caches.match(request, { ignoreSearch: true }).then(function(hit){
|
||||
// Any page navigation falls back to the app shell
|
||||
return hit || (request.mode === 'navigate' ? caches.match('./index.html') : undefined);
|
||||
});
|
||||
}
|
||||
|
||||
self.addEventListener('fetch', function(e){
|
||||
if(e.request.method !== 'GET') return;
|
||||
// Let cross-origin requests (MLB Stats API, team logos) pass through untouched.
|
||||
if(new URL(e.request.url).origin !== self.location.origin) return;
|
||||
|
||||
// Always revalidate with the server (cheap 304s) so a new index.html never
|
||||
// runs with older scripts from the browser's HTTP cache.
|
||||
var network = fetch(e.request, { cache: 'no-cache' }).then(function(resp){
|
||||
if(resp && resp.ok){
|
||||
var copy = resp.clone();
|
||||
caches.open(CACHE).then(function(c){ c.put(e.request, copy); });
|
||||
}
|
||||
return resp;
|
||||
});
|
||||
// Keep the worker alive until the background refresh finishes, even if the
|
||||
// cached copy was already served.
|
||||
e.waitUntil(network.catch(function(){}));
|
||||
|
||||
e.respondWith(new Promise(function(resolve, reject){
|
||||
var settled = false;
|
||||
function finish(resp){
|
||||
if(settled || !resp) return false;
|
||||
settled = true;
|
||||
resolve(resp);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Slow network: serve the cached copy if there is one; otherwise keep waiting.
|
||||
var timer = setTimeout(function(){
|
||||
fromCache(e.request).then(finish);
|
||||
}, NETWORK_TIMEOUT_MS);
|
||||
|
||||
network.then(function(resp){
|
||||
clearTimeout(timer);
|
||||
finish(resp);
|
||||
}).catch(function(){
|
||||
// Offline / request failed: cache now, or a real error if nothing cached.
|
||||
clearTimeout(timer);
|
||||
fromCache(e.request).then(function(hit){
|
||||
if(!finish(hit) && !settled) reject(new TypeError('offline and not cached'));
|
||||
});
|
||||
});
|
||||
}));
|
||||
});
|
||||
@@ -0,0 +1,226 @@
|
||||
// Tier 1 — pure game-logic tests.
|
||||
//
|
||||
// These exercise the scoring "rules engine": base-running advancement, run/RBI
|
||||
// crediting, runner lookup, sub-aware stat selection, and game-end detection.
|
||||
// Each test gets a fresh app instance (own window + own G) via loadApp().
|
||||
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { loadApp } from './helpers/loadApp.js';
|
||||
|
||||
let w; // the loaded app window — functions and G live here
|
||||
|
||||
beforeEach(() => {
|
||||
w = loadApp();
|
||||
});
|
||||
|
||||
describe('advanceRunners', () => {
|
||||
it('moves runners forward by N bases without overwriting', () => {
|
||||
// Runners on 1B and 3B, advance everyone 1 base.
|
||||
w.G.bases = ['R1', null, 'R3'];
|
||||
const runs = w.advanceRunners('away', 1);
|
||||
// R3 scores; R1 -> 2B.
|
||||
expect(runs).toBe(1);
|
||||
expect(w.G.bases).toEqual([null, 'R1', null]);
|
||||
});
|
||||
|
||||
it('processes 3B -> 1B so a trailing runner never clobbers a lead runner', () => {
|
||||
// Bases loaded, advance 1: the 3B->2B->1B order matters or names get lost.
|
||||
w.G.bases = ['R1', 'R2', 'R3'];
|
||||
const runs = w.advanceRunners('away', 1);
|
||||
expect(runs).toBe(1); // R3 scores
|
||||
expect(w.G.bases).toEqual([null, 'R1', 'R2']);
|
||||
});
|
||||
|
||||
it('scores every runner on a multi-base advance (e.g. HR with two on)', () => {
|
||||
w.G.bases = ['R1', null, 'R3'];
|
||||
const runs = w.advanceRunners('away', 4); // grand-slam-style clearing
|
||||
expect(runs).toBe(2);
|
||||
expect(w.G.bases).toEqual([null, null, null]);
|
||||
});
|
||||
|
||||
it('updates the running total and the current inning line score', () => {
|
||||
w.G.inning = 3;
|
||||
w.G.bases = [null, null, 'R3'];
|
||||
w.advanceRunners('away', 1);
|
||||
expect(w.G.rhe.away[0]).toBe(1);
|
||||
expect(w.G.scores.away[2]).toBe(1); // inning 3 -> index 2
|
||||
});
|
||||
});
|
||||
|
||||
describe('forceAdvance (walks / HBP / IBB)', () => {
|
||||
it('puts the batter on 1B with the bases empty and forces no one', () => {
|
||||
w.G.bases = [null, null, null];
|
||||
const runs = w.forceAdvance('away', 'Batter');
|
||||
expect(runs).toBe(0);
|
||||
expect(w.G.bases).toEqual(['Batter', null, null]);
|
||||
});
|
||||
|
||||
it('forces in a run only when the bases are loaded', () => {
|
||||
w.G.inning = 1;
|
||||
w.G.bases = ['R1', 'R2', 'R3'];
|
||||
const runs = w.forceAdvance('away', 'Batter');
|
||||
expect(runs).toBe(1); // R3 forced home
|
||||
expect(w.G.bases).toEqual(['Batter', 'R1', 'R2']);
|
||||
expect(w.G.rhe.away[0]).toBe(1);
|
||||
});
|
||||
|
||||
it('does NOT advance a non-forced runner (runner on 2B only)', () => {
|
||||
// Classic rule: with 1B open, the runner on 2B is not forced on a walk.
|
||||
w.G.bases = [null, 'R2', null];
|
||||
const runs = w.forceAdvance('away', 'Batter');
|
||||
expect(runs).toBe(0);
|
||||
expect(w.G.bases).toEqual(['Batter', 'R2', null]);
|
||||
});
|
||||
|
||||
it('advances the chain up to the first open base (runner on 1B only)', () => {
|
||||
w.G.bases = ['R1', null, null];
|
||||
const runs = w.forceAdvance('away', 'Batter');
|
||||
expect(runs).toBe(0);
|
||||
expect(w.G.bases).toEqual(['Batter', 'R1', null]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('findRunnerSlot', () => {
|
||||
beforeEach(() => {
|
||||
w.G.lineup.away[0].name = 'Alice';
|
||||
w.G.lineup.away[3].name = 'Bob';
|
||||
});
|
||||
|
||||
it('finds a runner by current lineup name', () => {
|
||||
expect(w.findRunnerSlot('away', 'Alice')).toBe(0);
|
||||
expect(w.findRunnerSlot('away', 'Bob')).toBe(3);
|
||||
});
|
||||
|
||||
it('returns -1 for unknown / sentinel runner values', () => {
|
||||
expect(w.findRunnerSlot('away', 'Nobody')).toBe(-1);
|
||||
expect(w.findRunnerSlot('away', '?')).toBe(-1);
|
||||
expect(w.findRunnerSlot('away', null)).toBe(-1);
|
||||
expect(w.findRunnerSlot('away', true)).toBe(-1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('creditRun / creditRBI', () => {
|
||||
it('credits the run to the slot of the runner who scored', () => {
|
||||
w.G.lineup.away[2].name = 'Scorer';
|
||||
w.creditRun('away', 'Scorer');
|
||||
expect(w.activeHits('away', 2).r).toBe(1);
|
||||
});
|
||||
|
||||
it('does not throw and credits nothing for an unknown runner', () => {
|
||||
const before = w.G.lineup.away.map((s) => s.hits.r);
|
||||
expect(() => w.creditRun('away', 'Ghost')).not.toThrow();
|
||||
expect(w.G.lineup.away.map((s) => s.hits.r)).toEqual(before);
|
||||
});
|
||||
|
||||
it('credits RBI(s) to the current batter', () => {
|
||||
w.G.awayBatter = 4;
|
||||
w.creditRBI('away', 2);
|
||||
expect(w.activeHits('away', 4).rbi).toBe(2);
|
||||
});
|
||||
|
||||
it('ignores zero / negative RBI counts', () => {
|
||||
w.G.awayBatter = 1;
|
||||
w.creditRBI('away', 0);
|
||||
w.creditRBI('away', -3);
|
||||
expect(w.activeHits('away', 1).rbi).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('activeHits (substitution-aware)', () => {
|
||||
it('returns the starter hits object when there are no subs', () => {
|
||||
expect(w.activeHits('home', 0)).toBe(w.G.lineup.home[0].hits);
|
||||
});
|
||||
|
||||
it('returns the latest sub hits object once a sub exists', () => {
|
||||
const sub = w.mkSlot();
|
||||
sub.name = 'Pinch';
|
||||
w.G.lineup.home[0].subs.push(sub);
|
||||
expect(w.activeHits('home', 0)).toBe(sub.hits);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isGameOver', () => {
|
||||
const setState = (over) => Object.assign(w.G, over);
|
||||
|
||||
it('is not over before the 9th inning', () => {
|
||||
setState({ inning: 8, half: 'bot', outs: 3 });
|
||||
w.G.rhe.home[0] = 5;
|
||||
w.G.rhe.away[0] = 3;
|
||||
expect(w.isGameOver()).toBe(false);
|
||||
});
|
||||
|
||||
it('ends after the bottom of the 9th when not tied', () => {
|
||||
setState({ inning: 9, half: 'bot', outs: 3 });
|
||||
w.G.rhe.home[0] = 5;
|
||||
w.G.rhe.away[0] = 3;
|
||||
expect(w.isGameOver()).toBe(true);
|
||||
});
|
||||
|
||||
it('continues into extras when tied after the bottom of the 9th', () => {
|
||||
setState({ inning: 9, half: 'bot', outs: 3 });
|
||||
w.G.rhe.home[0] = 3;
|
||||
w.G.rhe.away[0] = 3;
|
||||
expect(w.isGameOver()).toBe(false);
|
||||
});
|
||||
|
||||
it('ends after the top of the 9th if the home team already leads', () => {
|
||||
setState({ inning: 9, half: 'top', outs: 3 });
|
||||
w.G.rhe.home[0] = 5;
|
||||
w.G.rhe.away[0] = 3;
|
||||
expect(w.isGameOver()).toBe(true);
|
||||
});
|
||||
|
||||
it('requires the bottom of the 9th if the home team trails after the top', () => {
|
||||
setState({ inning: 9, half: 'top', outs: 3 });
|
||||
w.G.rhe.home[0] = 3;
|
||||
w.G.rhe.away[0] = 5;
|
||||
expect(w.isGameOver()).toBe(false);
|
||||
});
|
||||
|
||||
it('is not over mid-inning (fewer than 3 outs)', () => {
|
||||
setState({ inning: 9, half: 'bot', outs: 2 });
|
||||
w.G.rhe.home[0] = 5;
|
||||
w.G.rhe.away[0] = 3;
|
||||
expect(w.isGameOver()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('checkWalkoff', () => {
|
||||
it('flags a walk-off when the home team takes the lead in the bottom 9th+', () => {
|
||||
Object.assign(w.G, { inning: 9, half: 'bot' });
|
||||
w.G.rhe.home[0] = 4;
|
||||
w.G.rhe.away[0] = 3;
|
||||
expect(w.checkWalkoff()).toBe(true);
|
||||
});
|
||||
|
||||
it('is not a walk-off when the game is still tied', () => {
|
||||
Object.assign(w.G, { inning: 9, half: 'bot' });
|
||||
w.G.rhe.home[0] = 3;
|
||||
w.G.rhe.away[0] = 3;
|
||||
expect(w.checkWalkoff()).toBe(false);
|
||||
});
|
||||
|
||||
it('never fires in the top half of an inning', () => {
|
||||
Object.assign(w.G, { inning: 9, half: 'top' });
|
||||
w.G.rhe.home[0] = 4;
|
||||
w.G.rhe.away[0] = 3;
|
||||
expect(w.checkWalkoff()).toBe(false);
|
||||
});
|
||||
|
||||
it('never fires before the 9th inning', () => {
|
||||
Object.assign(w.G, { inning: 7, half: 'bot' });
|
||||
w.G.rhe.home[0] = 4;
|
||||
w.G.rhe.away[0] = 3;
|
||||
expect(w.checkWalkoff()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('recalc', () => {
|
||||
it('sums the inning line scores into the R total for each side', () => {
|
||||
w.G.scores.home = [1, 0, 2, null, 0, null, null, null, 1];
|
||||
w.G.scores.away = [0, 0, 0, 0, 0, 0, 0, 0, 0];
|
||||
w.recalc();
|
||||
expect(w.G.rhe.home[0]).toBe(4);
|
||||
expect(w.G.rhe.away[0]).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
// Test harness for the single-file baseball scorecard app.
|
||||
//
|
||||
// The whole app lives in index.html as inline <script>. Rather than refactor it
|
||||
// into modules, we load the real file into a jsdom window with scripts enabled.
|
||||
// Every top-level `function foo(){}` and `var x` in that script becomes a
|
||||
// property of the jsdom `window`, so tests can call the real game-logic
|
||||
// functions (window.advanceRunners, window.migrateGame, ...) and read/mutate the
|
||||
// real game state (window.G) exactly as the app does in a browser.
|
||||
//
|
||||
// init() runs on load. On a fresh DOM no team is selected, so init() never hits
|
||||
// the network (fetch/StatsAPI) — it only touches the DOM, which jsdom provides.
|
||||
|
||||
import { JSDOM } from 'jsdom';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { dirname, join } from 'node:path';
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const HTML_PATH = join(__dirname, '..', '..', 'index.html');
|
||||
const HTML = readFileSync(HTML_PATH, 'utf8');
|
||||
|
||||
// Load a fresh, fully-initialized copy of the app. Each call is isolated:
|
||||
// a new jsdom window with its own DOM, its own `G`, and its own localStorage.
|
||||
export function loadApp() {
|
||||
const dom = new JSDOM(HTML, {
|
||||
runScripts: 'dangerously',
|
||||
pretendToBeVisual: true, // provides requestAnimationFrame
|
||||
url: 'http://localhost/',
|
||||
});
|
||||
return dom.window;
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
// Tier 2 — schema migration tests.
|
||||
//
|
||||
// migrateGame() is documented in index.html as "the SINGLE source of truth for
|
||||
// backward compatibility". Every saved/imported game flows through it, so a
|
||||
// regression here silently corrupts (or fails to load) real user data. These
|
||||
// tests feed it old-shape fixtures and assert it backfills the current shape.
|
||||
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { loadApp } from './helpers/loadApp.js';
|
||||
|
||||
let w;
|
||||
|
||||
beforeEach(() => {
|
||||
w = loadApp();
|
||||
});
|
||||
|
||||
describe('migrateGame — defensive guards', () => {
|
||||
it('returns falsy input untouched', () => {
|
||||
expect(w.migrateGame(null)).toBe(null);
|
||||
expect(w.migrateGame(undefined)).toBe(undefined);
|
||||
});
|
||||
|
||||
it('mutates and returns the same object', () => {
|
||||
const g = {};
|
||||
expect(w.migrateGame(g)).toBe(g);
|
||||
});
|
||||
});
|
||||
|
||||
describe('migrateGame — v1 -> v2 (batterLog)', () => {
|
||||
it('adds a batterLog with both sides when missing', () => {
|
||||
const g = w.migrateGame({});
|
||||
expect(g.batterLog).toEqual({ home: {}, away: {} });
|
||||
});
|
||||
|
||||
it('fills in a missing side without dropping existing data', () => {
|
||||
const g = w.migrateGame({ batterLog: { home: { 0: 'X' } } });
|
||||
expect(g.batterLog.home).toEqual({ 0: 'X' });
|
||||
expect(g.batterLog.away).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
describe('migrateGame — v2 -> v3 (notes) and v3 -> v4 (abs)', () => {
|
||||
it('adds a notes object with the expected default keys', () => {
|
||||
const g = w.migrateGame({});
|
||||
expect(g.notes).toBeTypeOf('object');
|
||||
expect(g.notes).toMatchObject({ date: '', venue: '', weather: '' });
|
||||
});
|
||||
|
||||
it('adds ABS challenge tracking for both sides', () => {
|
||||
const g = w.migrateGame({});
|
||||
expect(g.abs).toEqual({
|
||||
home: { challenged: 0, overturned: 0 },
|
||||
away: { challenged: 0, overturned: 0 },
|
||||
});
|
||||
});
|
||||
|
||||
it('repairs a partially-present abs object', () => {
|
||||
const g = w.migrateGame({ abs: { home: { challenged: 2, overturned: 1 } } });
|
||||
expect(g.abs.home).toEqual({ challenged: 2, overturned: 1 });
|
||||
expect(g.abs.away).toEqual({ challenged: 0, overturned: 0 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('migrateGame — bases normalization (very early saves)', () => {
|
||||
it('converts legacy boolean bases to name/null form', () => {
|
||||
const g = w.migrateGame({ bases: [true, false, true] });
|
||||
expect(g.bases).toEqual(['?', null, '?']);
|
||||
});
|
||||
|
||||
it('leaves modern name/null bases alone', () => {
|
||||
const g = w.migrateGame({ bases: ['Alice', null, 'Bob'] });
|
||||
expect(g.bases).toEqual(['Alice', null, 'Bob']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('migrateGame — hit-key backfill on lineup slots and subs', () => {
|
||||
it('gives a slot with no hits object a full default hits object', () => {
|
||||
const g = w.migrateGame({
|
||||
lineup: { home: [{ name: 'NoHits', subs: [] }], away: [] },
|
||||
});
|
||||
const expected = w.mkHits();
|
||||
expect(g.lineup.home[0].hits).toEqual(expected);
|
||||
});
|
||||
|
||||
it('backfills newly-added hit keys onto an old (partial) hits object', () => {
|
||||
// Simulate a save made before `ibb` and `wp` existed.
|
||||
const partial = { s: 2, d: 1 }; // missing every other key
|
||||
const g = w.migrateGame({
|
||||
lineup: { home: [{ name: 'Old', hits: partial, subs: [] }], away: [] },
|
||||
});
|
||||
const hits = g.lineup.home[0].hits;
|
||||
expect(hits.s).toBe(2); // existing values preserved
|
||||
expect(hits.d).toBe(1);
|
||||
expect(hits.ibb).toBe(0); // new keys backfilled to 0
|
||||
expect(hits.wp).toBe(0);
|
||||
// Every key from the current schema is present.
|
||||
Object.keys(w.mkHits()).forEach((k) => {
|
||||
expect(hits[k]).toBeTypeOf('number');
|
||||
});
|
||||
});
|
||||
|
||||
it('backfills hits on subs from pre-per-sub-stats saves', () => {
|
||||
const g = w.migrateGame({
|
||||
lineup: {
|
||||
home: [{ name: 'Starter', hits: w.mkHits(), subs: [{ name: 'Sub' }] }],
|
||||
away: [],
|
||||
},
|
||||
});
|
||||
expect(g.lineup.home[0].subs[0].hits).toEqual(w.mkHits());
|
||||
});
|
||||
});
|
||||
|
||||
describe('migrateGame — a current-shape game is a no-op', () => {
|
||||
it('passes a freshly-created game through unchanged in structure', () => {
|
||||
const fresh = w.mkGame();
|
||||
const migrated = w.migrateGame(fresh);
|
||||
expect(migrated).toBe(fresh);
|
||||
expect(Object.keys(migrated.lineup.home[0].hits).sort()).toEqual(
|
||||
Object.keys(w.mkHits()).sort()
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,58 +0,0 @@
|
||||
// At-bat bar extras: the batter in your other saved games, and career vs the pitcher.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { loadApp, tick } = require('./helpers/app');
|
||||
|
||||
// Save a finished game where the away leadoff hitter had the given hits
|
||||
function saveGame(w, id, name, hits){
|
||||
const G = JSON.parse(JSON.stringify(w.G));
|
||||
G.lineup.away[0].name = name;
|
||||
Object.assign(G.lineup.away[0].hits, hits);
|
||||
G.log = [{ tag: 'Final', text: 'FINAL' }];
|
||||
w.localStorage.setItem(w.GM_GAME_PREFIX + id, JSON.stringify({ G, teamAway: 'New York Yankees', teamHome: 'Tampa Bay Rays' }));
|
||||
const index = w.gmGetIndex(); index.push({ id, away: 'New York Yankees', home: 'Tampa Bay Rays', savedAt: '2026-10-0' + index.length }); w.gmSaveIndex(index);
|
||||
}
|
||||
|
||||
function setup(t){
|
||||
const w = loadApp();
|
||||
t.after(() => w.close());
|
||||
w.document.getElementById('teamAway').value = 'New York Yankees';
|
||||
w.document.getElementById('teamHome').value = 'Tampa Bay Rays';
|
||||
w.G.lineup.away[0].name = 'Aaron Judge';
|
||||
w.G.pitchers.home[0].name = 'Drew Rasmussen';
|
||||
return w;
|
||||
}
|
||||
const extra = w => (w.document.querySelector('#atbatBar .atbat-extra') || {}).textContent || '';
|
||||
|
||||
test('shows how the batter hit in your other saved games (not this one)', (t) => {
|
||||
const w = setup(t);
|
||||
saveGame(w, 'a', 'Aaron Judge', { s: 1, hr: 1, ks: 2 }); // 2-for-4, HR
|
||||
saveGame(w, 'b', 'Aaron Judge', { d: 1, go: 2, bb: 1 }); // 1-for-3, BB
|
||||
w.recordHit(1); w.addBall(); w.renderAtBatBar(); // today's single isn't counted here
|
||||
w.G.awayBatter = 0; w.renderAtBatBar();
|
||||
assert.match(extra(w), /Your scorecards: 3-for-7 · 1 HR · 1 BB · 2 games/);
|
||||
});
|
||||
|
||||
test('no saved games for the batter: no line', (t) => {
|
||||
const w = setup(t);
|
||||
w.renderAtBatBar();
|
||||
assert.equal(extra(w), '');
|
||||
});
|
||||
|
||||
test('career vs the pitcher on the mound comes from MLB, once per matchup', async (t) => {
|
||||
const w = setup(t);
|
||||
w.ROSTERS.away = [{ id: 592450, name: 'Aaron Judge' }];
|
||||
w.ROSTERS.home = [{ id: 669373, name: 'Drew Rasmussen' }];
|
||||
const calls = [];
|
||||
w.fetch = url => {
|
||||
calls.push(url);
|
||||
const body = { stats: [{ type: { displayName: 'vsPlayerTotal' }, splits: [{ stat: { plateAppearances: 17, atBats: 15, hits: 7, homeRuns: 2, baseOnBalls: 2, strikeOuts: 5 } }] }] };
|
||||
return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve(body) });
|
||||
};
|
||||
w.renderAtBatBar();
|
||||
await tick(); await tick();
|
||||
assert.match(extra(w), /vs D\. Rasmussen: 7-for-15 · 2 HR · 2 BB/);
|
||||
w.renderAtBatBar(); w.renderAtBatBar();
|
||||
assert.equal(calls.filter(u => /vsPlayer/.test(u)).length, 1, 'asked MLB once');
|
||||
assert.match(calls[0], /people\/592450\/stats\?stats=vsPlayer&opposingPlayerId=669373/);
|
||||
});
|
||||
@@ -1 +0,0 @@
|
||||
{"copyright":"Copyright 2026 MLB Advanced Media, L.P. Use of any content on this page acknowledges agreement to the terms posted here http://gdx.mlb.com/components/copyright.txt","gamePk":849828,"link":"/api/v1.1/game/849828/feed/live","metaData":{"wait":10,"timeStamp":"20261003_225219","gameEvents":["field_out","game_finished"],"logicalEvents":["midInning","countChange","count02","newRightHandedHit","basesEmpty","gameStateChangeToGameOver"]},"gameData":{"game":{"pk":849828,"type":"D","doubleHeader":"N","id":"2026/10/03/atlmlb-lanmlb-1","gamedayType":"P","tiebreaker":"N","gameNumber":1,"calendarEventID":"14-849828-2026-10-03","season":"2026","seasonDisplay":"2026"},"datetime":{"dateTime":"2026-10-03T20:00:00Z","originalDate":"2026-10-03","officialDate":"2026-10-03","dayNight":"day","time":"1:00","ampm":"PM"},"status":{"abstractGameState":"Final","codedGameState":"F","detailedState":"Final","statusCode":"F","startTimeTBD":false,"abstractGameCode":"F"},"teams":{"away":{"springLeague":{"id":115,"name":"Grapefruit League","link":"/api/v1/league/115","abbreviation":"GL"},"allStarStatus":"N","id":144,"name":"Atlanta Braves","link":"/api/v1/teams/144","season":2026,"venue":{"id":4705,"name":"Truist Park","link":"/api/v1/venues/4705"},"springVenue":{"id":5380,"link":"/api/v1/venues/5380"},"teamCode":"atl","fileCode":"atl","abbreviation":"ATL","teamName":"Braves","locationName":"Atlanta","firstYearOfPlay":"1871","league":{"id":104,"name":"National League","link":"/api/v1/league/104"},"division":{"id":204,"name":"National League East","link":"/api/v1/divisions/204"},"sport":{"id":1,"link":"/api/v1/sports/1","name":"Major League Baseball"},"shortName":"Atlanta","record":{"gamesPlayed":1,"wildCardGamesBack":"-","leagueGamesBack":"-","springLeagueGamesBack":"-","sportGamesBack":"-","divisionGamesBack":"-","conferenceGamesBack":"-","leagueRecord":{"wins":0,"losses":1,"ties":0,"pct":".000"},"records":{},"divisionLeader":false,"wins":0,"losses":1,"winningPercentage":".000"},"franchiseName":"Atlanta","clubName":"Braves","active":true},"home":{"springLeague":{"id":114,"name":"Cactus League","link":"/api/v1/league/114","abbreviation":"CL"},"allStarStatus":"N","id":119,"name":"Los Angeles Dodgers","link":"/api/v1/teams/119","season":2026,"venue":{"id":22,"name":"UNIQLO Field at Dodger Stadium","link":"/api/v1/venues/22"},"springVenue":{"id":3809,"link":"/api/v1/venues/3809"},"teamCode":"lan","fileCode":"la","abbreviation":"LAD","teamName":"Dodgers","locationName":"Los Angeles","firstYearOfPlay":"1884","league":{"id":104,"name":"National League","link":"/api/v1/league/104"},"division":{"id":203,"name":"National League West","link":"/api/v1/divisions/203"},"sport":{"id":1,"link":"/api/v1/sports/1","name":"Major League Baseball"},"shortName":"LA Dodgers","record":{"gamesPlayed":1,"wildCardGamesBack":"-","leagueGamesBack":"-","springLeagueGamesBack":"-","sportGamesBack":"-","divisionGamesBack":"-","conferenceGamesBack":"-","leagueRecord":{"wins":1,"losses":0,"ties":0,"pct":"1.000"},"records":{},"divisionLeader":false,"wins":1,"losses":0,"winningPercentage":"1.000"},"franchiseName":"Los Angeles","clubName":"Dodgers","active":true}},"players":{"ID669257":{"id":669257,"fullName":"Will Smith"},"ID689266":{"id":689266,"fullName":"Dylan Dodd"},"ID669373":{"id":669373,"fullName":"Tarik Skubal"},"ID663158":{"id":663158,"fullName":"Robert Suarez"},"ID671739":{"id":671739,"fullName":"Michael Harris II"},"ID682989":{"id":682989,"fullName":"Victor Mederos"},"ID642133":{"id":642133,"fullName":"Rowdy Tellez"},"ID800311":{"id":800311,"fullName":"Didier Fuentes"},"ID571771":{"id":571771,"fullName":"Enrique Hern\u00e1ndez"},"ID571970":{"id":571970,"fullName":"Max Muncy"},"ID676551":{"id":676551,"fullName":"Brewer Hicklen"},"ID686948":{"id":686948,"fullName":"Drake Baldwin"},"ID518692":{"id":518692,"fullName":"Freddie Freeman"},"ID656945":{"id":656945,"fullName":"Tanner Scott"},"ID702275":{"id":702275,"fullName":"JR Ritchie"},"ID621566":{"id":621566,"fullName":"Matt Olson"},"ID669221":{"id":669221,"fullName":"Sean Murphy"},"ID623465":{"id":623465,"fullName":"Evan Phillips"},"ID621242":{"id":621242,"fullName":"Edwin D\u00edaz"},"ID645277":{"id":645277,"fullName":"Ozzie Albies"},"ID605483":{"id":605483,"fullName":"Blake Snell"},"ID800543":{"id":800543,"fullName":"Josue De Paula"},"ID656550":{"id":656550,"fullName":"Grant Holmes"},"ID573262":{"id":573262,"fullName":"Mike Yastrzemski"},"ID500743":{"id":500743,"fullName":"Miguel Rojas"},"ID657041":{"id":657041,"fullName":"Lane Thomas"},"ID608718":{"id":608718,"fullName":"Brent Suter"},"ID669276":{"id":669276,"fullName":"Dylan Lee"},"ID700363":{"id":700363,"fullName":"AJ Smith-Shawver"},"ID607192":{"id":607192,"fullName":"Tyler Glasnow"},"ID681911":{"id":681911,"fullName":"Alex Vesia"},"ID663656":{"id":663656,"fullName":"Kyle Tucker"},"ID643289":{"id":643289,"fullName":"Mauricio Dub\u00f3n"},"ID641816":{"id":641816,"fullName":"Tyler Mahle"},"ID519242":{"id":519242,"fullName":"Chris Sale"},"ID683618":{"Line truncated
|
||||
@@ -1 +0,0 @@
|
||||
{"copyright":"Copyright 2026 MLB Advanced Media, L.P. Use of any content on this page acknowledges agreement to the terms posted here http://gdx.mlb.com/components/copyright.txt","gamePk":849829,"link":"/api/v1.1/game/849829/feed/live","metaData":{"wait":10,"timeStamp":"20261003_195738","gameEvents":["strikeout","game_finished"],"logicalEvents":["midInning","countChange","count03","gameStateChangeToGameOver"]},"gameData":{"game":{"pk":849829,"type":"D","doubleHeader":"N","id":"2026/10/03/chamlb-clemlb-1","gamedayType":"P","tiebreaker":"N","gameNumber":1,"calendarEventID":"14-849829-2026-10-03","season":"2026","seasonDisplay":"2026"},"datetime":{"dateTime":"2026-10-03T17:00:00Z","originalDate":"2026-10-03","officialDate":"2026-10-03","dayNight":"day","time":"1:00","ampm":"PM"},"status":{"abstractGameState":"Final","codedGameState":"F","detailedState":"Final","statusCode":"F","startTimeTBD":false,"abstractGameCode":"F"},"teams":{"away":{"springLeague":{"id":114,"name":"Cactus League","link":"/api/v1/league/114","abbreviation":"CL"},"allStarStatus":"N","id":145,"name":"Chicago White Sox","link":"/api/v1/teams/145","season":2026,"venue":{"id":4,"name":"Rate Field","link":"/api/v1/venues/4"},"springVenue":{"id":3809,"link":"/api/v1/venues/3809"},"teamCode":"cha","fileCode":"cws","abbreviation":"CWS","teamName":"White Sox","locationName":"Chicago","firstYearOfPlay":"1901","league":{"id":103,"name":"American League","link":"/api/v1/league/103"},"division":{"id":202,"name":"American League Central","link":"/api/v1/divisions/202"},"sport":{"id":1,"link":"/api/v1/sports/1","name":"Major League Baseball"},"shortName":"Chi White Sox","record":{"gamesPlayed":1,"wildCardGamesBack":"-","leagueGamesBack":"-","springLeagueGamesBack":"-","sportGamesBack":"-","divisionGamesBack":"-","conferenceGamesBack":"-","leagueRecord":{"wins":1,"losses":0,"ties":0,"pct":"1.000"},"records":{},"divisionLeader":false,"wins":1,"losses":0,"winningPercentage":"1.000"},"franchiseName":"Chicago","clubName":"White Sox","active":true},"home":{"springLeague":{"id":114,"name":"Cactus League","link":"/api/v1/league/114","abbreviation":"CL"},"allStarStatus":"N","id":114,"name":"Cleveland Guardians","link":"/api/v1/teams/114","season":2026,"venue":{"id":5,"name":"Progressive Field","link":"/api/v1/venues/5"},"springVenue":{"id":3834,"link":"/api/v1/venues/3834"},"teamCode":"cle","fileCode":"cle","abbreviation":"CLE","teamName":"Guardians","locationName":"Cleveland","firstYearOfPlay":"1901","league":{"id":103,"name":"American League","link":"/api/v1/league/103"},"division":{"id":202,"name":"American League Central","link":"/api/v1/divisions/202"},"sport":{"id":1,"link":"/api/v1/sports/1","name":"Major League Baseball"},"shortName":"Cleveland","record":{"gamesPlayed":1,"wildCardGamesBack":"-","leagueGamesBack":"-","springLeagueGamesBack":"-","sportGamesBack":"-","divisionGamesBack":"-","conferenceGamesBack":"-","leagueRecord":{"wins":0,"losses":1,"ties":0,"pct":".000"},"records":{},"divisionLeader":false,"wins":0,"losses":1,"winningPercentage":".000"},"franchiseName":"Cleveland","clubName":"Guardians","active":true}},"players":{"ID671976":{"id":671976,"fullName":"Tristan Peters"},"ID542888":{"id":542888,"fullName":"Shawn Armstrong"},"ID663436":{"id":663436,"fullName":"Davis Martin"},"ID682668":{"id":682668,"fullName":"Luisangel Acu\u00f1a"},"ID595978":{"id":595978,"fullName":"Austin Hedges"},"ID663993":{"id":663993,"fullName":"Nathaniel Lowe"},"ID689818":{"id":689818,"fullName":"David Sandlin"},"ID683953":{"id":683953,"fullName":"Travis Bazzana"},"ID808959":{"id":808959,"fullName":"Munetaka Murakami"},"ID691019":{"id":691019,"fullName":"Kyle Teel"},"ID805367":{"id":805367,"fullName":"Chase Meidroth"},"ID672275":{"id":672275,"fullName":"Patrick Bailey"},"ID695657":{"id":695657,"fullName":"Colson Montgomery"},"ID695731":{"id":695731,"fullName":"Braden Montgomery"},"ID702273":{"id":702273,"fullName":"Noah Schultz"},"ID696146":{"id":696146,"fullName":"Hagen Smith"},"ID681807":{"id":681807,"fullName":"David Fry"},"ID671922":{"id":671922,"fullName":"Cade Smith"},"ID608070":{"id":608070,"fullName":"Jos\u00e9 Ram\u00edrez"},"ID643217":{"id":643217,"fullName":"Andrew Benintendi"},"ID680757":{"id":680757,"fullName":"Steven Kwan"},"ID682657":{"id":682657,"fullName":"Angel Mart\u00ednez"},"ID686668":{"id":686668,"fullName":"Brenton Doyle"},"ID656794":{"id":656794,"fullName":"Sean Newcomb"},"ID682982":{"id":682982,"fullName":"Daniel Espino"},"ID803011":{"id":803011,"fullName":"Sam Antonacci"},"ID678246":{"id":678246,"fullName":"Miguel Vargas"},"ID694197":{"id":694197,"fullName":"Angel Genao"},"ID641743":{"id":641743,"fullName":"Anthony Kay"},"ID800050":{"id":800050,"fullName":"Chase DeLauter"},"ID545341":{"id":545341,"fullName":"Randal Grichuk"},"ID682177":{"id":682177,"fullName":"Daniel Schneemann"},"ID691799":{"id":691799,"fullName":"Grant Taylor"},"ID502054":{"id":502054,"fullName":"Tommy Pham"},"ID677587":{"id":677587,"fullName":"Brayan Rocchio"},"ID690984":{"iLine truncated
|
||||
@@ -1 +0,0 @@
|
||||
{"copyright":"Copyright 2026 MLB Advanced Media, L.P. Use of any content on this page acknowledges agreement to the terms posted here http://gdx.mlb.com/components/copyright.txt","gamePk":849830,"link":"/api/v1.1/game/849830/feed/live","metaData":{"wait":10,"timeStamp":"20261004_040705","gameEvents":["field_out","game_finished"],"logicalEvents":["midInning","countChange","count01","newLeftHandedHit","basesEmpty","gameStateChangeToGameOver"]},"gameData":{"game":{"pk":849830,"type":"D","doubleHeader":"N","id":"2026/10/03/sdnmlb-milmlb-1","gamedayType":"P","tiebreaker":"N","gameNumber":1,"calendarEventID":"14-849830-2026-10-03","season":"2026","seasonDisplay":"2026"},"datetime":{"dateTime":"2026-10-04T00:30:00Z","originalDate":"2026-10-03","officialDate":"2026-10-03","dayNight":"night","time":"7:30","ampm":"PM"},"status":{"abstractGameState":"Final","codedGameState":"F","detailedState":"Final","statusCode":"F","startTimeTBD":false,"abstractGameCode":"F"},"teams":{"away":{"springLeague":{"id":114,"name":"Cactus League","link":"/api/v1/league/114","abbreviation":"CL"},"allStarStatus":"N","id":135,"name":"San Diego Padres","link":"/api/v1/teams/135","season":2026,"venue":{"id":2680,"name":"Petco Park","link":"/api/v1/venues/2680"},"springVenue":{"id":2530,"link":"/api/v1/venues/2530"},"teamCode":"sdn","fileCode":"sd","abbreviation":"SD","teamName":"Padres","locationName":"San Diego","firstYearOfPlay":"1968","league":{"id":104,"name":"National League","link":"/api/v1/league/104"},"division":{"id":203,"name":"National League West","link":"/api/v1/divisions/203"},"sport":{"id":1,"link":"/api/v1/sports/1","name":"Major League Baseball"},"shortName":"San Diego","record":{"gamesPlayed":1,"wildCardGamesBack":"-","leagueGamesBack":"-","springLeagueGamesBack":"-","sportGamesBack":"-","divisionGamesBack":"-","conferenceGamesBack":"-","leagueRecord":{"wins":0,"losses":1,"ties":0,"pct":".000"},"records":{},"divisionLeader":false,"wins":0,"losses":1,"winningPercentage":".000"},"franchiseName":"San Diego","clubName":"Padres","active":true},"home":{"springLeague":{"id":114,"name":"Cactus League","link":"/api/v1/league/114","abbreviation":"CL"},"allStarStatus":"N","id":158,"name":"Milwaukee Brewers","link":"/api/v1/teams/158","season":2026,"venue":{"id":32,"name":"American Family Field","link":"/api/v1/venues/32"},"springVenue":{"id":2518,"link":"/api/v1/venues/2518"},"teamCode":"mil","fileCode":"mil","abbreviation":"MIL","teamName":"Brewers","locationName":"Milwaukee","firstYearOfPlay":"1968","league":{"id":104,"name":"National League","link":"/api/v1/league/104"},"division":{"id":205,"name":"National League Central","link":"/api/v1/divisions/205"},"sport":{"id":1,"link":"/api/v1/sports/1","name":"Major League Baseball"},"shortName":"Milwaukee","record":{"gamesPlayed":1,"wildCardGamesBack":"-","leagueGamesBack":"-","springLeagueGamesBack":"-","sportGamesBack":"-","divisionGamesBack":"-","conferenceGamesBack":"-","leagueRecord":{"wins":1,"losses":0,"ties":0,"pct":"1.000"},"records":{},"divisionLeader":false,"wins":1,"losses":0,"winningPercentage":"1.000"},"franchiseName":"Milwaukee","clubName":"Brewers","active":true}},"players":{"ID669134":{"id":669134,"fullName":"Luis Campusano"},"ID673513":{"id":673513,"fullName":"Yuki Matsui"},"ID666023":{"id":666023,"fullName":"Freddy Fermin"},"ID650633":{"id":650633,"fullName":"Michael King"},"ID687401":{"id":687401,"fullName":"Joey Ortiz"},"ID605397":{"id":605397,"fullName":"Joe Musgrove"},"ID687957":{"id":687957,"fullName":"Dustin Harris"},"ID675660":{"id":675660,"fullName":"Shane Drohan"},"ID657757":{"id":657757,"fullName":"Gavin Sheets"},"ID670970":{"id":670970,"fullName":"Adrian Morejon"},"ID592518":{"id":592518,"fullName":"Manny Machado"},"ID609280":{"id":609280,"fullName":"Miguel Andujar"},"ID666152":{"id":666152,"fullName":"David Hamilton"},"ID661388":{"id":661388,"fullName":"William Contreras"},"ID668930":{"id":668930,"fullName":"Brice Turang"},"ID687749":{"id":687749,"fullName":"Jase Bowen"},"ID630105":{"id":630105,"fullName":"Jake Cronenworth"},"ID622608":{"id":622608,"fullName":"Antonio Senzatela"},"ID694477":{"id":694477,"fullName":"Chad Patrick"},"ID695243":{"id":695243,"fullName":"Mason Miller"},"ID806198":{"id":806198,"fullName":"Cooper Pratt"},"ID701656":{"id":701656,"fullName":"Logan Henderson"},"ID694192":{"id":694192,"fullName":"Jackson Chourio"},"ID688158":{"id":688158,"fullName":"David Morgan"},"ID592885":{"id":592885,"fullName":"Christian Yelich"},"ID641343":{"id":641343,"fullName":"Jake Bauers"},"ID701538":{"id":701538,"fullName":"Jackson Merrill"},"ID686217":{"id":686217,"fullName":"Sal Frelick"},"ID682842":{"id":682842,"fullName":"Abner Uribe"},"ID668941":{"id":668941,"fullName":"JoJo Romero"},"ID592094":{"id":592094,"fullName":"Jason Adam"},"ID683734":{"id":683734,"fullName":"Andrew Vaughn"},"ID699134":{"id":699134,"fullName":"Bradgley Rodriguez"},"ID669392":{"id":669392,"fullName":"Samad Taylor"},"ID690986":{"id":690986,"fullName":"Kyle Harrison"},"ID806956":{Line truncated
|
||||
@@ -1 +0,0 @@
|
||||
{"copyright":"Copyright 2026 MLB Advanced Media, L.P. Use of any content on this page acknowledges agreement to the terms posted here http://gdx.mlb.com/components/copyright.txt","gamePk":849835,"link":"/api/v1.1/game/849835/feed/live","metaData":{"wait":10,"timeStamp":"20261004_010846","gameEvents":["field_out","game_finished"],"logicalEvents":["midInning","countChange","count21","newLeftHandedHit","gameStateChangeToGameOver"]},"gameData":{"game":{"pk":849835,"type":"D","doubleHeader":"N","id":"2026/10/03/nyamlb-tbamlb-1","gamedayType":"P","tiebreaker":"N","gameNumber":1,"calendarEventID":"14-849835-2026-10-03","season":"2026","seasonDisplay":"2026"},"datetime":{"dateTime":"2026-10-03T22:30:00Z","originalDate":"2026-10-03","officialDate":"2026-10-03","dayNight":"night","time":"6:30","ampm":"PM"},"status":{"abstractGameState":"Final","codedGameState":"F","detailedState":"Final","statusCode":"F","startTimeTBD":false,"abstractGameCode":"F"},"teams":{"away":{"springLeague":{"id":115,"name":"Grapefruit League","link":"/api/v1/league/115","abbreviation":"GL"},"allStarStatus":"N","id":147,"name":"New York Yankees","link":"/api/v1/teams/147","season":2026,"venue":{"id":3313,"name":"Yankee Stadium","link":"/api/v1/venues/3313"},"springVenue":{"id":2523,"link":"/api/v1/venues/2523"},"teamCode":"nya","fileCode":"nyy","abbreviation":"NYY","teamName":"Yankees","locationName":"Bronx","firstYearOfPlay":"1903","league":{"id":103,"name":"American League","link":"/api/v1/league/103"},"division":{"id":201,"name":"American League East","link":"/api/v1/divisions/201"},"sport":{"id":1,"link":"/api/v1/sports/1","name":"Major League Baseball"},"shortName":"NY Yankees","record":{"gamesPlayed":1,"wildCardGamesBack":"-","leagueGamesBack":"-","springLeagueGamesBack":"-","sportGamesBack":"-","divisionGamesBack":"-","conferenceGamesBack":"-","leagueRecord":{"wins":0,"losses":1,"ties":0,"pct":".000"},"records":{},"divisionLeader":false,"wins":0,"losses":1,"winningPercentage":".000"},"franchiseName":"New York","clubName":"Yankees","active":true},"home":{"springLeague":{"id":115,"name":"Grapefruit League","link":"/api/v1/league/115","abbreviation":"GL"},"allStarStatus":"N","id":139,"name":"Tampa Bay Rays","link":"/api/v1/teams/139","season":2026,"venue":{"id":12,"name":"Tropicana Field","link":"/api/v1/venues/12"},"springVenue":{"id":2534,"link":"/api/v1/venues/2534"},"teamCode":"tba","fileCode":"tb","abbreviation":"TB","teamName":"Rays","locationName":"St. Petersburg","firstYearOfPlay":"1996","league":{"id":103,"name":"American League","link":"/api/v1/league/103"},"division":{"id":201,"name":"American League East","link":"/api/v1/divisions/201"},"sport":{"id":1,"link":"/api/v1/sports/1","name":"Major League Baseball"},"shortName":"Tampa Bay","record":{"gamesPlayed":1,"wildCardGamesBack":"-","leagueGamesBack":"-","springLeagueGamesBack":"-","sportGamesBack":"-","divisionGamesBack":"-","conferenceGamesBack":"-","leagueRecord":{"wins":1,"losses":0,"ties":0,"pct":"1.000"},"records":{},"divisionLeader":false,"wins":1,"losses":0,"winningPercentage":"1.000"},"franchiseName":"Tampa Bay","clubName":"Rays","active":true}},"players":{"ID670764":{"id":670764,"fullName":"Taylor Walls"},"ID621112":{"id":621112,"fullName":"Paul Blackburn"},"ID669330":{"id":669330,"fullName":"Tyler Wells"},"ID671218":{"id":671218,"fullName":"Heliot Ramos"},"ID571927":{"id":571927,"fullName":"Steven Matz"},"ID682987":{"id":682987,"fullName":"Spencer Jones"},"ID622761":{"id":622761,"fullName":"Jorge Mateo"},"ID668723":{"id":668723,"fullName":"Ryan Vilade"},"ID802415":{"id":802415,"fullName":"Chandler Simpson"},"ID607259":{"id":607259,"fullName":"Nick Martinez"},"ID592155":{"id":592155,"fullName":"Cam Booser"},"ID676356":{"id":676356,"fullName":"Jonny DeLuca"},"ID677960":{"id":677960,"fullName":"Ryan Weathers"},"ID502671":{"id":502671,"fullName":"Paul Goldschmidt"},"ID669224":{"id":669224,"fullName":"Austin Wells"},"ID642121":{"id":642121,"fullName":"Cole Sulser"},"ID700250":{"id":700250,"fullName":"Ben Rice"},"ID687396":{"id":687396,"fullName":"Brent Headrick"},"ID701542":{"id":701542,"fullName":"Will Warren"},"ID689414":{"id":689414,"fullName":"Liam Hicks"},"ID641355":{"id":641355,"fullName":"Cody Bellinger"},"ID519317":{"id":519317,"fullName":"Giancarlo Stanton"},"ID643377":{"id":643377,"fullName":"Griffin Jax"},"ID665862":{"id":665862,"fullName":"Jazz Chisholm Jr."},"ID650490":{"id":650490,"fullName":"Yandy D\u00edaz"},"ID810938":{"id":810938,"fullName":"Ben Williamson"},"ID663757":{"id":663757,"fullName":"Trent Grisham"},"ID683748":{"id":683748,"fullName":"Victor Mesa Jr."},"ID670280":{"id":670280,"fullName":"David Bednar"},"ID543037":{"id":543037,"fullName":"Gerrit Cole"},"ID691406":{"id":691406,"fullName":"Junior Caminero"},"ID656876":{"id":656876,"fullName":"Drew Rasmussen"},"ID670167":{"id":670167,"fullName":"John Schreiber"},"ID645305":{"id":645305,"fullName":"Ali S\u00e1nchez"},"ID676609":{"id":676609,"fullName":"Jos\u00e9 Caballero"},"ID607074":{"id":607074,"Line truncated
|
||||
@@ -1 +0,0 @@
|
||||
{"copyright":"Copyright 2026 MLB Advanced Media, L.P. Use of any content on this page acknowledges agreement to the terms posted here http://gdx.mlb.com/components/copyright.txt","gamePk":849839,"link":"/api/v1.1/game/849839/feed/live","metaData":{"wait":10,"timeStamp":"20261006_015227","gameEvents":["at_bat_start"],"logicalEvents":["countChange","count00","newBatter","batterSwitchedToRightHanded"]},"gameData":{"game":{"pk":849839,"type":"D","doubleHeader":"N","id":"2026/10/05/nyamlb-tbamlb-1","gamedayType":"P","tiebreaker":"N","gameNumber":1,"calendarEventID":"14-849839-2026-10-05","season":"2026","seasonDisplay":"2026"},"datetime":{"dateTime":"2026-10-06T00:00:00Z","originalDate":"2026-10-05","officialDate":"2026-10-05","dayNight":"night","time":"8:00","ampm":"PM"},"status":{"abstractGameState":"Live","codedGameState":"I","detailedState":"In Progress","statusCode":"I","startTimeTBD":false,"abstractGameCode":"L"},"teams":{"away":{"springLeague":{"id":115,"name":"Grapefruit League","link":"/api/v1/league/115","abbreviation":"GL"},"allStarStatus":"N","id":147,"name":"New York Yankees","link":"/api/v1/teams/147","season":2026,"venue":{"id":3313,"name":"Yankee Stadium","link":"/api/v1/venues/3313"},"springVenue":{"id":2523,"link":"/api/v1/venues/2523"},"teamCode":"nya","fileCode":"nyy","abbreviation":"NYY","teamName":"Yankees","locationName":"Bronx","firstYearOfPlay":"1903","league":{"id":103,"name":"American League","link":"/api/v1/league/103"},"division":{"id":201,"name":"American League East","link":"/api/v1/divisions/201"},"sport":{"id":1,"link":"/api/v1/sports/1","name":"Major League Baseball"},"shortName":"NY Yankees","record":{"gamesPlayed":1,"wildCardGamesBack":"-","leagueGamesBack":"-","springLeagueGamesBack":"-","sportGamesBack":"-","divisionGamesBack":"-","conferenceGamesBack":"-","leagueRecord":{"wins":0,"losses":1,"ties":0,"pct":".000"},"records":{},"divisionLeader":false,"wins":0,"losses":1,"winningPercentage":".000"},"franchiseName":"New York","clubName":"Yankees","active":true},"home":{"springLeague":{"id":115,"name":"Grapefruit League","link":"/api/v1/league/115","abbreviation":"GL"},"allStarStatus":"N","id":139,"name":"Tampa Bay Rays","link":"/api/v1/teams/139","season":2026,"venue":{"id":12,"name":"Tropicana Field","link":"/api/v1/venues/12"},"springVenue":{"id":2534,"link":"/api/v1/venues/2534"},"teamCode":"tba","fileCode":"tb","abbreviation":"TB","teamName":"Rays","locationName":"St. Petersburg","firstYearOfPlay":"1996","league":{"id":103,"name":"American League","link":"/api/v1/league/103"},"division":{"id":201,"name":"American League East","link":"/api/v1/divisions/201"},"sport":{"id":1,"link":"/api/v1/sports/1","name":"Major League Baseball"},"shortName":"Tampa Bay","record":{"gamesPlayed":1,"wildCardGamesBack":"-","leagueGamesBack":"-","springLeagueGamesBack":"-","sportGamesBack":"-","divisionGamesBack":"-","conferenceGamesBack":"-","leagueRecord":{"wins":1,"losses":0,"ties":0,"pct":"1.000"},"records":{},"divisionLeader":false,"wins":1,"losses":0,"winningPercentage":"1.000"},"franchiseName":"Tampa Bay","clubName":"Rays","active":true}},"players":{"ID670764":{"id":670764,"fullName":"Taylor Walls","link":"/api/v1/people/670764","firstName":"Taylor","lastName":"Walls","primaryNumber":"6","birthDate":"1996-07-10","currentAge":30,"birthCity":"Cordele","birthStateProvince":"GA","birthCountry":"USA","height":"5' 9\"","weight":185,"active":true,"primaryPosition":{"code":"6","name":"Shortstop","type":"Infielder","abbreviation":"SS"},"useName":"Taylor","useLastName":"Walls","boxscoreName":"Walls","gender":"M","isPlayer":true,"isVerified":true,"draftYear":2017,"mlbDebutDate":"2021-05-22","batSide":{"code":"S","description":"Switch"},"pitchHand":{"code":"R","description":"Right"},"nameFirstLast":"Taylor Walls","nameSlug":"taylor-walls-670764","firstLastName":"Taylor Walls","lastFirstName":"Walls, Taylor","lastInitName":"Walls, T","initLastName":"T Walls","fullFMLName":"Taylor Walls","fullLFMName":"Walls, Taylor","strikeZoneTop":3.056,"strikeZoneBottom":1.542},"ID621112":{"id":621112,"fullName":"Paul Blackburn","link":"/api/v1/people/621112","firstName":"Paul","lastName":"Blackburn","primaryNumber":"58","birthDate":"1993-12-04","currentAge":32,"birthCity":"Antioch","birthStateProvince":"CA","birthCountry":"USA","height":"6' 1\"","weight":196,"active":true,"primaryPosition":{"code":"1","name":"Pitcher","type":"Pitcher","abbreviation":"P"},"useName":"Paul","useLastName":"Blackburn","middleName":"Cady","boxscoreName":"Blackburn, P","nickName":"Blackie","gender":"M","isPlayer":true,"isVerified":true,"draftYear":2012,"mlbDebutDate":"2017-07-01","batSide":{"code":"R","description":"Right"},"pitchHand":{"code":"R","description":"Right"},"nameFirstLast":"Paul Blackburn","nameSlug":"paul-blackburn-621112","firstLastName":"Paul Blackburn","lastFirstName":"Blackburn, Paul","lastInitName":"Blackburn, P","initLastName":"P Blackburn","fullFMLName":"Paul Cady Blackburn","fullLFMName":"Blackburn, Paul Cady","strLine truncated
|
||||
@@ -1 +0,0 @@
|
||||
{"copyright":"Copyright 2026 MLB Advanced Media, L.P. Use of any content on this page acknowledges agreement to the terms posted here http://gdx.mlb.com/components/copyright.txt","totalItems":4,"totalEvents":0,"totalGames":4,"totalGamesInProgress":0,"dates":[{"date":"2026-10-03","totalItems":4,"totalEvents":0,"totalGames":4,"totalGamesInProgress":0,"games":[{"gamePk":849829,"gameGuid":"c912c124-b09b-4ece-91b9-56e70e3f3ab0","link":"/api/v1.1/game/849829/feed/live","gameType":"D","season":"2026","gameDate":"2026-10-03T17:00:00Z","officialDate":"2026-10-03","status":{"abstractGameState":"Final","codedGameState":"F","detailedState":"Final","statusCode":"F","startTimeTBD":false,"abstractGameCode":"F"},"teams":{"away":{"team":{"id":145,"name":"Chicago White Sox","link":"/api/v1/teams/145"},"leagueRecord":{"wins":1,"losses":0,"ties":0,"pct":"1.000"},"score":3,"isWinner":true,"probablePitcher":{"id":696146,"fullName":"Hagen Smith","link":"/api/v1/people/696146"},"splitSquad":false,"seriesNumber":2},"home":{"team":{"id":114,"name":"Cleveland Guardians","link":"/api/v1/teams/114"},"leagueRecord":{"wins":0,"losses":1,"ties":0,"pct":".000"},"score":0,"isWinner":false,"probablePitcher":{"id":800048,"fullName":"Parker Messick","link":"/api/v1/people/800048"},"splitSquad":false,"seriesNumber":2}},"venue":{"id":5,"name":"Progressive Field","link":"/api/v1/venues/5"},"content":{"link":"/api/v1/game/849829/content"},"isTie":false,"gameNumber":1,"publicFacing":true,"doubleHeader":"N","gamedayType":"P","tiebreaker":"N","calendarEventID":"14-849829-2026-10-03","seasonDisplay":"2026","dayNight":"day","description":"ALDS 'B' Game 1","scheduledInnings":9,"reverseHomeAwayStatus":false,"inningBreakLength":175,"gamesInSeries":5,"seriesGameNumber":1,"seriesDescription":"AL Division Series","recordSource":"S","ifNecessary":"N","ifNecessaryDescription":"Normal Game","lineups":{"homePlayers":[{"id":680757,"fullName":"Steven Kwan","link":"/api/v1/people/680757","firstName":"Steven","lastName":"Kwan","primaryPosition":{"code":"8","name":"Outfielder","type":"Outfielder","abbreviation":"CF"},"useName":"Steven"},{"id":608070,"fullName":"Jos\u00e9 Ram\u00edrez","link":"/api/v1/people/608070","firstName":"Jos\u00e9","lastName":"Ram\u00edrez","primaryPosition":{"code":"5","name":"Third Base","type":"Infielder","abbreviation":"3B"},"useName":"Jos\u00e9"},{"id":800050,"fullName":"Chase DeLauter","link":"/api/v1/people/800050","firstName":"Chase","lastName":"DeLauter","primaryPosition":{"code":"9","name":"Outfielder","type":"Outfielder","abbreviation":"RF"},"useName":"Chase"},{"id":666176,"fullName":"Jo Adell","link":"/api/v1/people/666176","firstName":"Jordon","lastName":"Adell","primaryPosition":{"code":"10","name":"Designated Hitter","type":"Hitter","abbreviation":"DH"},"useName":"Jo"},{"id":682657,"fullName":"Angel Mart\u00ednez","link":"/api/v1/people/682657","firstName":"Angel","lastName":"Mart\u00ednez","primaryPosition":{"code":"7","name":"Outfielder","type":"Outfielder","abbreviation":"LF"},"useName":"Angel"},{"id":681807,"fullName":"David Fry","link":"/api/v1/people/681807","firstName":"David","lastName":"Fry","primaryPosition":{"code":"3","name":"First Base","type":"Infielder","abbreviation":"1B"},"useName":"David"},{"id":683953,"fullName":"Travis Bazzana","link":"/api/v1/people/683953","firstName":"Travis","lastName":"Bazzana","primaryPosition":{"code":"4","name":"Second Base","type":"Infielder","abbreviation":"2B"},"useName":"Travis"},{"id":595978,"fullName":"Austin Hedges","link":"/api/v1/people/595978","firstName":"Austin","lastName":"Hedges","primaryPosition":{"code":"2","name":"Catcher","type":"Catcher","abbreviation":"C"},"useName":"Austin"},{"id":677587,"fullName":"Brayan Rocchio","link":"/api/v1/people/677587","firstName":"Brayan","lastName":"Rocchio","primaryPosition":{"code":"6","name":"Shortstop","type":"Infielder","abbreviation":"SS"},"useName":"Brayan"}],"awayPlayers":[{"id":805367,"fullName":"Chase Meidroth","link":"/api/v1/people/805367","firstName":"Chase","lastName":"Meidroth","primaryPosition":{"code":"4","name":"Second Base","type":"Infielder","abbreviation":"2B"},"useName":"Chase"},{"id":545341,"fullName":"Randal Grichuk","link":"/api/v1/people/545341","firstName":"Randal","lastName":"Grichuk","primaryPosition":{"code":"7","name":"Outfielder","type":"Outfielder","abbreviation":"LF"},"useName":"Randal"},{"id":678246,"fullName":"Miguel Vargas","link":"/api/v1/people/678246","firstName":"Miguel","lastName":"Vargas","primaryPosition":{"code":"5","name":"Third Base","type":"Infielder","abbreviation":"3B"},"useName":"Miguel"},{"id":808959,"fullName":"Munetaka Murakami","link":"/api/v1/people/808959","firstName":"Munetaka","lastName":"Murakami","primaryPosition":{"code":"3","name":"First Base","type":"Infielder","abbreviation":"1B"},"useName":"Munetaka"},{"id":502054,"fullName":"Tommy Pham","link":"/api/v1/people/502054","firstName":"Thomas","lastName":"Pham","primaryPosition":{"code":"10","name":"Designated Hitter","typeLine truncated
|
||||
@@ -1 +0,0 @@
|
||||
{"copyright": "Copyright 2026 MLB Advanced Media, L.P. Use of any content on this page acknowledges agreement to the terms posted here http://gdx.mlb.com/components/copyright.txt", "totalItems": 2, "totalEvents": 0, "totalGames": 2, "totalGamesInProgress": 1, "dates": [{"date": "2026-10-05", "totalItems": 2, "totalEvents": 0, "totalGames": 2, "totalGamesInProgress": 1, "games": [{"gamePk": 849839, "gameGuid": "8f0516e5-9273-4800-9483-8cf19c530720", "link": "/api/v1.1/game/849839/feed/live", "gameType": "D", "season": "2026", "gameDate": "2026-10-06T00:00:00Z", "officialDate": "2026-10-05", "status": {"abstractGameState": "Live", "codedGameState": "I", "detailedState": "In Progress", "statusCode": "I", "startTimeTBD": false, "abstractGameCode": "L"}, "teams": {"away": {"team": {"id": 147, "name": "New York Yankees", "link": "/api/v1/teams/147"}, "leagueRecord": {"wins": 0, "losses": 1, "ties": 0, "pct": ".000"}, "score": 1, "probablePitcher": {"id": 693645, "fullName": "Cam Schlittler", "link": "/api/v1/people/693645"}, "splitSquad": false, "seriesNumber": 1}, "home": {"team": {"id": 139, "name": "Tampa Bay Rays", "link": "/api/v1/teams/139"}, "leagueRecord": {"wins": 1, "losses": 0, "ties": 0, "pct": "1.000"}, "score": 2, "probablePitcher": {"id": 642547, "fullName": "Freddy Peralta", "link": "/api/v1/people/642547"}, "splitSquad": false, "seriesNumber": 1}}, "venue": {"id": 12, "name": "Tropicana Field", "link": "/api/v1/venues/12"}, "content": {"link": "/api/v1/game/849839/content"}, "gameNumber": 1, "publicFacing": true, "doubleHeader": "N", "gamedayType": "P", "tiebreaker": "N", "calendarEventID": "14-849839-2026-10-05", "seasonDisplay": "2026", "dayNight": "night", "description": "ALDS 'A' Game 2", "scheduledInnings": 9, "reverseHomeAwayStatus": false, "inningBreakLength": 175, "gamesInSeries": 5, "seriesGameNumber": 2, "seriesDescription": "AL Division Series", "recordSource": "S", "ifNecessary": "N", "ifNecessaryDescription": "Normal Game", "lineups": {"homePlayers": [{"id": 650490, "fullName": "Yandy D\u00edaz", "link": "/api/v1/people/650490", "firstName": "Yandy", "lastName": "D\u00edaz", "primaryPosition": {"code": "10", "name": "Designated Hitter", "type": "Hitter", "abbreviation": "DH"}, "useName": "Yandy"}, {"id": 666018, "fullName": "Jonathan Aranda", "link": "/api/v1/people/666018", "firstName": "Jonathan", "lastName": "Aranda", "primaryPosition": {"code": "3", "name": "First Base", "type": "Infielder", "abbreviation": "1B"}, "useName": "Jonathan"}, {"id": 691406, "fullName": "Junior Caminero", "link": "/api/v1/people/691406", "firstName": "Junior", "lastName": "Caminero", "primaryPosition": {"code": "5", "name": "Third Base", "type": "Infielder", "abbreviation": "3B"}, "useName": "Junior"}, {"id": 689414, "fullName": "Liam Hicks", "link": "/api/v1/people/689414", "firstName": "Liam", "lastName": "Hicks", "primaryPosition": {"code": "2", "name": "Catcher", "type": "Catcher", "abbreviation": "C"}, "useName": "Liam"}, {"id": 802415, "fullName": "Chandler Simpson", "link": "/api/v1/people/802415", "firstName": "Chandler", "lastName": "Simpson", "primaryPosition": {"code": "7", "name": "Outfielder", "type": "Outfielder", "abbreviation": "LF"}, "useName": "Chandler"}, {"id": 683748, "fullName": "Victor Mesa Jr.", "link": "/api/v1/people/683748", "firstName": "Victor", "lastName": "Mesa", "primaryPosition": {"code": "9", "name": "Outfielder", "type": "Outfielder", "abbreviation": "RF"}, "useName": "Victor"}, {"id": 676356, "fullName": "Jonny DeLuca", "link": "/api/v1/people/676356", "firstName": "Jonathan", "lastName": "DeLuca", "primaryPosition": {"code": "8", "name": "Outfielder", "type": "Outfielder", "abbreviation": "CF"}, "useName": "Jonny"}, {"id": 680700, "fullName": "Richie Palacios", "link": "/api/v1/people/680700", "firstName": "Richard", "lastName": "Palacios", "primaryPosition": {"code": "4", "name": "Second Base", "type": "Infielder", "abbreviation": "2B"}, "useName": "Richie"}, {"id": 670764, "fullName": "Taylor Walls", "link": "/api/v1/people/670764", "firstName": "Taylor", "lastName": "Walls", "primaryPosition": {"code": "6", "name": "Shortstop", "type": "Infielder", "abbreviation": "SS"}, "useName": "Taylor"}], "awayPlayers": [{"id": 700250, "fullName": "Ben Rice", "link": "/api/v1/people/700250", "firstName": "Benjamin", "lastName": "Rice", "primaryPosition": {"code": "10", "name": "Designated Hitter", "type": "Hitter", "abbreviation": "DH"}, "useName": "Ben"}, {"id": 641355, "fullName": "Cody Bellinger", "link": "/api/v1/people/641355", "firstName": "Cody", "lastName": "Bellinger", "primaryPosition": {"code": "7", "name": "Outfielder", "type": "Outfielder", "abbreviation": "LF"}, "useName": "Cody"}, {"id": 671277, "fullName": "Luis Garc\u00eda Jr.", "link": "/api/v1/people/671277", "firstName": "Luis", "lastName": "Garc\u00eda", "primaryPosition": {"code": "3", "name": "First Base", "type": "Infielder", "abbreviation": "1B"}, "useName": "Luis"}, {"id": 682987, "fullName": "SpeLine truncated
|
||||
@@ -1,122 +0,0 @@
|
||||
// Follow MLB: keeps the scorecard caught up with MLB's play-by-play while watching.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { loadApp, loadMlbGame, readJSON, tick, same } = require('./helpers/app');
|
||||
|
||||
function app(t){
|
||||
const w = loadApp();
|
||||
t.after(() => { w.clearTimeout(w._follow.timer); w.G.mlbFollow = null; w.close(); });
|
||||
return w;
|
||||
}
|
||||
const feedFetches = w => (w.fetchLog || []).filter(u => /\/feed\/live$/.test(u)).length;
|
||||
|
||||
test('catches the game up, then downloads the play-by-play again only when MLB has an update', async (t) => {
|
||||
const w = app(t);
|
||||
await loadMlbGame(w, 849839, '2026-10-05');
|
||||
w.mlbStamps = ['20261005_234153'];
|
||||
await w.startFollow();
|
||||
assert.ok(w.G.pas.length > 30, 'plays added');
|
||||
assert.equal(w.G.mlbFollow.device, w.followDevice(), 'this device is following');
|
||||
assert.equal(w.document.getElementById('followPill').textContent, '📡 Following MLB');
|
||||
assert.equal(feedFetches(w), 1);
|
||||
|
||||
await w.followTick();
|
||||
assert.equal(feedFetches(w), 1, 'no new update at MLB: nothing downloaded');
|
||||
w.mlbStamps = ['20261005_234153', '20261005_234210'];
|
||||
await w.followTick();
|
||||
assert.equal(feedFetches(w), 2, 'MLB updated: downloaded again');
|
||||
assert.ok(w._follow.timer, 'next check scheduled');
|
||||
});
|
||||
|
||||
test('moves the count of the at-bat in progress forward, never back', async (t) => {
|
||||
const w = app(t);
|
||||
await loadMlbGame(w, 849839, '2026-10-05');
|
||||
await w.startFollow();
|
||||
const feed = readJSON('feed-849839.json');
|
||||
const last = feed.liveData.plays.allPlays.at(-1);
|
||||
last.playEvents = [{ isPitch: true, details: { description: 'Ball' } }, { isPitch: true, details: { description: 'Called Strike' } }, { isPitch: true, details: { description: 'Ball' } }];
|
||||
last.count = { balls: 2, strikes: 1, outs: last.count.outs };
|
||||
w.followApply(feed);
|
||||
assert.deepEqual([w.G.balls, w.G.strikes], [2, 1], 'MLB ahead: count follows');
|
||||
w.G.balls = 3; w.G.strikes = 2; // the scorer is ahead of MLB's feed
|
||||
w.followApply(feed);
|
||||
assert.deepEqual([w.G.balls, w.G.strikes], [3, 2], 'scorer ahead: left alone');
|
||||
});
|
||||
|
||||
test('waits while a dialog is open, and an Undo stops following so it sticks', async (t) => {
|
||||
const w = app(t);
|
||||
await loadMlbGame(w, 849839, '2026-10-05');
|
||||
const dlg = w.document.createElement('div'); dlg.className = 'rp-overlay'; w.document.body.appendChild(dlg);
|
||||
await w.startFollow();
|
||||
assert.equal(w.G.pas.length, 0, 'nothing changed while the dialog is open');
|
||||
dlg.remove();
|
||||
await w.followTick();
|
||||
assert.ok(w.G.pas.length > 30, 'caught up once it closed');
|
||||
|
||||
w.undoAction();
|
||||
assert.equal(w.G.mlbFollow, null, 'stopped following');
|
||||
assert.equal(w.G.pas.length, 0, 'the catch-up was undone');
|
||||
assert.equal(w.document.getElementById('followPill').hidden, true);
|
||||
});
|
||||
|
||||
test('a finished game: catches up, marks it final and stops following', async (t) => {
|
||||
const w = app(t);
|
||||
await loadMlbGame(w, 849830);
|
||||
await w.startFollow();
|
||||
assert.ok(w.G.log.some(l => l.tag === 'Final'), 'final');
|
||||
assert.equal(w.G.mlbFollow, null, 'stopped');
|
||||
});
|
||||
|
||||
test('another device following: this one only shows it, and doesn\'t poll', async (t) => {
|
||||
const w = app(t);
|
||||
await loadMlbGame(w, 849839, '2026-10-05');
|
||||
w.G.mlbFollow = { device: 'Some other iPad', since: 1 };
|
||||
w.renderFollowPill();
|
||||
await w.followTick();
|
||||
assert.equal(feedFetches(w), 0, 'no downloads');
|
||||
assert.equal(w.document.getElementById('followPill').textContent, '📡 Following on Some other iPad');
|
||||
});
|
||||
|
||||
// Regression: at an inning boundary MLB's live feed can briefly leave the
|
||||
// previous half's runner on the new half's in-progress at-bat matchup. The
|
||||
// scorecard must never show a fielding-team player on base (once seen as a
|
||||
// Rays runner standing on base during a Guardians at-bat).
|
||||
test('a runner stranded on the in-progress matchup from the half just ended never shows on base', async (t) => {
|
||||
const w = app(t);
|
||||
await loadMlbGame(w, 849839, '2026-10-05'); // Yankees @ Rays
|
||||
const feed = readJSON('feed-849839.json');
|
||||
const plays = feed.liveData.plays.allPlays;
|
||||
const clone = o => JSON.parse(JSON.stringify(o));
|
||||
|
||||
// First top → bottom flip: home (Rays) start batting, away (Yankees) now field
|
||||
let flip = -1;
|
||||
for(let i = 1; i < plays.length; i++){
|
||||
if(plays[i - 1].about.halfInning === 'top' && plays[i].about.halfInning === 'bottom'){ flip = i; break; }
|
||||
}
|
||||
assert.ok(flip > 0, 'fixture has a top→bottom flip');
|
||||
|
||||
const awayP = Object.values(feed.liveData.boxscore.teams.away.players)[0].person; // a Yankee (fielding)
|
||||
const homeP = Object.values(feed.liveData.boxscore.teams.home.players).find(p => p.position && /[1-9]/.test(p.position.code || ''))?.person
|
||||
|| Object.values(feed.liveData.boxscore.teams.home.players)[0].person; // a Ray (batting)
|
||||
|
||||
function snapshot(injectLeftover){
|
||||
const f = clone(feed);
|
||||
const p = f.liveData.plays.allPlays.slice(0, flip + 1);
|
||||
const cur = p[flip];
|
||||
cur.about.isComplete = false; // bottom-half at-bat in progress
|
||||
cur.result = { eventType: undefined };
|
||||
cur.matchup.postOnFirst = injectLeftover ? { id: awayP.id, fullName: awayP.fullName } : null;
|
||||
cur.matchup.postOnSecond = injectLeftover ? { id: homeP.id, fullName: homeP.fullName } : null;
|
||||
cur.matchup.postOnThird = null;
|
||||
f.liveData.plays.allPlays = p;
|
||||
return f;
|
||||
}
|
||||
|
||||
w.mlbApplyCatchUp(snapshot(false)); // bottom half begins, bases empty
|
||||
assert.equal(w.G.half, 'bot', 'home team batting');
|
||||
same(w.G.bases, [null, null, null], 'no one on to start the half');
|
||||
|
||||
w.mlbApplyCatchUp(snapshot(true)); // MLB leaves the previous half's runner on the matchup
|
||||
assert.ok(!w.G.bases.includes(awayP.fullName), 'the fielding-team runner is dropped, not shown on base');
|
||||
assert.equal(w.G.bases[1], homeP.fullName, 'a genuine batting-team runner is still kept');
|
||||
});
|
||||
@@ -1,66 +0,0 @@
|
||||
// Loads the real app (index.html + js/*.js, in index.html's order) into jsdom.
|
||||
// MLB requests are answered from tests/fixtures, so tests run offline and give
|
||||
// the same result every time.
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { JSDOM } = require('jsdom');
|
||||
|
||||
const ROOT = path.join(__dirname, '..', '..');
|
||||
const FIXTURES = path.join(__dirname, '..', 'fixtures');
|
||||
|
||||
function readJSON(file){ return JSON.parse(fs.readFileSync(path.join(FIXTURES, file), 'utf8')); }
|
||||
|
||||
// Answers the app's fetch() calls: schedule and live feeds from fixtures,
|
||||
// anything else (rosters, venues) with an empty but valid response. A game's
|
||||
// update-times list is w.mlbStamps (set by a test); every URL is logged in w.fetchLog.
|
||||
function fakeFetch(url, w){
|
||||
let body = {};
|
||||
if(w) (w.fetchLog = w.fetchLog || []).push(url);
|
||||
const feed = /\/game\/(\d+)\/feed\/live/.exec(url);
|
||||
if(/\/feed\/live\/timestamps/.test(url)) body = (w && w.mlbStamps) || ['20261005_000000'];
|
||||
else if(feed) body = readJSON('feed-' + feed[1] + '.json');
|
||||
else if(/\/schedule\?/.test(url) && /date=2026-10-03/.test(url)) body = readJSON('schedule-2026-10-03.json');
|
||||
else if(/\/roster/.test(url)) body = { roster: [] };
|
||||
return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve(JSON.parse(JSON.stringify(body))) });
|
||||
}
|
||||
|
||||
// url: each simulated device gets its own origin, so its own localStorage
|
||||
function loadApp(url){
|
||||
const html = fs.readFileSync(path.join(ROOT, 'index.html'), 'utf8');
|
||||
const scripts = [...html.matchAll(/<script src="([^"]+)"><\/script>/g)].map(m => m[1]);
|
||||
const dom = new JSDOM(html.replace(/<script src="[^"]+"><\/script>/g, '').replace(/<link rel="stylesheet"[^>]*>/, ''), {
|
||||
url: url || 'https://scorecard.test/',
|
||||
runScripts: 'outside-only',
|
||||
pretendToBeVisual: true
|
||||
});
|
||||
const w = dom.window;
|
||||
w.fetch = url => fakeFetch(url, w);
|
||||
w.matchMedia = () => ({ matches: false, addEventListener(){}, removeEventListener(){} });
|
||||
w.scrollTo = () => {};
|
||||
w.HTMLElement.prototype.scrollIntoView = function(){};
|
||||
scripts.forEach(src => w.eval(fs.readFileSync(path.join(ROOT, src), 'utf8')));
|
||||
w.showConfirm = () => Promise.resolve(true); // accept confirmation dialogs
|
||||
w.kbFlash = () => {}; // no toasts
|
||||
return w;
|
||||
}
|
||||
|
||||
const tick = (ms = 0) => new Promise(r => setTimeout(r, ms));
|
||||
|
||||
// Values from the jsdom window are from another JS realm (their arrays aren't
|
||||
// Node's arrays), so compare plain copies.
|
||||
const assert = require('node:assert/strict');
|
||||
function same(actual, expected, msg){ assert.deepEqual(JSON.parse(JSON.stringify(actual)), expected, msg); }
|
||||
|
||||
// A fresh game loaded the way Today's Games does it, plus its MLB feed
|
||||
async function loadMlbGame(w, gamePk, date){
|
||||
const sched = readJSON('schedule-' + (date || '2026-10-03') + '.json');
|
||||
const game = sched.dates[0].games.find(g => g.gamePk === gamePk);
|
||||
w._doLoadTodaysGame(game);
|
||||
const feed = readJSON('feed-' + gamePk + '.json');
|
||||
w._mlb = { feed, fetchedAt: Date.now() };
|
||||
return feed;
|
||||
}
|
||||
|
||||
const GAMES = readJSON('schedule-2026-10-03.json').dates[0].games.map(g => g.gamePk);
|
||||
|
||||
module.exports = { loadApp, loadMlbGame, tick, readJSON, GAMES, same };
|
||||
@@ -1,97 +0,0 @@
|
||||
// A small in-memory stand-in for Firebase (auth + Firestore) shared by several
|
||||
// simulated devices. It enforces the same rule as firestore.rules (an update must
|
||||
// be newer than what's stored) and can take one device offline, queueing its writes.
|
||||
|
||||
const clone = v => JSON.parse(JSON.stringify(v));
|
||||
|
||||
function createBackend(){
|
||||
return { docs: new Map(), listeners: [], users: { 'fan@example.test': 'correct-horse' } };
|
||||
}
|
||||
|
||||
function fakeFirebase(backend){
|
||||
const client = { offline: false, queue: [], user: null, authCbs: [] };
|
||||
|
||||
function deliver(key, data, existed, writer){
|
||||
const col = key.slice(0, key.lastIndexOf('/')), id = key.slice(key.lastIndexOf('/') + 1);
|
||||
backend.listeners.forEach(l => {
|
||||
if(l.col !== col || l.client.offline) return;
|
||||
// Like Firestore, a device sees its own write first as a pending local change
|
||||
const change = { type: existed ? 'modified' : 'added', doc: { id, data: () => clone(data), metadata: { hasPendingWrites: l.client === writer } } };
|
||||
setTimeout(() => l.cb({ docChanges: () => [change] }), 0);
|
||||
});
|
||||
}
|
||||
|
||||
function commit(key, data){
|
||||
const existing = backend.docs.get(key);
|
||||
if(existing && !(data.updatedAt > existing.updatedAt)){
|
||||
const err = new Error('Missing or insufficient permissions.'); err.code = 'permission-denied';
|
||||
return Promise.reject(err);
|
||||
}
|
||||
backend.docs.set(key, clone(data));
|
||||
deliver(key, data, !!existing, client);
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
function docRef(path){
|
||||
return {
|
||||
collection: name => colRef(path + '/' + name),
|
||||
set(data){
|
||||
if(client.offline) return new Promise((resolve, reject) => client.queue.push({ path, data: clone(data), resolve, reject }));
|
||||
return commit(path, data);
|
||||
},
|
||||
get(){
|
||||
const d = backend.docs.get(path);
|
||||
return Promise.resolve({ exists: !!d, data: () => clone(d) });
|
||||
}
|
||||
};
|
||||
}
|
||||
function colRef(path){
|
||||
return {
|
||||
doc: id => docRef(path + '/' + id),
|
||||
onSnapshot(cb){
|
||||
const l = { col: path, cb, client };
|
||||
backend.listeners.push(l);
|
||||
const changes = [...backend.docs.entries()].filter(([k]) => k.startsWith(path + '/')).map(([k, d]) =>
|
||||
({ type: 'added', doc: { id: k.slice(path.length + 1), data: () => clone(d), metadata: { hasPendingWrites: false } } }));
|
||||
setTimeout(() => cb({ docChanges: () => changes }), 0);
|
||||
return () => { backend.listeners = backend.listeners.filter(x => x !== l); };
|
||||
}
|
||||
};
|
||||
}
|
||||
const db = { collection: name => colRef(name), enablePersistence: () => Promise.resolve() };
|
||||
|
||||
const auth = {
|
||||
onAuthStateChanged(cb){ client.authCbs.push(cb); setTimeout(() => cb(client.user), 0); },
|
||||
signInWithEmailAndPassword(email, pw){
|
||||
if(backend.users[email] !== pw){ const e = new Error('bad'); e.code = 'auth/invalid-credential'; return Promise.reject(e); }
|
||||
client.user = { uid: 'uid-1', email };
|
||||
client.authCbs.forEach(cb => cb(client.user));
|
||||
return Promise.resolve({ user: client.user });
|
||||
},
|
||||
signOut(){ client.user = null; client.authCbs.forEach(cb => cb(null)); return Promise.resolve(); }
|
||||
};
|
||||
|
||||
const firebase = {
|
||||
apps: [],
|
||||
initializeApp(){ this.apps.push({}); },
|
||||
auth: () => auth,
|
||||
firestore: () => db
|
||||
};
|
||||
|
||||
// Test controls
|
||||
firebase._goOffline = () => { client.offline = true; };
|
||||
firebase._goOnline = async () => {
|
||||
client.offline = false;
|
||||
const q = client.queue.splice(0);
|
||||
for(const w of q) await commit(w.path, w.data).then(w.resolve, w.reject);
|
||||
// Catch up on everything changed while offline
|
||||
backend.listeners.filter(l => l.client === client).forEach(l => {
|
||||
const changes = [...backend.docs.entries()].filter(([k]) => k.startsWith(l.col + '/')).map(([k, d]) =>
|
||||
({ type: 'modified', doc: { id: k.slice(l.col.length + 1), data: () => clone(d), metadata: { hasPendingWrites: false } } }));
|
||||
setTimeout(() => l.cb({ docChanges: () => changes }), 0);
|
||||
});
|
||||
};
|
||||
return firebase;
|
||||
}
|
||||
|
||||
module.exports = { createBackend, fakeFirebase };
|
||||
@@ -1,74 +0,0 @@
|
||||
// The team pickers live in the box score's team cells and survive its redraws.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { loadApp } = require('./helpers/app');
|
||||
|
||||
test('team pickers sit in the box score, keep their team through redraws, and change the game', (t) => {
|
||||
const w = loadApp();
|
||||
t.after(() => w.close());
|
||||
const away = w.document.getElementById('teamAway');
|
||||
assert.ok(w.document.querySelector('#scoreTable #row-away #teamAway'), 'away picker in the away row');
|
||||
assert.ok(w.document.querySelector('#scoreTable #row-home #teamHome'), 'home picker in the home row');
|
||||
|
||||
away.value = 'New York Yankees';
|
||||
assert.equal(away.getAttribute('onchange'), 'onTeamChange()');
|
||||
w.onTeamChange(); // jsdom here doesn't run inline handlers
|
||||
assert.equal(w.team('away'), 'New York Yankees');
|
||||
assert.match(w.document.querySelector('#row-away img').getAttribute('src'), /147\.svg$/, 'box score shows the logo');
|
||||
w.recordHit(1); w.renderScore(); w.renderAll();
|
||||
const again = w.document.getElementById('teamAway');
|
||||
assert.equal(again, away, 'the same picker element, moved back in');
|
||||
assert.equal(again.value, 'New York Yankees', 'keeps its team');
|
||||
assert.ok(w.document.querySelector('#scoreTable #row-away #teamAway'), 'still in the box score');
|
||||
assert.equal(w.document.querySelectorAll('#teamAway').length, 1, 'only one');
|
||||
});
|
||||
|
||||
test('dark mode shows the dark-background team logos, including ones drawn later; printing switches back', async (t) => {
|
||||
const w = loadApp();
|
||||
t.after(() => w.close());
|
||||
const away = w.document.getElementById('teamAway');
|
||||
away.value = 'New York Yankees'; w.onTeamChange();
|
||||
const logo = () => w.document.querySelector('#row-away img').getAttribute('src');
|
||||
assert.equal(logo(), 'https://www.mlbstatic.com/team-logos/147.svg', 'light mode: regular logo');
|
||||
|
||||
w.matchMedia = () => ({ matches: true, addEventListener(){}, removeEventListener(){} }); // switch to dark
|
||||
w.fixLogosIn(w.document.body);
|
||||
assert.equal(logo(), 'https://www.mlbstatic.com/team-logos/team-cap-on-dark/147.svg');
|
||||
w.renderScore(); // redrawn: the new image follows along
|
||||
await new Promise(r => setTimeout(r, 0));
|
||||
assert.equal(logo(), 'https://www.mlbstatic.com/team-logos/team-cap-on-dark/147.svg', 'after a redraw');
|
||||
|
||||
w.dispatchEvent(new w.Event('beforeprint'));
|
||||
assert.equal(logo(), 'https://www.mlbstatic.com/team-logos/147.svg', 'printing: regular logo for white paper');
|
||||
w.dispatchEvent(new w.Event('afterprint'));
|
||||
assert.equal(logo(), 'https://www.mlbstatic.com/team-logos/team-cap-on-dark/147.svg', 'back after printing');
|
||||
w.document.querySelectorAll('img[src*="league-on-light"]').forEach(i => assert.ok(!/cap-on-dark/.test(i.src)));
|
||||
});
|
||||
|
||||
test('Bases card: Full field draws the home park\'s wall and signs; the choice is remembered; no home team, no toggle', (t) => {
|
||||
const w = loadApp();
|
||||
t.after(() => w.close());
|
||||
const toggle = () => w.document.getElementById('fieldToggle');
|
||||
assert.equal(toggle().children.length, 0, 'no home team: infield only, no toggle');
|
||||
|
||||
const home = w.document.getElementById('teamHome');
|
||||
home.value = 'Boston Red Sox'; w.onTeamChange();
|
||||
assert.equal(toggle().children.length, 2, 'toggle shown once there is a home park');
|
||||
w.setFieldView('full');
|
||||
const svg = w.document.querySelector('#infield svg');
|
||||
assert.equal(svg.getAttribute('aria-label'), 'Field');
|
||||
const signs = [...svg.querySelectorAll('text')].map(x => x.textContent);
|
||||
for(const n of ['310', '420', '302']) assert.ok(signs.includes(n), 'Fenway sign ' + n);
|
||||
assert.equal(w.localStorage.getItem('baseball_scorecard_field_view'), 'full', 'remembered');
|
||||
|
||||
w.toggleBase(2); // runners still work at this scale
|
||||
assert.ok(w.G.bases[1], 'runner on second');
|
||||
assert.equal(w.document.querySelectorAll('#infield .if-base').length, 3);
|
||||
|
||||
w.setFieldView('infield');
|
||||
assert.equal(w.document.querySelector('#infield svg').getAttribute('aria-label'), 'Infield');
|
||||
for(const name of Object.keys(w.FIELD_WALLS)){
|
||||
const f = w.FIELD_WALLS[name];
|
||||
assert.ok(f.w.length >= 3 && f.w[0][0] < 0 && f.w.at(-1)[0] > 0, name + ': wall runs left pole to right pole');
|
||||
}
|
||||
});
|
||||
@@ -1,182 +0,0 @@
|
||||
// Real games: catch each ALDS Game 1 (Oct 3, 2026) up from an empty scorecard and
|
||||
// compare the result with MLB's official play-by-play and box score.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { loadApp, loadMlbGame, tick, GAMES, same } = require('./helpers/app');
|
||||
|
||||
// MLB's "Team RISP" / "Team LOB" lines from the box score
|
||||
function mlbTeamInfo(feed, side){
|
||||
const out = {};
|
||||
(feed.liveData.boxscore.teams[side].info || []).forEach(b => (b.fieldList || []).forEach(f => {
|
||||
if(f.label === 'Team RISP') out.risp = f.value.replace(/\.$/, '');
|
||||
if(f.label === 'Team LOB') out.lob = Number(f.value.replace(/\.$/, ''));
|
||||
}));
|
||||
return out;
|
||||
}
|
||||
|
||||
for(const gamePk of GAMES){
|
||||
test('game ' + gamePk + ': catch-up from an empty scorecard matches MLB', async (t) => {
|
||||
const w = loadApp();
|
||||
t.after(() => w.close());
|
||||
const feed = await loadMlbGame(w, gamePk);
|
||||
const label = w.team('away') + ' @ ' + w.team('home');
|
||||
|
||||
assert.equal(w.G.pas.length, 0, 'starts empty');
|
||||
w.mlbCatchUp();
|
||||
await tick();
|
||||
|
||||
await t.test('every plate appearance, pitching line and inning matches (Check vs MLB finds 0 differences)', () => {
|
||||
const d = w.mlbDiffs(feed);
|
||||
assert.equal(d.behind, 0, label + ': nothing left to catch up');
|
||||
same(d.plays.map(x => x.type + ' ' + x.half + x.inn), [], label + ': play differences');
|
||||
same(d.pitchers.map(x => x.mlb.name), [], label + ': pitcher differences');
|
||||
same(d.runs.map(x => x.side + ' ' + x.inn), [], label + ': run differences');
|
||||
same(d.errors.map(x => x.side + ' ' + x.app + '/' + x.mlb), [], label + ': error differences');
|
||||
assert.ok(w.G.log.some(l => l.tag === 'Final'), label + ': marked FINAL');
|
||||
});
|
||||
|
||||
await t.test('team RISP and left on base equal MLB\'s box score', () => {
|
||||
for(const side of ['away', 'home']){
|
||||
const mlb = mlbTeamInfo(feed, side), r = w.rispLine(side);
|
||||
assert.equal(r.h + '-for-' + r.ab, mlb.risp, label + ' ' + side + ' RISP');
|
||||
assert.equal(w.teamLOB(side), mlb.lob, label + ' ' + side + ' LOB');
|
||||
}
|
||||
});
|
||||
|
||||
await t.test('score matches MLB', () => {
|
||||
const ls = feed.liveData.linescore.teams;
|
||||
same([w.G.rhe.away[0], w.G.rhe.home[0]], [ls.away.runs, ls.home.runs]);
|
||||
same([w.G.rhe.away[1], w.G.rhe.home[1]], [ls.away.hits, ls.home.hits]);
|
||||
});
|
||||
|
||||
await t.test('every batter and pitcher line equals MLB\'s box score (season stats over this game)', () => {
|
||||
w._ss.team = 'all'; w._ss.attended = 'all'; w._ss.type = 'all';
|
||||
const games = w.ssGames();
|
||||
const bat = w.ssBatting(games), pit = w.ssPitching(games);
|
||||
for(const side of ['away', 'home']){
|
||||
const tm = side === 'away' ? w.team('away') : w.team('home');
|
||||
for(const p of Object.values(feed.liveData.boxscore.teams[side].players)){
|
||||
const name = p.person.fullName, key = w.mlbNormName(name);
|
||||
const b = p.stats.batting, q = p.stats.pitching;
|
||||
if(b && b.plateAppearances){
|
||||
const a = bat.find(r => r.team === tm && w.mlbNormName(r.name) === key);
|
||||
assert.ok(a, name + ' is in the batting stats');
|
||||
same([a.ab, a.h, a.r, a.hr, a.rbi, a.bb, a.k, a.sb], [b.atBats, b.hits, b.runs, b.homeRuns, b.rbi, b.baseOnBalls, b.strikeOuts, b.stolenBases], name + ' AB H R HR RBI BB K SB');
|
||||
}
|
||||
if(q && q.numberOfPitches){
|
||||
const a = pit.find(r => r.team === tm && w.mlbNormName(r.name) === key);
|
||||
assert.ok(a, name + ' is in the pitching stats');
|
||||
same([w.fmtIP(a.outs), a.h, a.r, a.er, a.bb, a.k, a.pitches], [q.inningsPitched, q.hits, q.runs, q.earnedRuns, q.baseOnBalls, q.strikeOuts, q.numberOfPitches], name + ' IP H R ER BB K P');
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
test('catch-up continues from a hand-scored start and ends mid at-bat on MLB\'s batter and count', async (t) => {
|
||||
const w = loadApp();
|
||||
t.after(() => w.close());
|
||||
const full = await loadMlbGame(w, 849835); // Yankees @ Rays
|
||||
|
||||
// Hand-score the first 14 plate appearances with the scoring buttons
|
||||
const m = w.mlbPlays(full);
|
||||
const seq = Object.keys(m.halves).map(Number).sort((a, b) => a - b).flatMap(o => m.halves[o]);
|
||||
for(const e of seq.slice(0, 14)){
|
||||
if(e.side === 'away') w.G.awayBatter = e.slot; else w.G.homeBatter = e.slot;
|
||||
const r = e.res, fd = (r.match(/\d/g) || []).map(Number);
|
||||
if(/^(1B|2B|3B|HR)/.test(r)){ w.recordHit({ '1B':1, '2B':2, '3B':3, 'HR':4 }[r.slice(0, 2)]); if(w.document.getElementById('rpOverlay')) w.rpAutoAdvance(); }
|
||||
else if(r === 'K') w.recordKO('swinging');
|
||||
else if(r === 'ꓘ') w.recordKO('looking');
|
||||
else if(r === 'BB'){ w.G.balls = 3; w.addBall(); }
|
||||
else if(/^F\d/.test(r)){ w.outState.type = 'fly'; w.outState.fielder = fd[0]; w.recordOut(); }
|
||||
else if(/^G\d/.test(r)){ w.outState.type = 'ground'; w.outState.fielder = fd[0]; w.outState.throwTo = fd.slice(1); w.recordOut(); }
|
||||
}
|
||||
assert.equal(w.G.pas.length, 14);
|
||||
|
||||
// MLB "live": the feed cut off three pitches into play 41
|
||||
const cut = JSON.parse(JSON.stringify(full));
|
||||
const plays = cut.liveData.plays.allPlays.slice(0, 41), live = plays[40], prev = plays[39];
|
||||
live.about.isComplete = false; live.result = { type: 'atBat' };
|
||||
live.count = { balls: 2, strikes: 1, outs: prev.about.halfInning === live.about.halfInning ? prev.count.outs : 0 };
|
||||
delete live.matchup.postOnFirst; delete live.matchup.postOnSecond; delete live.matchup.postOnThird;
|
||||
live.runners = [];
|
||||
cut.liveData.plays.allPlays = plays;
|
||||
cut.gameData.status = { abstractGameState: 'Live', detailedState: 'In Progress' };
|
||||
w._mlb = { feed: cut, fetchedAt: Date.now() };
|
||||
|
||||
const adds = w.mlbCatchUpCount(cut);
|
||||
w.mlbCatchUp();
|
||||
await tick();
|
||||
|
||||
assert.equal(w.G.pas.length, 14 + adds, 'adds only what was missing');
|
||||
const side = w.batting();
|
||||
assert.equal(w.curName(side, w.abIdx(side)), live.matchup.batter.fullName, 'current batter');
|
||||
const fSide = side === 'away' ? 'home' : 'away';
|
||||
assert.equal(w.G.pitchers[fSide][w.activePIdx(fSide)].name, live.matchup.pitcher.fullName, 'current pitcher');
|
||||
same([w.G.balls, w.G.strikes], [2, 1], 'count');
|
||||
assert.equal(w.G.inning, live.about.inning, 'inning');
|
||||
assert.ok(!w.G.log.some(l => l.tag === 'Final'), 'not final');
|
||||
|
||||
w.undoAction();
|
||||
assert.equal(w.G.pas.length, 14, 'one Undo reverses the whole catch-up');
|
||||
});
|
||||
|
||||
// ALDS Game 2, Oct 5 2026 (saved mid-game): the bottom of the 1st has all three kinds
|
||||
// of Yankees error — McMahon's fielding error on the batter (E5), Chisholm's throwing
|
||||
// error on a runner during a force out, and Wells's catcher's interference.
|
||||
test('Catch up counts every error MLB charges: on the batter, on a runner, and catcher\'s interference', async (t) => {
|
||||
const w = loadApp();
|
||||
t.after(() => w.close());
|
||||
const feed = await loadMlbGame(w, 849839, '2026-10-05');
|
||||
w.mlbCatchUp();
|
||||
await tick();
|
||||
const ls = feed.liveData.linescore.teams;
|
||||
same([w.G.rhe.away[2], w.G.rhe.home[2]], [ls.away.errors, ls.home.errors], 'errors match MLB');
|
||||
assert.equal(ls.away.errors, 3, 'the fixture has the three Yankees errors');
|
||||
const b1 = w.G.pas.filter(p => p.inn === 1 && p.half === 'bot').map(p => p.res);
|
||||
same(b1, ['E5', '1B', 'FC6-4', 'CI', 'FC4-6', 'G4-3'], 'bottom of the 1st');
|
||||
same(w.mlbDiffs(feed).errors, [], 'Check vs MLB: no error differences');
|
||||
});
|
||||
|
||||
test('Check vs MLB offers MLB\'s error total when the scorecard\'s is off, and Use MLB\'s fixes it', async (t) => {
|
||||
const w = loadApp();
|
||||
t.after(() => w.close());
|
||||
const feed = await loadMlbGame(w, 849839, '2026-10-05');
|
||||
w.mlbCatchUp();
|
||||
await tick();
|
||||
w.G.rhe.away[2] = 1; // as in a game caught up before this fix
|
||||
const d = w.mlbDiffs(feed).errors;
|
||||
same(d.map(x => [x.side, x.app, x.mlb]), [['away', 1, 3]]);
|
||||
w.mlbApply(d[0]);
|
||||
assert.equal(w.G.rhe.away[2], 3);
|
||||
});
|
||||
|
||||
// Mid at-bat: MLB has pitches the scorecard doesn't. Check vs MLB offers the count, and
|
||||
// taking MLB's pitching line for the pitcher on the mound brings the count along.
|
||||
test('Check vs MLB syncs the count of the at-bat in progress', async (t) => {
|
||||
const w = loadApp();
|
||||
t.after(() => w.close());
|
||||
const feed = await loadMlbGame(w, 849839, '2026-10-05');
|
||||
w.mlbCatchUp();
|
||||
await tick();
|
||||
const last = feed.liveData.plays.allPlays.at(-1); // Simpson batting, saved at 0-0
|
||||
const pitch = desc => ({ isPitch: true, details: { description: desc } });
|
||||
last.playEvents = [pitch('Ball'), pitch('Ball'), pitch('Foul')];
|
||||
last.count = { balls: 2, strikes: 1, outs: last.count.outs };
|
||||
assert.equal(w.curName('home', w.abIdx('home')), 'Chandler Simpson', 'scorecard is on the same batter');
|
||||
|
||||
const d = w.mlbDiffs(feed).count;
|
||||
same(d.map(x => [x.mlb.balls, x.mlb.strikes, x.mlb.n, x.mlb.fouls]), [[2, 1, 3, 1]], 'count row offered');
|
||||
w.mlbApply(d[0]);
|
||||
same([w.G.balls, w.G.strikes, w.G.fouls], [2, 1, 1], 'count set');
|
||||
same(w.mlbDiffs(feed).count, [], 'nothing left to fix');
|
||||
|
||||
// Same at-bat, fixed from the pitcher's row instead
|
||||
w.G.balls = 0; w.G.strikes = 0; w.G.fouls = 0;
|
||||
const p = w.G.pitchers.away.find(x => x.name === 'Cam Schlittler');
|
||||
p.pitches -= 3;
|
||||
const pd = w.mlbDiffs(feed).pitchers.find(x => x.mlb.name === 'Cam Schlittler');
|
||||
w.mlbApply(pd);
|
||||
same([w.G.balls, w.G.strikes], [2, 1], 'pitching line fix brings the count along');
|
||||
});
|
||||
@@ -1,64 +0,0 @@
|
||||
// Postseason badge: the bundled official logo for the right round and year,
|
||||
// the league logo everywhere else.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { loadApp } = require('./helpers/app');
|
||||
|
||||
function badgeFor(w, gameType, date, seriesGame){
|
||||
Object.assign(w.G.notes, { gameType, date, seriesGame: seriesGame || '' });
|
||||
return w.postseasonBadge();
|
||||
}
|
||||
|
||||
test('2026 ALDS games show the official ALDS logo and the game number', (t) => {
|
||||
const w = loadApp();
|
||||
t.after(() => w.close());
|
||||
const html = badgeFor(w, 'alds', '2026-10-04', '2');
|
||||
assert.match(html, /assets\/postseason\/alds-2026\.png/);
|
||||
assert.match(html, /alt="2026 ALDS"/);
|
||||
assert.match(html, /Game 2/);
|
||||
});
|
||||
|
||||
test('2026 NLDS games show the official NLDS logo', (t) => {
|
||||
const w = loadApp();
|
||||
t.after(() => w.close());
|
||||
const html = badgeFor(w, 'nlds', '2026-10-04', '2');
|
||||
assert.match(html, /assets\/postseason\/nlds-2026\.png/);
|
||||
assert.match(html, /alt="2026 NLDS"/);
|
||||
assert.match(html, /Game 2/);
|
||||
});
|
||||
|
||||
test('2026 ALCS, NLCS and World Series games show their official logos', (t) => {
|
||||
const w = loadApp();
|
||||
t.after(() => w.close());
|
||||
for(const [type, file, label] of [['alcs', 'alcs', 'ALCS'], ['nlcs', 'nlcs', 'NLCS'], ['ws', 'ws', 'World Series']]){
|
||||
const html = badgeFor(w, type, '2026-10-20', '3');
|
||||
assert.match(html, new RegExp('assets/postseason/' + file + '-2026\\.png'), label);
|
||||
assert.match(html, new RegExp('alt="2026 ' + label + '"'), label);
|
||||
assert.match(html, /Game 3/, label);
|
||||
}
|
||||
});
|
||||
|
||||
test('other years and rounds keep the league-logo badge', (t) => {
|
||||
const w = loadApp();
|
||||
t.after(() => w.close());
|
||||
assert.match(badgeFor(w, 'alds', '2025-10-04'), /team-logos\/league-on-light\/103\.svg/, '2025 ALDS');
|
||||
assert.match(badgeFor(w, 'nlds', '2025-10-04'), /team-logos\/league-on-light\/104\.svg/, '2025 NLDS');
|
||||
assert.match(badgeFor(w, 'alcs', '2025-10-12'), /team-logos\/league-on-light\/103\.svg/, '2025 ALCS');
|
||||
assert.match(badgeFor(w, 'wild', '2026-09-30'), /team-logos\/league-on-light\/1\.svg/, '2026 Wild Card (no official logo)');
|
||||
assert.equal(badgeFor(w, 'regular', '2026-07-04'), '', 'regular season: no badge');
|
||||
});
|
||||
|
||||
test('every bundled postseason logo exists and is cached for offline use', (t) => {
|
||||
const w = loadApp();
|
||||
t.after(() => w.close());
|
||||
const root = path.join(__dirname, '..');
|
||||
const sw = fs.readFileSync(path.join(root, 'sw.js'), 'utf8');
|
||||
for(const round of Object.values(w.POSTSEASON)){
|
||||
for(const file of Object.values(round.official || {})){
|
||||
assert.ok(fs.existsSync(path.join(root, file)), file + ' exists');
|
||||
assert.ok(sw.includes("'./" + file + "'"), file + ' is in the service worker cache list');
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -1,267 +0,0 @@
|
||||
// Hand-scoring rules, driven through the same functions the buttons call.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { loadApp, same } = require('./helpers/app');
|
||||
|
||||
// A fresh app with an empty game; closed after the test
|
||||
function fresh(t){
|
||||
const w = loadApp();
|
||||
t.after(() => w.close());
|
||||
return w;
|
||||
}
|
||||
const pa = (w, i) => w.G.pas[i < 0 ? w.G.pas.length + i : i];
|
||||
|
||||
test('strike three from the Strike button is a strikeout for batter and pitcher', (t) => {
|
||||
const w = fresh(t);
|
||||
w.addStrike(); w.addStrike(); w.addStrike();
|
||||
assert.equal(pa(w, -1).res, 'K');
|
||||
assert.equal(w.G.lineup.away[0].hits.ks, 1);
|
||||
assert.equal(w.G.pitchers.home[0].k, 1);
|
||||
assert.equal(w.G.outs, 1);
|
||||
});
|
||||
|
||||
test('ABS: a ball overturned to strike three is a called strikeout', (t) => {
|
||||
const w = fresh(t);
|
||||
w.addStrike(); w.addStrike(); w.addBall();
|
||||
Object.assign(w.absState, { open: true, side: 'home', callType: 'ball', result: 'overturned' });
|
||||
w.absConfirm();
|
||||
assert.equal(pa(w, -1).res, 'ꓘ');
|
||||
assert.equal(w.G.outs, 1);
|
||||
same([w.G.pitchers.home[0].pitches, w.G.pitchers.home[0].balls], [3, 0], 'three pitches, no balls');
|
||||
});
|
||||
|
||||
test('ABS: overturning ball four turns the walk into a strikeout; one Undo restores the walk', (t) => {
|
||||
const w = fresh(t);
|
||||
w.addBall(); w.addBall(); w.addBall(); w.addStrike(); w.addStrike();
|
||||
w.addBall(); // ball four: walk
|
||||
assert.equal(pa(w, -1).res, 'BB');
|
||||
Object.assign(w.absState, { open: true, side: 'home', callType: 'ball', result: 'overturned' });
|
||||
w.absConfirm();
|
||||
assert.equal(pa(w, -1).res, 'ꓘ');
|
||||
assert.equal(w.G.bases[0], null, 'no runner');
|
||||
assert.equal(w.G.outs, 1);
|
||||
w.undoAction();
|
||||
assert.equal(pa(w, -1).res, 'BB', 'walk is back');
|
||||
assert.ok(w.G.bases[0], 'runner is back on first');
|
||||
});
|
||||
|
||||
test('reaching on an error: batter to first, counts an at-bat, run that scores is unearned', (t) => {
|
||||
const w = fresh(t);
|
||||
w.outState.type = 'error'; w.outState.fielder = 6; w.recordOut();
|
||||
const h = w.G.lineup.away[0].hits;
|
||||
assert.ok(w.G.bases[0], 'on first');
|
||||
same([h.roe, w.abFor(h)], [1, 1], 'reached on error is an at-bat');
|
||||
w.recordHit(4); // home run scores him
|
||||
const p = w.G.pitchers.home[0];
|
||||
same([p.r, p.er], [2, 1], 'the runner who reached on the error is unearned');
|
||||
});
|
||||
|
||||
test('double play: the runner from first is retired before the batter (out 1, batter out 2)', (t) => {
|
||||
const w = fresh(t);
|
||||
w.recordHit(1);
|
||||
const runner = pa(w, 0);
|
||||
Object.assign(w.outState, { type: 'ground', fielder: 6, throwTo: [4], multiOut: 'dp' });
|
||||
w.recordOut();
|
||||
same([w.G.outs, w.G.bases], [2, [null, null, null]]);
|
||||
same([runner.out, runner.outOnBases, pa(w, -1).out], [1, true, 2]);
|
||||
assert.equal(w.G.pitchers.home[0].outs, 2);
|
||||
});
|
||||
|
||||
test('double play with a 3-fielder throw chain reads G4-6-3', (t) => {
|
||||
const w = fresh(t);
|
||||
w.recordHit(1); // runner on first
|
||||
Object.assign(w.outState, { type: 'ground', fielder: 4, throwTo: [6, 3], multiOut: 'dp' });
|
||||
w.recordOut();
|
||||
assert.equal(pa(w, -1).res, 'G4-6-3', 'the full chain is in the batter cell');
|
||||
same([w.G.outs, w.G.bases], [2, [null, null, null]], 'two outs, bases cleared');
|
||||
});
|
||||
|
||||
test('out on the bases: runner thrown out advancing; the batter keeps his count', (t) => {
|
||||
const w = fresh(t);
|
||||
w.recordHit(2); // runner on second
|
||||
const runner = pa(w, 0);
|
||||
w.addBall(); w.addStrike(); // next batter 1-1
|
||||
w.startRunnerOut();
|
||||
w.executeRunnerOut(2); // out at third
|
||||
same([w.G.outs, w.G.balls, w.G.strikes], [1, 1, 1], 'out recorded, count kept');
|
||||
same([runner.res, runner.reached, runner.out], ['2B', 2, 1], 'cell keeps the double, gets the out');
|
||||
assert.equal(w.G.pitchers.home[0].outs, 1);
|
||||
assert.equal(w.G.lineup.away[0].hits.cs, 0, 'not a caught stealing');
|
||||
});
|
||||
|
||||
test('caught stealing keeps the batter\'s count', (t) => {
|
||||
const w = fresh(t);
|
||||
w.recordHit(1);
|
||||
w.addBall(); w.addBall(); w.addStrike(); // 2-1
|
||||
w.executeBRAction('cs', 0);
|
||||
same([w.G.outs, w.G.balls, w.G.strikes], [1, 2, 1]);
|
||||
});
|
||||
|
||||
test('RISP: a steal of second during the at-bat makes it a RISP at-bat; walks are not at-bats', (t) => {
|
||||
const w = fresh(t);
|
||||
w.recordHit(1);
|
||||
w.recordKO('swinging');
|
||||
assert.equal(pa(w, -1).risp, false, 'runner only on first');
|
||||
w.executeBRAction('sb', 0);
|
||||
w.outState.type = 'fly'; w.outState.fielder = 8; w.recordOut();
|
||||
assert.equal(pa(w, -1).risp, true, 'after the steal');
|
||||
w.addBall(); w.addBall(); w.addBall(); w.addBall();
|
||||
w.recordHit(2); if(w.document.getElementById('rpOverlay')) w.rpAutoAdvance();
|
||||
const l = w.rispLine('away');
|
||||
assert.equal(l.h + '-for-' + l.ab, '1-for-2', 'flyout + double; the walk is not an at-bat');
|
||||
});
|
||||
|
||||
test('innings pitched: each out goes to the pitcher on the mound', (t) => {
|
||||
const w = fresh(t);
|
||||
for(let i = 0; i < 4; i++) w.recordKO('swinging'); // 3 outs top 1, 1 out bottom 1
|
||||
assert.equal(w.fmtIP(w.G.pitchers.home[0].outs), '1.0');
|
||||
assert.equal(w.fmtIP(w.G.pitchers.away[0].outs), '0.1');
|
||||
});
|
||||
|
||||
test('a reliever is not charged for a runner he inherited', (t) => {
|
||||
const w = fresh(t);
|
||||
w.recordHit(1); // starter allows a single
|
||||
w.addPitcher('home'); w.setActivePitcher('home', 1);
|
||||
w.recordHit(4); // reliever allows a homer
|
||||
const [starter, reliever] = w.G.pitchers.home;
|
||||
same([starter.r, starter.er, reliever.r, reliever.er], [1, 1, 1, 1]);
|
||||
});
|
||||
|
||||
test('Undo after deleting a play-log entry restores the right log', (t) => {
|
||||
const w = fresh(t);
|
||||
w.recordHit(1); w.recordKO('swinging');
|
||||
const before = JSON.stringify(w.G.log);
|
||||
w.addBall();
|
||||
w.deleteLogLine(w.G.log.length - 1); // delete the oldest entry (text only)
|
||||
const expected = JSON.parse(before).slice(0, -1);
|
||||
w.undoAction(); // undo the ball
|
||||
same(w.G.log, expected, 'log as before the ball, minus the deleted entry');
|
||||
});
|
||||
|
||||
test('earned runs: with two outs, a batter who reaches on an error ends the inning for earned-run purposes', (t) => {
|
||||
const w = fresh(t);
|
||||
w.recordKO('swinging'); w.recordKO('swinging'); // 2 outs
|
||||
w.outState.type = 'error'; w.outState.fielder = 6; w.recordOut(); // should have been the 3rd out
|
||||
w.recordHit(4); // two-run homer
|
||||
const p = w.G.pitchers.home[0];
|
||||
same([p.r, p.er], [2, 0], 'both runs unearned (the old rule made the homer earned)');
|
||||
});
|
||||
|
||||
test('earned runs: with one out, the reconstructed inning is not over, so the homer is earned', (t) => {
|
||||
const w = fresh(t);
|
||||
w.recordKO('swinging'); // 1 out
|
||||
w.outState.type = 'error'; w.outState.fielder = 6; w.recordOut();
|
||||
w.recordHit(4);
|
||||
const p = w.G.pitchers.home[0];
|
||||
same([p.r, p.er], [2, 1], 'runner who reached on the error unearned, batter earned');
|
||||
});
|
||||
|
||||
test('earned runs: a reliever does not get the benefit of an error made before he came in', (t) => {
|
||||
const w = fresh(t);
|
||||
w.recordKO('swinging'); w.recordKO('swinging');
|
||||
w.outState.type = 'error'; w.outState.fielder = 6; w.recordOut(); // error under the starter
|
||||
w.addPitcher('home'); w.setActivePitcher('home', 1);
|
||||
w.recordHit(4);
|
||||
const [starter, reliever] = w.G.pitchers.home;
|
||||
same([starter.r, starter.er, reliever.r, reliever.er], [1, 0, 1, 1], 'inherited runner unearned to the starter; homer earned to the reliever');
|
||||
});
|
||||
|
||||
test('play log: a result line is linked to its play; "Edit play" opens the scorecard editor', (t) => {
|
||||
const w = fresh(t);
|
||||
w.recordHit(2);
|
||||
const line = w.G.log.findIndex(e => /Double/.test(e.text));
|
||||
assert.equal(w.G.log[line].paId, w.G.pas[0].id, 'linked');
|
||||
w.logEditStart(line);
|
||||
assert.ok(w.document.querySelector('.log-edit-play'), 'Edit play button shown');
|
||||
w.logEditPlay(line);
|
||||
assert.ok(w.document.getElementById('peOverlay'), 'cell editor open');
|
||||
w.closePaEditor();
|
||||
});
|
||||
|
||||
test('play log: deleting a result line can remove the play and its stats (and Undo brings the play back)', async (t) => {
|
||||
const w = fresh(t);
|
||||
w.recordHit(1); w.recordKO('swinging');
|
||||
const line = w.G.log.findIndex(e => /Single/.test(e.text));
|
||||
w.showConfirm = () => Promise.resolve(true); // "Remove play"
|
||||
w.logEditDelete(line);
|
||||
await new Promise(r => setTimeout(r, 0));
|
||||
same([w.G.pas.map(p => p.res), w.G.lineup.away[0].hits.s, w.G.rhe.away[1], w.G.pitchers.home[0].h], [['K'], 0, 0, 0]);
|
||||
assert.ok(!w.G.log.some(e => /Single/.test(e.text)), 'line gone');
|
||||
w.undoAction();
|
||||
same(w.G.pas.map(p => p.res), ['1B', 'K'], 'play restored');
|
||||
});
|
||||
|
||||
test('play log: "Just the log line" leaves the play alone', async (t) => {
|
||||
const w = fresh(t);
|
||||
w.recordHit(1);
|
||||
const line = w.G.log.findIndex(e => /Single/.test(e.text));
|
||||
w.showConfirm = () => Promise.resolve(false);
|
||||
w.logEditDelete(line);
|
||||
await new Promise(r => setTimeout(r, 0));
|
||||
same([w.G.pas.length, w.G.lineup.away[0].hits.s], [1, 1]);
|
||||
assert.ok(!w.G.log.some(e => /Single/.test(e.text)), 'only the line is gone');
|
||||
});
|
||||
|
||||
test('cell editor: changing a flyout to a single moves the batter, pitcher and team stats', (t) => {
|
||||
const w = fresh(t);
|
||||
w.outState.type = 'fly'; w.outState.fielder = 8; w.recordOut();
|
||||
w.openPaEditor(0); w.peSet('t', '1B'); w.savePaEditor();
|
||||
const h = w.G.lineup.away[0].hits;
|
||||
same([h.fo, h.s, w.abFor(h), w.G.pitchers.home[0].h, w.G.rhe.away[1]], [0, 1, 1, 1, 1]);
|
||||
w.undoAction(); // Undo restores a fresh copy of the game
|
||||
const back = w.G.lineup.away[0].hits;
|
||||
same([back.fo, back.s, w.G.rhe.away[1]], [1, 0, 0], 'back to the flyout');
|
||||
});
|
||||
|
||||
test('saved games from older versions load with the new fields', (t) => {
|
||||
const w = fresh(t);
|
||||
const old = JSON.parse(JSON.stringify(w.G));
|
||||
delete old.pas; delete old.mlbKeep;
|
||||
old.pitchers.home.forEach(p => { delete p.outs; delete p.er; delete p.balls; });
|
||||
old.lineup.away.forEach(sl => { delete sl.hits.roe; });
|
||||
const g = w.migrateGame(old);
|
||||
assert.ok(Array.isArray(g.pas));
|
||||
assert.equal(typeof g.mlbKeep, 'object');
|
||||
same([g.pitchers.home[0].outs, g.pitchers.home[0].balls, g.lineup.away[0].hits.roe], [0, 0, 0]);
|
||||
});
|
||||
|
||||
test("catcher's interference: batter to first, not an at-bat, an error on the catcher's team", (t) => {
|
||||
const w = fresh(t);
|
||||
w.recordHit(1); // runner on first
|
||||
w.addStrike(); w.addStrike(); // 0-2, as with Liam Hicks in ALDS Game 2
|
||||
w.recordCI();
|
||||
const p = pa(w, -1), h = w.G.lineup.away[1].hits;
|
||||
assert.equal(p.res, 'CI');
|
||||
same([h.ci, w.abFor(h), w.G.rhe.home[2], w.G.rhe.away[1]], [1, 0, 1, 1], 'CI, no at-bat, one error, still one hit');
|
||||
assert.ok(w.G.bases[0] && w.G.bases[1] && !w.G.bases[2], 'batter on first, runner forced to second');
|
||||
same([w.G.pitchers.home[0].pitches, w.G.pitchers.home[0].bb], [4, 0], 'the pitch counts; not a walk');
|
||||
same([w.G.balls, w.G.strikes, w.G.awayBatter], [0, 0, 2], 'count reset, next batter up');
|
||||
assert.equal(w.paLabelClass('CI'), ' sc-err');
|
||||
});
|
||||
|
||||
test("catcher's interference with the bases loaded: run scores, RBI, unearned", (t) => {
|
||||
const w = fresh(t);
|
||||
w.recordHBP(); w.recordHBP(); w.recordHBP(); // three hit batters: bases loaded
|
||||
assert.ok(w.G.bases.every(Boolean), 'bases loaded');
|
||||
w.recordCI();
|
||||
same([w.G.rhe.away[0], w.G.lineup.away[3].hits.rbi], [1, 1], 'run forced in, RBI to the batter');
|
||||
same([w.G.pitchers.home[0].r, w.G.pitchers.home[0].er], [1, 0], 'unearned');
|
||||
});
|
||||
|
||||
test("the cell editor can change a result to catcher's interference and back", (t) => {
|
||||
const w = fresh(t);
|
||||
w.recordHit(1);
|
||||
w.openPaEditor(0); w.peSet('t', 'CI'); w.savePaEditor();
|
||||
const h = w.G.lineup.away[0].hits;
|
||||
same([pa(w, 0).res, h.s, h.ci, w.G.rhe.away[1], w.G.rhe.home[2]], ['CI', 0, 1, 0, 1]);
|
||||
w.openPaEditor(0); w.peSet('t', '1B'); w.savePaEditor();
|
||||
same([h.s, h.ci, w.G.rhe.away[1], w.G.rhe.home[2]], [1, 0, 1, 0]);
|
||||
});
|
||||
|
||||
test('a passed ball moves the runner up but is not an error; a run scoring on it is unearned', (t) => {
|
||||
const w = fresh(t);
|
||||
w.recordHBP(); w.recordHBP(); w.recordHBP(); // bases loaded
|
||||
w.executeBRAction('pb', 2); // runner on third scores on a passed ball
|
||||
same([w.G.rhe.home[2], w.G.rhe.away[0]], [0, 1], 'no error; the run counts');
|
||||
same([w.G.pitchers.home[0].r, w.G.pitchers.home[0].er], [1, 0], 'unearned');
|
||||
});
|
||||
@@ -1,78 +0,0 @@
|
||||
// Postseason series view at the top of My Games: saved postseason games grouped
|
||||
// by year, round and teams, with the series score from finished games.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { loadApp, same } = require('./helpers/app');
|
||||
|
||||
const NYY = 'New York Yankees', TB = 'Tampa Bay Rays', LAD = 'Los Angeles Dodgers', PHI = 'Philadelphia Phillies';
|
||||
|
||||
// Save a game to My Games directly: teams, score, round, game number, finished or not
|
||||
function saveGame(w, id, { away, home, as, hs, type, num, date = '2026-10-04', final = true }){
|
||||
const G = JSON.parse(JSON.stringify(w.G));
|
||||
G.rhe = { away: [as, 0, 0], home: [hs, 0, 0] };
|
||||
G.log = [final ? { tag: 'Final', text: 'FINAL' } : { tag: 'Play', text: 'single' }];
|
||||
Object.assign(G.notes, { gameType: type, seriesGame: num ? String(num) : '', date });
|
||||
w.localStorage.setItem(w.GM_GAME_PREFIX + id, JSON.stringify({ G, teamAway: away, teamHome: home }));
|
||||
const index = w.gmGetIndex();
|
||||
index.push({ id, away, home, awayScore: as, homeScore: hs, date, status: final ? 'Final' : 'T5', plays: 1 });
|
||||
w.gmSaveIndex(index);
|
||||
}
|
||||
|
||||
test('postseason games are grouped into series with the series score', (t) => {
|
||||
const w = loadApp();
|
||||
t.after(() => w.close());
|
||||
saveGame(w, 'g1', { away: TB, home: NYY, as: 3, hs: 5, type: 'alds', num: 1, date: '2026-10-03' });
|
||||
saveGame(w, 'g2', { away: TB, home: NYY, as: 4, hs: 2, type: 'alds', num: 2, date: '2026-10-04' });
|
||||
saveGame(w, 'g3', { away: NYY, home: TB, as: 6, hs: 1, type: 'alds', num: 3, date: '2026-10-06' });
|
||||
saveGame(w, 'n1', { away: PHI, home: LAD, as: 2, hs: 7, type: 'nlds', num: 1, date: '2026-10-04' });
|
||||
saveGame(w, 'r1', { away: NYY, home: TB, as: 1, hs: 0, type: 'regular', date: '2026-07-04' });
|
||||
|
||||
const list = w.psSeriesList();
|
||||
same(list.map(s => s.label), ['2026 ALDS', '2026 NLDS'], 'one card per series, newest first; regular season left out');
|
||||
const alds = list[0];
|
||||
same(alds.games.map(g => g.id), ['g1', 'g2', 'g3'], 'home and away flip within the series');
|
||||
assert.equal(w.psSeriesStatus(alds), 'Yankees lead 2–1');
|
||||
assert.equal(w.psSeriesStatus(list[1]), 'Dodgers lead 1–0');
|
||||
saveGame(w, 'n2', { away: PHI, home: LAD, as: 1, hs: 1, type: 'nlds', num: 2, date: '2026-10-05', final: false });
|
||||
assert.equal(w.psSeriesStatus(w.psSeriesList()[1]), 'Dodgers lead 1–0', 'a game still in progress doesn\'t make the score uncertain');
|
||||
|
||||
saveGame(w, 'g4', { away: NYY, home: TB, as: 3, hs: 2, type: 'alds', num: 4, date: '2026-10-07' });
|
||||
assert.equal(w.psSeriesStatus(w.psSeriesList()[0]), 'Yankees win 3–1', 'three wins in a best-of-five clinches');
|
||||
});
|
||||
|
||||
test('gaps and unfinished games are shown honestly', (t) => {
|
||||
const w = loadApp();
|
||||
t.after(() => w.close());
|
||||
saveGame(w, 'g1', { away: TB, home: NYY, as: 3, hs: 5, type: 'alds', num: 1 });
|
||||
saveGame(w, 'g3', { away: NYY, home: TB, as: 1, hs: 4, type: 'alds', num: 3 });
|
||||
saveGame(w, 'g4', { away: NYY, home: TB, as: 2, hs: 2, type: 'alds', num: 4, final: false });
|
||||
const s = w.psSeriesList()[0];
|
||||
assert.equal(w.psSeriesStatus(s), 'Tied 1–1 in games you scored', 'Game 2 is missing, so it may not be the real score');
|
||||
const html = w.psSeriesHtml();
|
||||
assert.match(html, /G2 · not scored/);
|
||||
assert.match(html, /G1 · Yankees 5–3/);
|
||||
assert.match(html, /G4 · Yankees 2, Rays 2 · unfinished/);
|
||||
});
|
||||
|
||||
test('My Games shows the series section, uses the official logo, and opens a game from it', (t) => {
|
||||
const w = loadApp();
|
||||
t.after(() => w.close());
|
||||
saveGame(w, 'g1', { away: TB, home: NYY, as: 3, hs: 5, type: 'alds', num: 1 });
|
||||
w.showGameManager();
|
||||
const section = w.document.querySelector('#gmOverlay .ps-series-wrap');
|
||||
assert.ok(section, 'Postseason section is shown');
|
||||
assert.match(section.querySelector('.ps-series-logo').getAttribute('src'), /assets\/postseason\/alds-2026\.png/);
|
||||
// jsdom here doesn't run inline handlers: check the button's, then run it
|
||||
const onclick = section.querySelector('button.ps-game').getAttribute('onclick');
|
||||
assert.equal(onclick, "gmLoadGame('g1')");
|
||||
w.eval(onclick);
|
||||
assert.equal(w.gmGetActiveId(), 'g1', 'tapping a game opens it');
|
||||
same([w.G.rhe.away[0], w.G.rhe.home[0]], [3, 5]);
|
||||
});
|
||||
|
||||
test('no postseason games: no series section', (t) => {
|
||||
const w = loadApp();
|
||||
t.after(() => w.close());
|
||||
saveGame(w, 'r1', { away: NYY, home: TB, as: 1, hs: 0, type: 'regular' });
|
||||
assert.equal(w.psSeriesHtml(), '');
|
||||
});
|
||||
@@ -1,193 +0,0 @@
|
||||
// Sync between two simulated devices sharing a fake Firebase backend.
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { loadApp, same } = require('./helpers/app');
|
||||
const { createBackend, fakeFirebase } = require('./helpers/fake-firebase');
|
||||
|
||||
const wait = (ms = 20) => new Promise(r => setTimeout(r, ms));
|
||||
// Wait until a condition holds (sync runs on timers; a fixed pause can be too short
|
||||
// when the whole suite runs in parallel)
|
||||
async function until(cond, ms = 2000){
|
||||
const end = Date.now() + ms;
|
||||
while(Date.now() < end){ try { if(cond()) return; } catch(e){} await wait(10); }
|
||||
}
|
||||
|
||||
// A device: the app, its fake Firebase client, signed in to the shared backend
|
||||
async function device(t, backend, name){
|
||||
const w = loadApp('https://' + name.toLowerCase() + '.scorecard.test/');
|
||||
// Stop syncing and let in-flight work settle before closing, so no timer fires afterwards
|
||||
t.after(async () => { w._sync.user = null; w.clearTimeout(w._sync.timer); await wait(60); w.close(); });
|
||||
w.FIREBASE_CONFIG = { projectId: 'test' };
|
||||
w.firebase = fakeFirebase(backend);
|
||||
w.SYNC_DELAY_MS = 0;
|
||||
w.syncRenameDevice(name);
|
||||
await w.syncSignIn('fan@example.test', 'correct-horse');
|
||||
await wait();
|
||||
return w;
|
||||
}
|
||||
|
||||
// Score a few plays on a device and let it upload
|
||||
async function scoreAndSync(w, plays){
|
||||
plays.forEach(p => p(w));
|
||||
w._doSave();
|
||||
await w.syncPush();
|
||||
await wait();
|
||||
}
|
||||
const single = w => w.recordHit(1);
|
||||
const strikeout = w => w.recordKO('swinging');
|
||||
|
||||
test('a game scored on one device shows up on the other, in My Games and season stats', async (t) => {
|
||||
const backend = createBackend();
|
||||
const ipad = await device(t, backend, 'iPad');
|
||||
const mac = await device(t, backend, 'Mac');
|
||||
ipad.G.lineup.away[0].name = 'Ben Rice';
|
||||
await scoreAndSync(ipad, [single, strikeout]);
|
||||
|
||||
const id = ipad.gmGetActiveId();
|
||||
const onMac = mac.gmGetIndex().find(e => e.id === id);
|
||||
assert.ok(onMac, 'game is in My Games on the Mac');
|
||||
const payload = JSON.parse(mac.localStorage.getItem(mac.GM_GAME_PREFIX + id));
|
||||
same(payload.G.pas.map(p => p.res), ['1B', 'K']);
|
||||
mac._ss.team = 'all'; mac._ss.attended = 'all'; mac._ss.type = 'all';
|
||||
const rice = mac.ssBatting(mac.ssGames()).find(r => r.name === 'Ben Rice');
|
||||
same([rice.ab, rice.h], [1, 1], 'season stats on the Mac include it');
|
||||
});
|
||||
|
||||
test('a game open on both devices follows the device that is scoring it', async (t) => {
|
||||
const backend = createBackend();
|
||||
const ipad = await device(t, backend, 'iPad');
|
||||
const mac = await device(t, backend, 'Mac');
|
||||
await scoreAndSync(ipad, [single]);
|
||||
const id = ipad.gmGetActiveId();
|
||||
mac.gmLoadGame(id);
|
||||
assert.equal(mac.G.pas.length, 1);
|
||||
await scoreAndSync(ipad, [strikeout, strikeout]);
|
||||
same(mac.G.pas.map(p => p.res), ['1B', 'K', 'K'], 'the Mac shows the new plays');
|
||||
});
|
||||
|
||||
test('deleting a game on one device deletes it everywhere', async (t) => {
|
||||
const backend = createBackend();
|
||||
const ipad = await device(t, backend, 'iPad');
|
||||
const mac = await device(t, backend, 'Mac');
|
||||
await scoreAndSync(ipad, [single]);
|
||||
const id = ipad.gmGetActiveId();
|
||||
ipad.resetGameSilent(); ipad.gmSetActiveId(ipad.gmGenId()); // move on to a new game
|
||||
ipad.gmDeleteSlot(id);
|
||||
await ipad.syncPush(); await wait();
|
||||
assert.ok(!mac.gmGetIndex().some(e => e.id === id), 'gone from My Games on the Mac');
|
||||
assert.equal(mac.localStorage.getItem(mac.GM_GAME_PREFIX + id), null);
|
||||
assert.equal(backend.docs.get('users/uid-1/games/' + id).deleted, true, 'stored as deleted, not erased');
|
||||
});
|
||||
|
||||
test('changes made offline wait, then upload when the device is back online', async (t) => {
|
||||
const backend = createBackend();
|
||||
const ipad = await device(t, backend, 'iPad');
|
||||
const mac = await device(t, backend, 'Mac');
|
||||
await scoreAndSync(ipad, [single]);
|
||||
const id = ipad.gmGetActiveId();
|
||||
ipad.firebase._goOffline();
|
||||
ipad.recordKO('swinging'); ipad._doSave(); ipad.syncPush(); await wait();
|
||||
assert.equal(ipad.syncWaiting(), 1, 'one game waiting');
|
||||
assert.equal(JSON.parse(mac.localStorage.getItem(mac.GM_GAME_PREFIX + id)).G.pas.length, 1, 'Mac has not seen it yet');
|
||||
await ipad.firebase._goOnline();
|
||||
await until(() => ipad.syncWaiting() === 0 && JSON.parse(mac.localStorage.getItem(mac.GM_GAME_PREFIX + id)).G.pas.length === 2);
|
||||
assert.equal(ipad.syncWaiting(), 0, 'nothing waiting');
|
||||
assert.equal(JSON.parse(mac.localStorage.getItem(mac.GM_GAME_PREFIX + id)).G.pas.length, 2, 'Mac has the offline play');
|
||||
});
|
||||
|
||||
test('same game changed on two devices: the newer version wins and the older is kept as a copy', async (t) => {
|
||||
const backend = createBackend();
|
||||
const ipad = await device(t, backend, 'iPad');
|
||||
const mac = await device(t, backend, 'Mac');
|
||||
await scoreAndSync(ipad, [single]);
|
||||
const id = ipad.gmGetActiveId();
|
||||
mac.gmLoadGame(id);
|
||||
|
||||
ipad.firebase._goOffline(); // iPad edits offline (older)
|
||||
ipad.recordKO('swinging'); ipad._doSave(); ipad.syncPush(); await wait();
|
||||
await wait(5);
|
||||
await scoreAndSync(mac, [single, single]); // Mac edits later (newer)
|
||||
|
||||
await ipad.firebase._goOnline();
|
||||
await until(() => ipad.gmGetIndex().some(e => /^Copy/.test(e.status || '')) && JSON.parse(ipad.localStorage.getItem(ipad.GM_GAME_PREFIX + id)).G.pas.length === 3);
|
||||
same(JSON.parse(ipad.localStorage.getItem(ipad.GM_GAME_PREFIX + id)).G.pas.map(p => p.res), ['1B', '1B', '1B'], 'newest (Mac) version wins on the iPad');
|
||||
const copies = ipad.gmGetIndex().filter(e => /^Copy/.test(e.status || ''));
|
||||
assert.equal(copies.length, 1, 'exactly one copy kept');
|
||||
const copy = JSON.parse(ipad.localStorage.getItem(ipad.GM_GAME_PREFIX + copies[0].id));
|
||||
same(copy.G.pas.map(p => p.res), ['1B', 'K'], 'the copy is the iPad\'s offline version');
|
||||
same(JSON.parse(backend.docs.get('users/uid-1/games/' + id).payload).G.pas.map(p => p.res), ['1B', '1B', '1B'], 'cloud keeps the newer version');
|
||||
ipad._ss.team = 'all'; ipad._ss.attended = 'all'; ipad._ss.type = 'all';
|
||||
assert.ok(!ipad.ssGames().some(x => x.id === copies[0].id), 'copies are left out of season stats');
|
||||
});
|
||||
|
||||
test('signing in with the wrong password shows a clear error', async (t) => {
|
||||
const w = loadApp('https://wrong.scorecard.test/');
|
||||
t.after(() => w.close());
|
||||
w.FIREBASE_CONFIG = { projectId: 'test' };
|
||||
w.firebase = fakeFirebase(createBackend());
|
||||
w.openSyncPanel();
|
||||
w.document.getElementById('syncEmail').value = 'fan@example.test';
|
||||
w.document.getElementById('syncPassword').value = 'nope';
|
||||
w.syncSubmitSignIn();
|
||||
await wait();
|
||||
assert.match(w.document.querySelector('.sync-err').textContent, /don't match/);
|
||||
});
|
||||
|
||||
test('sync is invisible until it is set up and signed in', (t) => {
|
||||
const w = loadApp('https://fresh.scorecard.test/');
|
||||
t.after(() => w.close());
|
||||
assert.equal(w.document.getElementById('syncPill').hidden, true, 'no pill before signing in');
|
||||
w.openSyncPanel();
|
||||
assert.ok(w.document.getElementById('syncEmail'), 'configured: the panel offers sign-in');
|
||||
w.closeSyncPanel();
|
||||
w.FIREBASE_CONFIG = null;
|
||||
w.openSyncPanel();
|
||||
assert.match(w.document.querySelector('.sync-body').textContent, /isn't set up/, 'without a config it says so');
|
||||
});
|
||||
|
||||
test('"Sync now" says what happened and shows the device and cloud counts', async (t) => {
|
||||
const backend = createBackend();
|
||||
const ipad = await device(t, backend, 'iPad');
|
||||
await scoreAndSync(ipad, [single]);
|
||||
ipad.openSyncPanel();
|
||||
ipad.syncNow();
|
||||
assert.equal(ipad.document.getElementById('syncNowBtn').textContent, 'Syncing…', 'button shows progress');
|
||||
await wait();
|
||||
const text = ipad.document.querySelector('.sync-body').textContent;
|
||||
assert.match(text, /✓ Synced at .* — nothing new to upload/);
|
||||
assert.match(text, /On this device: 1 game · In the cloud: 1/);
|
||||
ipad.recordKO('swinging'); ipad._doSave();
|
||||
ipad.syncNow(); await wait();
|
||||
assert.match(ipad.document.querySelector('.sync-body').textContent, /1 game uploaded/);
|
||||
});
|
||||
|
||||
test('an upload stuck waiting on the network does not block later syncs', async (t) => {
|
||||
const backend = createBackend();
|
||||
const ipad = await device(t, backend, 'iPad');
|
||||
await scoreAndSync(ipad, [single]);
|
||||
const id = ipad.gmGetActiveId();
|
||||
ipad.firebase._goOffline();
|
||||
ipad.recordKO('swinging'); ipad._doSave(); ipad.syncPush(); // stuck: no network
|
||||
assert.equal(ipad._sync.pushing, false, 'not left "busy"');
|
||||
ipad.recordHit(2); ipad._doSave(); ipad.syncPush(); // a later change still queues
|
||||
await ipad.firebase._goOnline();
|
||||
await until(() => JSON.parse(backend.docs.get('users/uid-1/games/' + id).payload).G.pas.length === 3 && ipad.syncWaiting() === 0);
|
||||
const cloud = JSON.parse(backend.docs.get('users/uid-1/games/' + id).payload);
|
||||
same(cloud.G.pas.map(p => p.res), ['1B', 'K', '2B'], 'the cloud has the latest version');
|
||||
assert.equal(ipad.syncWaiting(), 0);
|
||||
});
|
||||
|
||||
test('on a synced device the backup reminder counts games in the cloud as backed up', async (t) => {
|
||||
const backend = createBackend();
|
||||
const ipad = await device(t, backend, 'iPad');
|
||||
ipad.firebase._goOffline();
|
||||
ipad.recordHit(1); ipad._doSave(); ipad.syncPush(); await wait();
|
||||
assert.equal(ipad.bkUnbacked().length, 1, 'not uploaded yet: still needs a backup');
|
||||
await ipad.firebase._goOnline();
|
||||
await until(() => ipad.bkUnbacked().length === 0);
|
||||
assert.equal(ipad.bkUnbacked().length, 0, 'uploaded: nothing to remind about');
|
||||
ipad.renderBackupHint();
|
||||
assert.match(ipad.document.getElementById('backupHint').textContent, /Backed up by sync/);
|
||||
await ipad.syncSignOut();
|
||||
assert.equal(ipad.bkUnbacked().length, 1, 'signed out: backup files are the only backup again');
|
||||
});
|
||||
@@ -1,46 +0,0 @@
|
||||
const test = require('node:test');
|
||||
const assert = require('node:assert/strict');
|
||||
const { loadApp, tick } = require('./helpers/app');
|
||||
|
||||
test('workspace views retain the game and support keyboard navigation without changing innings', async t => {
|
||||
const w = loadApp(); t.after(() => w.close());
|
||||
w.addBall();
|
||||
w.setWorkspaceView('lineups');
|
||||
assert.equal(w.document.getElementById('scoringPanel').hidden, true);
|
||||
assert.equal(w.document.getElementById('lineupsPanel').hidden, false);
|
||||
const tab = w.document.getElementById('tab-lineups');
|
||||
tab.dispatchEvent(new w.KeyboardEvent('keydown', {key:'ArrowRight',bubbles:true}));
|
||||
assert.equal(w.document.getElementById('tab-notes').getAttribute('aria-selected'), 'true');
|
||||
assert.equal(w.G.inning, 1, 'tab arrow does not trigger the inning shortcut');
|
||||
w.setWorkspaceView('live');
|
||||
assert.equal(w.G.balls, 1, 'count survives view changes');
|
||||
assert.equal(w.document.getElementById('scoringPanel').hidden, false);
|
||||
await tick(20);
|
||||
assert.match(w.document.getElementById('boardStatus').textContent, /SCORING IN PROGRESS/);
|
||||
});
|
||||
|
||||
test('scoreboard reflects scoring, undo, game notes, and imported team selections', t => {
|
||||
const w = loadApp(); t.after(() => w.close());
|
||||
w.document.getElementById('teamAway').value = 'Seattle Mariners';
|
||||
w.document.getElementById('teamHome').value = 'Boston Red Sox';
|
||||
w.onTeamChange();
|
||||
assert.match(w.document.getElementById('matchup').textContent, /Seattle Mariners/);
|
||||
assert.equal(w.document.getElementById('setupTip').hidden, true);
|
||||
w.recordHit(4);
|
||||
assert.match(w.document.querySelector('.matchup-score').textContent, /1:0/);
|
||||
w.undoAction();
|
||||
assert.match(w.document.querySelector('.matchup-score').textContent, /0:0/);
|
||||
w.document.getElementById('giVenue').value = 'Fenway Park';
|
||||
w.saveNotes();
|
||||
assert.equal(w.document.getElementById('boardVenue').textContent, 'Fenway Park');
|
||||
});
|
||||
|
||||
test('out indicators work with the keyboard and announce their state', t => {
|
||||
const w = loadApp(); t.after(() => w.close());
|
||||
const out = w.document.getElementById('o0');
|
||||
// Outside-only jsdom does not execute inline click handlers.
|
||||
out.onclick = () => w.toggleOut(0);
|
||||
out.dispatchEvent(new w.KeyboardEvent('keydown', {key:'Enter',bubbles:true}));
|
||||
assert.equal(w.G.outs, 1);
|
||||
assert.equal(out.getAttribute('aria-pressed'), 'true');
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
// The app is loaded into its own jsdom window by test/helpers/loadApp.js,
|
||||
// so the test runner itself only needs a plain node environment.
|
||||
environment: 'node',
|
||||
include: ['test/**/*.test.js'],
|
||||
},
|
||||
});
|
||||