@courthive/scoring-visualizations 0.2.5 → 0.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,5 +1,271 @@
1
- # Scoring Visualizations
1
+ # @courthive/scoring-visualizations
2
2
 
3
- Data visualizations built with D3.js and the [Competition Factory](https://courthive.github.io/competition-factory/) ScoringEngine.
3
+ Standalone scoring visualizations for tennis match data. Transforms [TODS](https://itftennis.atlassian.net/wiki/spaces/TODS/overview) match data (via the [Competition Factory](https://courthive.github.io/competition-factory/) `ScoringEngine`) into episode sequences and renders interactive D3 charts — GameTree, Momentum, PTS, GameFish, Corona, rally trees, stat panels, and dashboards — plus parsers/validators for third-party match feeds (ProTracker `.ptf` files and IONSport JSON) and a factory-backed statistics adapter.
4
4
 
5
- View here: [TennisVisuals.com](https://www.tennisvisuals.com)
5
+ Part of the [CourtHive](https://github.com/CourtHive) ecosystem. Consumed by `epixodic` (point-by-point match tracker) and `competition-factory-server`.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pnpm add @courthive/scoring-visualizations
11
+ ```
12
+
13
+ `tods-competition-factory` (>=5.0.0) is a peer dependency and must be installed alongside. `d3` and `tippy.js` are bundled dependencies.
14
+
15
+ ## Rendering patterns
16
+
17
+ Most charts follow the **D3 reusable-chart closure pattern**: call the factory (e.g. `gameTree()`) to get a configurable `chart` function, feed it data via chained accessors, then mount it into a container with a D3 selection:
18
+
19
+ ```typescript
20
+ import { select } from 'd3';
21
+ import { gameTree, buildEpisodes } from '@courthive/scoring-visualizations';
22
+
23
+ const chart = gameTree();
24
+ chart.options({ display: { sizeToFit: true } });
25
+ chart.players(['Federer', 'Djokovic']);
26
+ chart.data(buildEpisodes(matchUp)); // or chart.matchUp(matchUp)
27
+
28
+ select(container).call(chart);
29
+ chart.update();
30
+ ```
31
+
32
+ Charts that expose a `.matchUp(matchUpState)` accessor can be driven directly from live `ScoringEngine` state — pair them with `LiveEngine` for reactive updates.
33
+
34
+ Several charts also ship a `*FromMatchUp` convenience wrapper (and `coronaChart` / `donutChart` / `simpleChart` render directly) that take a DOM element and a MatchUp and render in one call, sizing to the container.
35
+
36
+ ## API reference
37
+
38
+ ### Episodes
39
+
40
+ The episode array is the common intermediate representation consumed by every chart and the statistics adapter.
41
+
42
+ #### `buildEpisodes(matchUp): Episode[]`
43
+
44
+ Transforms a `ScoringEngine` MatchUp (from `getState()`) into an ordered `Episode[]`, one entry per point played. Each `Episode` carries point, game, set, and "needed" (points/games remaining) sub-objects. Returns `[]` when the MatchUp has no point history.
45
+
46
+ Exported types: `Episode`, `EpisodePoint`, `EpisodeGame`, `EpisodeSet`, `EpisodeNeeded`.
47
+
48
+ ```typescript
49
+ import { buildEpisodes } from '@courthive/scoring-visualizations';
50
+
51
+ const episodes = buildEpisodes(scoringEngine.getState());
52
+ ```
53
+
54
+ ### Charts
55
+
56
+ Reusable-chart closures (call, configure, mount). All accept episode data via `.data(episodes)` and most accept live state via `.matchUp(matchUpState)`:
57
+
58
+ #### `gameTree()`
59
+ Sankey-style point-progression tree for game scoring. Accessors: `.options()`, `.events()`, `.data()`, `.players()`, `.matchUp()`, `.width()`, `.height()`, `.reset()`, `.counters()`, `.exports()`, `.update()`.
60
+
61
+ #### `momentumChart()`
62
+ Vertical/horizontal momentum ribbon (game-fish "school") across the match.
63
+
64
+ #### `gameFish()`
65
+ Single-game "fish" cell grid visualizing point-by-point flow within a game.
66
+
67
+ #### `rallyTree()`
68
+ Rally-length tree. Accessors include `.data()` and `.matchUp()`.
69
+
70
+ #### `ptsHorizon()`
71
+ Compact horizon band of the point-score differential timeline; supports a brush for range selection (used to coordinate the dashboard).
72
+
73
+ #### `ptsMatch()`
74
+ Full point-timeline-series (PTS) match chart.
75
+
76
+ #### `horizonChart()`
77
+ Generic horizon-band chart primitive.
78
+
79
+ #### `statView()`
80
+ Statistics panel rendered from `StatObject[]` (or `.matchUp()` state).
81
+
82
+ #### `matchUpDashboard()`
83
+ Cross-visualization coordination layer — CSS-grid layout combining `ptsHorizon`, `coronaChart`, `statView`, `gameTree`, and `rallyTree`, with `ptsHorizon` brush events filtering all sub-charts simultaneously. Configurable via `.options({ colors, players, display })`.
84
+
85
+ Direct-render charts (call with a target element + data):
86
+
87
+ #### `coronaChart(target, setMap, prefs, x?, y?): void`
88
+ Radial/circular point-differential chart. `target` is a D3 selection, `setMap` is a `SetMap[]` (see `buildSetMap`), `prefs` configures dimensions/colors/display. `x` and `y` default to `0`.
89
+
90
+ #### `coronaChartFromMatchUp(container, matchUp, options?): void`
91
+ Convenience wrapper: takes an `HTMLElement` and a MatchUp, auto-sizes to the container. `options` supports `width`, `height`, `radius`, `colors`, `players`, `display`.
92
+
93
+ #### `ptsHorizonFromMatchUp(container, matchUp, options?): void`
94
+ Convenience wrapper for `ptsHorizon`. `options` supports `width`, `height`, `bands`, `mode` (`'mirror' | 'offset'`), `colors`, `players`, `showBrush`.
95
+
96
+ #### `simpleChart(target, data, playerNames?): void`
97
+ Minimal chart primitive. `simpleChartFromMatchUp(target, matchUp, playerNames?)` renders from a MatchUp.
98
+
99
+ #### `donutChart(target, data, options?): void`
100
+ Match-competitiveness donut from `DonutDatum[]`. `donutChartFromMatchUps(target, matchUps, options?)` aggregates first via `aggregateMatchUps(matchUps): DonutDatum[]`. Types: `DonutChartOptions`, `DonutDatum`, `CompetitivenessBucket` (`'COMPETITIVE' | 'ROUTINE' | 'DECISIVE' | 'WALKOVER'`).
101
+
102
+ Chart event types: `PtsChartEvents`, `GameFishEvents`, `GameTreeEvents`, `MomentumChartEvents`.
103
+
104
+ ```typescript
105
+ import { select } from 'd3';
106
+ import { coronaChartFromMatchUp, momentumChart, buildEpisodes } from '@courthive/scoring-visualizations';
107
+
108
+ // Direct one-call render
109
+ coronaChartFromMatchUp(document.getElementById('corona'), matchUp, {
110
+ players: ['Federer', 'Djokovic'],
111
+ });
112
+
113
+ // Reusable-chart pattern
114
+ const chart = momentumChart();
115
+ chart.data(buildEpisodes(matchUp));
116
+ select('#momentum').call(chart);
117
+ chart.update();
118
+ ```
119
+
120
+ ### Engines
121
+
122
+ #### `class LiveEngine`
123
+ Reactive pub/sub wrapper around the factory `ScoringEngine`. Every mutation notifies subscribers with fresh `getState()`.
124
+
125
+ - `new LiveEngine(engine?)` — wraps a provided engine or creates one (`SET3-S:6/TB7`).
126
+ - `subscribe(cb: (matchUp) => void): () => void` — returns an unsubscribe function.
127
+ - Mutations (notify): `addPoint({ winner, server?, result?, rallyLength? })`, `undo(count?)`, `redo(count?)`, `editPoint(pointIndex, newData, options?)`, `reset()`.
128
+ - Queries (no notify): `getState()`, `canUndo()`, `canRedo()`, `isComplete()`, `getPointCount()`, `getScoreboard()`.
129
+
130
+ #### `createPlaybackEngine(options): PlaybackControls`
131
+ Incrementally feeds MCP fixture points into a `LiveEngine` — auto-play with configurable delay, step forward/back, pause, reset. `options`: `matchIndex?` (default `0`), `delayMs?` (default `200`), `onComplete?`. Returns `PlaybackControls`: `{ liveEngine, start(), pause(), stepForward(), stepBack(), reset(), isPlaying(), getProgress(), getFixture(), destroy() }`.
132
+
133
+ ```typescript
134
+ import { select } from 'd3';
135
+ import { createPlaybackEngine, gameTree } from '@courthive/scoring-visualizations';
136
+
137
+ const chart = gameTree();
138
+ const playback = createPlaybackEngine({ matchIndex: 0, delayMs: 200 });
139
+
140
+ playback.liveEngine.subscribe((matchUp) => {
141
+ chart.matchUp(matchUp);
142
+ chart.update();
143
+ });
144
+
145
+ select('#chart').call(chart);
146
+ playback.start();
147
+ ```
148
+
149
+ #### ScoringEngine fixtures & extractors
150
+
151
+ - `feedMatchUp(matchIndex = 0): any` — builds a MatchUp by feeding a bundled MCP fixture through a `ScoringEngine`.
152
+ - `feedAllMatchUps(): any[]` — all bundled fixtures fed to completion.
153
+ - `getMcpFixture(matchIndex = 0): McpFixture` — raw fixture (players, points).
154
+ - `extractRallyLengths(matchUp): number[][]`
155
+ - `extractGamePoints(matchUp, setIdx = 0, gameIdx = 0): any[]`
156
+
157
+ #### `buildSetMap(matchUp, players?): SetMap[]`
158
+ Derives per-set point-differential data (`p2sdiff`, `gamesScore`, `players`, `winnerIndex`) used by `coronaChart`. `players` defaults to `['Player 1', 'Player 2']`. Type: `SetMap`.
159
+
160
+ ### Parsers & Validators
161
+
162
+ Parse and validate third-party match feeds into factory-compatible structures.
163
+
164
+ ProTracker (`.ptf`, UTF-16LE):
165
+
166
+ - `validateProTrackerMatch(options): ProTrackerValidationResult` — `options`: `{ content, matchUpFormat?, debug? }`.
167
+ - `validateProTrackerBuffer(buffer, options?): ProTrackerValidationResult` — decodes an `ArrayBuffer`, then validates.
168
+ - `parsePTFContent(...)`, `parsePTFPoint(...)`, `mapPTFFormat(...)`, `classifyResult(...)`, `mapServeLocation(...)`, `decodeUTF16LE(...)`, `splitPTFRows(...)`.
169
+
170
+ IONSport (JSON):
171
+
172
+ - `parseIONSportMatch(jsonData): ParsedIONSportMatch` — parses a raw IONSport match object.
173
+ - `validateIONSportMatch(options): IONSportValidationResult` — `options`: `{ jsonData, debug? }`.
174
+ - `parseIONSportPoint(...)`, `mapIONSportFormat(ionFormat: string): string` (maps to a factory `matchUpFormat`, default `SET3-S:6/TB7`), `isTimedFormat(matchFormat: string): boolean`, `extractPlayersFromSide(...)`, `extractPlayers(...)`, `buildSubstitutionEvents(courtTimeLog): SubstitutionInfo[]`.
175
+
176
+ Exported types: `PointResult`, `StrokeType`, `ServeLocation`, `RallyShot`, `ProTrackerValidationResult`, `ProTrackerValidationOptions`, `IONSportValidationResult`, `IONSportValidationOptions`, `PTFMatch`, `ParsedPTFPoint`, `ParsedIONSportMatch`, `PlayerInfo`, `SubstitutionInfo`.
177
+
178
+ ```typescript
179
+ import { validateProTrackerBuffer, parseIONSportMatch } from '@courthive/scoring-visualizations';
180
+
181
+ const result = validateProTrackerBuffer(arrayBuffer, { matchUpFormat: 'SET3-S:6/TB7' });
182
+ if (result.valid) {
183
+ /* result.errors / result.warnings otherwise */
184
+ }
185
+
186
+ const parsed = parseIONSportMatch(ionSportJson);
187
+ ```
188
+
189
+ ### Statistics
190
+
191
+ #### `computeMatchStats(episodes, setFilter?): StatObject[]`
192
+ Computes display-ready match statistics from an `Episode[]`, delegating calculation to `tods-competition-factory`. `setFilter` (0-based) restricts stats to a single set; omit for the whole match.
193
+
194
+ #### `computeMatchStatsFromMatchUp(matchUp, setFilter?): StatObject[]`
195
+ Convenience wrapper — runs `buildEpisodes` then `computeMatchStats`.
196
+
197
+ Type: `StatObject` (re-exported from the factory).
198
+
199
+ ```typescript
200
+ import { computeMatchStatsFromMatchUp, statView } from '@courthive/scoring-visualizations';
201
+ import { select } from 'd3';
202
+
203
+ const stats = computeMatchStatsFromMatchUp(matchUp);
204
+ const panel = statView();
205
+ panel.data(stats);
206
+ select('#stats').call(panel);
207
+ panel.update();
208
+ ```
209
+
210
+ ### Utilities & helpers
211
+
212
+ - `supportsGameVisualizations(matchUpFormat): boolean` — whether a format has traditional game scoring (required by GameTree/GameFish/etc.).
213
+ - `supportsPointsToVisualization(matchUpFormat): boolean` — whether a format exposes points-to-win data.
214
+ - `createFileDropzone(options): HTMLElement` — drag-and-drop widget for loading `.ptf`/JSON match files. `options`: `{ onPTFFile, onJSONFile, onError }`. Type: `FileDropzoneOptions`.
215
+
216
+ ## Architecture
217
+
218
+ ```
219
+ ScoringEngine MatchUp (TODS) Third-party feeds (.ptf / IONSport JSON)
220
+ │ │
221
+ │ buildEpisodes() parse* / validate* / map*Format()
222
+ ▼ ▼
223
+ Episode[] ◄──────────────────────── factory-compatible match data
224
+ │
225
+ ├─► D3 charts (gameTree, momentum, gameFish, ptsHorizon, corona, rallyTree, statView, dashboard)
226
+ └─► computeMatchStats() → StatObject[] → statView
227
+ ```
228
+
229
+ The `Episode[]` array is the pivot between data and presentation: `buildEpisodes` turns engine state into episodes, charts render episodes, and `computeMatchStats` derives statistics from them. `LiveEngine` closes the loop for interactive/live scoring by pushing fresh state to subscribed charts on every mutation.
230
+
231
+ ### Source layout
232
+
233
+ ```
234
+ src/
235
+ index.ts Public API exports
236
+ episodes/ Episode transform (buildEpisodes + types)
237
+ engine/ LiveEngine, playback, feedMatchUp fixtures, buildSetMap
238
+ parsers/ ProTracker + IONSport parsers and validators
239
+ statistics/ Factory-backed match statistics adapter
240
+ utils/ Format-support helpers
241
+ visualizations/ D3 chart implementations + Storybook stories + helpers
242
+ ```
243
+
244
+ Vite library mode outputs ES and UMD bundles to `dist/`; TypeScript declarations are emitted via `tsc --emitDeclarationOnly`.
245
+
246
+ ## Development
247
+
248
+ ```bash
249
+ pnpm install
250
+ pnpm build # Vite library build → dist/
251
+ pnpm build:types # Emit .d.ts declarations only
252
+ pnpm test # Vitest single run
253
+ pnpm test:watch # Vitest watch mode
254
+ pnpm lint # ESLint on src/
255
+ pnpm storybook # Storybook dev server on :6006
256
+ pnpm build-storybook # Build static Storybook
257
+ ```
258
+
259
+ Storybook (11 stories across the chart set, with live-playback and format-awareness demos) is the primary surface for visual development and testing — run `pnpm storybook` and open <http://localhost:6006>.
260
+
261
+ ### Key dependencies
262
+
263
+ | Package | Purpose |
264
+ | --- | --- |
265
+ | `d3` | Charting / SVG rendering |
266
+ | `tippy.js` | Tooltips for interactive elements |
267
+ | `tods-competition-factory` | TODS types, `ScoringEngine`, and statistics (peer dependency) |
268
+
269
+ ## License
270
+
271
+ MIT
@@ -2173,7 +2173,7 @@ function He(e, t, n, r, i, a, o, s, c, l, u, d, f, p, m) {
2173
2173
  } else e.selectAll(".sbox" + t.id).remove(), e.selectAll(".return" + t.id).remove(), e.selectAll(".serve" + t.id).remove();
2174
2174
  }
2175
2175
  function Ue(e) {
2176
- let t = [], n = new Set([
2176
+ let t = [], n = /* @__PURE__ */ new Set([
2177
2177
  "Ace",
2178
2178
  "Serve Winner",
2179
2179
  "Double Fault"
@@ -2665,11 +2665,11 @@ function Xe() {
2665
2665
  }, c;
2666
2666
  }
2667
2667
  function Ze() {
2668
- let e, t, n, r = new Set([
2668
+ let e, t, n, r = /* @__PURE__ */ new Set([
2669
2669
  "Ace",
2670
2670
  "Winner",
2671
2671
  "Serve Winner"
2672
- ]), i = new Set([
2672
+ ]), i = /* @__PURE__ */ new Set([
2673
2673
  "Forced Error",
2674
2674
  "Unforced Error",
2675
2675
  "Double Fault",
@@ -3228,12 +3228,12 @@ var at = [
3228
3228
  ROUTINE: "Routine",
3229
3229
  DECISIVE: "Decisive",
3230
3230
  WALKOVER: "Walkover / Defaulted"
3231
- }, lt = new Set([
3231
+ }, lt = /* @__PURE__ */ new Set([
3232
3232
  "WALKOVER",
3233
3233
  "DOUBLE_WALKOVER",
3234
3234
  "DEFAULTED",
3235
3235
  "DOUBLE_DEFAULT"
3236
- ]), ut = new Set([
3236
+ ]), ut = /* @__PURE__ */ new Set([
3237
3237
  "COMPETITIVE",
3238
3238
  "ROUTINE",
3239
3239
  "DECISIVE"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@courthive/scoring-visualizations",
3
- "version": "0.2.5",
3
+ "version": "0.2.7",
4
4
  "description": "Standalone scoring visualizations for tennis match data — episode transforms, D3 charts (GameTree, Momentum, PTS, GameFish, Corona)",
5
5
  "type": "module",
6
6
  "main": "dist/scoring-visualizations.es.js",
@@ -40,16 +40,16 @@
40
40
  "game-tree",
41
41
  "momentum"
42
42
  ],
43
- "packageManager": "pnpm@11.5.1",
43
+ "packageManager": "pnpm@11.9.0",
44
44
  "license": "MIT",
45
45
  "dependencies": {
46
46
  "d3": "^7.9.0",
47
47
  "tippy.js": "^6.3.7",
48
- "tods-competition-factory": "5.4.0"
48
+ "tods-competition-factory": "6.0.2"
49
49
  },
50
50
  "devDependencies": {
51
- "@commitlint/cli": "21.0.2",
52
- "@commitlint/config-conventional": "21.0.2",
51
+ "@commitlint/cli": "21.1.0",
52
+ "@commitlint/config-conventional": "21.1.0",
53
53
  "@eslint/js": "^10.0.1",
54
54
  "@storybook/addon-docs": "^10.2.17",
55
55
  "@storybook/addon-links": "^10.2.17",