Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 113 additions & 0 deletions src/__tests__/ptsChartOptionalNeeded.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
// @vitest-environment happy-dom
import { describe, expect, it } from 'vitest';
import { select } from 'd3';
import { scoreGovernor } from 'tods-competition-factory';

import { buildEpisodes } from '../episodes/buildEpisodes';
import { ptsMatch } from '../visualizations/ptsChart';

const { ScoringEngine } = scoreGovernor as any;

// SCORING-102: the factory's v2 kernel omits `needed` tuples for timed, aggregate and outs sets.
// The chart must draw the sets that have tuples, gap the points that lack one, and hide a set with none.

function play(matchUpFormat: string, winners: number[]) {
const engine = new ScoringEngine({ matchUpFormat });
for (const winner of winners) engine.addPoint({ winner });
return buildEpisodes(engine.getState());
}

// happy-dom's SVGTransformList lacks consolidate(), which d3-interpolate calls for `transform`
// tweens; null makes d3 fall back to the identity transform, which these assertions do not read.
const transformList = (globalThis as any).SVGTransformList?.prototype;
if (transformList && !transformList.consolidate) transformList.consolidate = () => null;

/** d3 transitions apply their attrs on a timer, even at duration 0. */
const settle = () => new Promise((resolve) => setTimeout(resolve, 50));

async function render(episodes: any[]) {
const container = document.createElement('div');
document.body.appendChild(container);
const chart: any = ptsMatch();
chart.data(episodes);
select(container).call(chart);
chart.update({});
await settle();
const setDivs = Array.from(container.querySelectorAll('div.pts')) as HTMLElement[];
return {
visible: setDivs.map((div) => div.style.display !== 'none'),
// one path per player; both must carry a drawn `d` for the per-line assertions to mean anything
lines: (setIndex: number) => {
const ds = Array.from(setDivs[setIndex].querySelectorAll('path.ptsChartLine')).map((p) => p.getAttribute('d'));
expect(ds).toHaveLength(2);
ds.forEach((d) => expect(d).toMatch(/^M/));
return ds as string[];
},
};
}

/** The x of every vertex of an SVG path, per subpath (`M` starts a new one). */
function subpathXs(d: string): number[][] {
return d
.split('M')
.filter(Boolean)
.map((segment) => segment.split('L').map((pair) => Number(pair.split(',')[0])));
}

const tiebreakSets = [...Array(7).fill(0), 1, 1];

describe('ptsChart with optional points-to-set tuples (SCORING-102)', () => {
it('draws every set when all points carry tuples (SET3-S:TB7)', async () => {
const episodes = play('SET3-S:TB7', tiebreakSets);
expect(episodes.every((ep: any) => ep.needed?.pointsToSet)).toBe(true);

const chart = await render(episodes);
expect(chart.visible.slice(0, 2)).toEqual([true, true]);
for (const d of chart.lines(0)) {
const subpaths = subpathXs(d);
expect(subpaths).toHaveLength(1);
expect(d).not.toContain('NaN');
}
});

it('does not throw and hides the set when no point carries a tuple (SET1-S:T10)', async () => {
const episodes = play('SET1-S:T10', [0, 1, 0, 0]);
expect(episodes.some((ep: any) => ep.needed?.pointsToSet)).toBe(false);

const chart = await render(episodes);
expect(chart.visible[0]).toBe(false);
});

it('draws the tiebreak sets and hides the timed final set (SET3-S:TB7-F:T10)', async () => {
const episodes = play('SET3-S:TB7-F:T10', [...Array(7).fill(0), ...Array(7).fill(1), 0, 1, 0]);
expect(episodes.filter((ep: any) => !ep.needed?.pointsToSet)).toHaveLength(3);

const chart = await render(episodes);
expect(chart.visible.slice(0, 3)).toEqual([true, true, false]);
for (const setIndex of [0, 1]) {
for (const d of chart.lines(setIndex)) {
expect(subpathXs(d)).toHaveLength(1);
expect(d).not.toContain('NaN');
}
}
});

it('draws a gap, not a zero, for a point without a tuple, keeping point order', async () => {
const episodes = play('SET3-S:TB7', tiebreakSets).map((ep: any, i: number) =>
i === 3 ? { ...ep, needed: undefined } : ep,
);

const chart = await render(episodes);
expect(chart.visible[0]).toBe(true);
for (const d of chart.lines(0)) {
expect(d).not.toContain('NaN');
// vertex 0 is the pre-match start, vertex i + 1 is point i: point 3 (vertex 4) is the gap
const subpaths = subpathXs(d);
expect(subpaths.map((xs) => xs.length)).toEqual([4, 3]);
const xs = subpaths.flat();
expect(xs).toEqual([...xs].sort((a, b) => a - b));
const step = xs[1] - xs[0];
expect(subpaths[1][0] - subpaths[0][3]).toBeCloseTo(2 * step);
}
});
});
52 changes: 36 additions & 16 deletions src/visualizations/ptsChart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,21 @@ function groupGames(point_episodes: any[]) {
return games;
}

/**
* A points-to-set tuple when the episode carries one, else undefined. The factory's v2 kernel omits
* `needed` for timed, aggregate and outs sets, so a set (or a run of points) may have none.
*/
function pointsToSetTuple(episode: any): [number, number] | undefined {
const tuple = episode?.needed?.pointsToSet;
return Array.isArray(tuple) && Number.isFinite(tuple[0]) && Number.isFinite(tuple[1]) ? tuple : undefined;
}

/** True when at least one point of the set at `setIndex` carries a points-to-set tuple. */
function setHasPointsToSet(set: any, setIndex: number): boolean {
const episodes = set?.history?.action?.('addPoint') ?? [];
return episodes.some((ep: any) => ep?.point?.set == setIndex && pointsToSetTuple(ep));
}

function add_index(d: any[], i: number) {
for (const item of d) {
item['_i'] = i;
Expand Down Expand Up @@ -160,7 +175,8 @@ export function ptsMatch() {

let true_height = 0;
for (let s = 0; s < pts_charts.length; s++) {
if (sets?.[s]?.history.points().length) {
// A set with no points-to-set tuples (timed, aggregate, outs) has no series to draw: hide it
if (sets?.[s]?.history.points().length && setHasPointsToSet(sets[s], s)) {
pts_sets[s].style('display', 'inline');
pts_charts[s].width(options.width);
pts_charts[s].height(options.height);
Expand Down Expand Up @@ -575,18 +591,20 @@ function ptsChart() {

const range_start = points[0].point.index;

// Points without a tuple stay undefined in place (point order is kept) and draw as a gap
const tuples = points.map(pointsToSetTuple);
const present = tuples.filter(Boolean) as [number, number][];
if (!present.length) {
return false;
}

game_data = groupGames(points);
pointsToSet = points.map((p: any) => p.needed?.pointsToSet);
const pts_max = Math.max(
...[].concat(
pointsToSet.map((p: number[]) => p[0]),
pointsToSet.map((p: number[]) => p[1]),
),
);
const pts_start = Math.max(...pointsToSet[0]);

// add pts prior to first point
pointsToSet.unshift([pts_start, pts_start]);
pointsToSet = tuples;
const pts_max = Math.max(...present.map((p) => p[0]), ...present.map((p) => p[1]));

// add pts prior to first point; unknown (a gap) when the first point has no tuple
const pts_start = tuples[0] ? Math.max(...tuples[0]) : undefined;
pointsToSet.unshift(pts_start === undefined ? undefined : [pts_start, pts_start]);

const longest_rally =
Math.max.apply(
Expand Down Expand Up @@ -699,6 +717,7 @@ function ptsChart() {

// Player PTS Lines
const lineGen = line()
.defined((d: number | undefined) => d !== undefined)
.x((_: any, i: number) => {
return xScale(i);
})
Expand Down Expand Up @@ -730,15 +749,15 @@ function ptsChart() {
})
// .attr('d', function(d: any) { return lineGen(player_data[d]) })
.attr('d', (d: any) => {
return lineGen(pointsToSet.map((p: any) => p[d]));
return lineGen(pointsToSet.map((p: any) => p?.[d]));
});

const bp_data = [
pointsToSet.map((p: any) => {
return { pts: p[0] };
return { pts: p?.[0] };
}),
pointsToSet.map((p: any) => {
return { pts: p[1] };
return { pts: p?.[1] };
}),
];
const bp_wrappers = pts.selectAll('.' + options.class + 'BPWrapper').data(bp_data)
Expand Down Expand Up @@ -768,6 +787,7 @@ function ptsChart() {
}
})
.style('opacity', (d: any, i: any) => {
if (d.pts === undefined) return 0;
if (points[i - 1] && points[i - 1].point.isBreakpoint != undefined) {
// return points[i - 1].point.isBreakpoint == d._i ? 1 : 0
return points[i - 1].point.server == 1 - d._i ? 1 : 0;
Expand All @@ -777,7 +797,7 @@ function ptsChart() {
return xScale(i);
})
.attr('cy', (d: any) => {
return yScale(pts_max - d.pts);
return d.pts === undefined ? 0 : yScale(pts_max - d.pts);
})
.attr('r', 2);

Expand Down