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
3 changes: 3 additions & 0 deletions src/api/analysis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,9 @@ export const fetchAnalyzedMaiaGame = async (
// is saved. (A reply without is_owner, from before the backend sent it,
// counts as the owner's, as every game opened then was.)
isOwner: data['is_owner'] !== false,
// The PGN the backend built, with each move's clock in a game played
// with clocks (for the export).
pgn: typeof data['pgn'] === 'string' ? data['pgn'] : undefined,
// UTC, with or without a zone; `ended_time` only on games finished since
// the backend began keeping it.
createdAt: parseTimeMs(data['created_time']),
Expand Down
4 changes: 4 additions & 0 deletions src/components/Board/GameplayInterface.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ export const GameplayInterface: React.FC<React.PropsWithChildren<Props>> = (
setPremove,
clearPremove,
premoveResetKey,
practice,
} = useContext(PlayControllerContext)

const { user } = useContext(AuthContext)
Expand Down Expand Up @@ -200,6 +201,9 @@ export const GameplayInterface: React.FC<React.PropsWithChildren<Props>> = (
? gameStart.rating
: undefined
const pgnDetails = {
// A practice game's clocks can't be rebuilt from its move times: a
// takeback keeps the time used, and added time isn't kept move by move.
withClocks: !practice,
date: gameStart?.gameId === game.id ? gameStart.date : undefined,
timeControl: pgnTimeControl(timeControl),
whiteElo:
Expand Down
52 changes: 50 additions & 2 deletions src/components/Common/ExportGame.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { render, screen } from '@testing-library/react'
import { Chess } from 'chess.ts'
import { GameTree } from 'src/types'
import { AnalyzedGame, GameTree } from 'src/types'
import { ExportGame } from './ExportGame'

const buildTree = () => {
Expand Down Expand Up @@ -33,6 +33,7 @@ describe('ExportGame', () => {
type="play"
date="2026.11.06"
timeControl="300+3"
withClocks
whiteElo={1432}
blackElo={1500}
/>,
Expand All @@ -46,6 +47,53 @@ describe('ExportGame', () => {
expect(pgn).toContain('[BlackElo "1500"]')
expect(pgn).toContain('[TimeControl "300+3"]')
expect(pgn).toContain('[Termination "Resign"]')
expect(pgn).toContain('1. e4 e5 (1... c5) 0-1')
// Each main-line move with its clock (the first two moves are free).
expect(pgn).toContain(
'1. e4 { [%clk 0:05:00] } 1... e5 { [%clk 0:05:00] } (1... c5) 0-1',
)
})

it('leaves the clocks out of a practice game', () => {
const tree = buildTree()
render(
<ExportGame
game={{ id: 'g1', turn: 'white', tree }}
gameTree={tree}
currentNode={tree.getRoot()}
whitePlayer="Guest"
blackPlayer="Maia-3 1500"
event="Play vs. Maia-3 1500"
type="play"
timeControl="300+3"
withClocks={false}
/>,
)
const pgn = screen.getByText(/\[Event/).textContent ?? ''
expect(pgn).toContain('1. e4 e5 (1... c5) *')
})

it("writes an analysed game's clocks from the PGN it came with", () => {
const tree = buildTree()
render(
<ExportGame
game={
{
id: 'g1',
tree,
type: 'play',
pgn: '1. e4 { [%clk 0:05:00] } 1... e5 { [%clk 0:04:58] } *',
} as unknown as AnalyzedGame
}
currentNode={tree.getRoot()}
whitePlayer="Guest"
blackPlayer="Maia-3 1500"
event="Analysis"
type="analysis"
/>,
)
const pgn = screen.getByText(/\[Event/).textContent ?? ''
expect(pgn).toContain(
'1. e4 { [%clk 0:05:00] } 1... e5 { [%clk 0:04:58] } (1... c5) *',
)
})
})
44 changes: 30 additions & 14 deletions src/components/Common/ExportGame.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { useContext, useEffect, useState } from 'react'

import { PlayedGame, AnalyzedGame, GameTree, GameNode } from 'src/types'
import { TreeControllerContext } from 'src/contexts'
import { gameTreeToPgn } from 'src/lib/pgn'
import { gameTreeToPgn, mainlineClocks, pgnClocks } from 'src/lib/pgn'

// What the PGN's headers say of the game when it's known.
interface GameDetails {
Expand All @@ -15,6 +15,8 @@ interface GameDetails {
timeControl?: string
whiteElo?: number
blackElo?: number
/** A game played here: each move's clock, from the time it took. */
withClocks?: boolean
}

interface AnalysisProps extends GameDetails {
Expand Down Expand Up @@ -58,6 +60,7 @@ export const ExportGame: React.FC<Props> = (props) => {
timeControl,
whiteElo,
blackElo,
withClocks,
} = props
const [fen, setFen] = useState('')
const [pgn, setPgn] = useState('')
Expand Down Expand Up @@ -88,19 +91,31 @@ export const ExportGame: React.FC<Props> = (props) => {
elo && Number.isFinite(elo) && elo > 0 ? Math.round(elo) : undefined

setPgn(
gameTreeToPgn(gameTree, {
Event: event,
Site: 'https://maiachess.com/',
Date: date,
White: whitePlayer,
Black: blackPlayer,
Result: game.termination?.result,
ID: game.id,
WhiteElo: positiveElo(whiteElo),
BlackElo: positiveElo(blackElo),
TimeControl: timeControl,
Termination: game.termination?.condition,
}),
gameTreeToPgn(
gameTree,
{
Event: event,
Site: 'https://maiachess.com/',
Date: date,
White: whitePlayer,
Black: blackPlayer,
Result: game.termination?.result,
ID: game.id,
WhiteElo: positiveElo(whiteElo),
BlackElo: positiveElo(blackElo),
TimeControl: timeControl,
Termination: game.termination?.condition,
},
// A game played here: each move's clock, from the time it took; a
// game opened for analysis: the clocks in the PGN it came with.
type === 'play'
? withClocks
? mainlineClocks(gameTree, timeControl)
: undefined
: type === 'analysis'
? pgnClocks(gameTree, (game as AnalyzedGame).pgn)
: undefined,
),
)
setFen(currentNode.fen)
}, [
Expand All @@ -116,6 +131,7 @@ export const ExportGame: React.FC<Props> = (props) => {
timeControl,
whiteElo,
blackElo,
withClocks,
])

const copy = (content: string) => {
Expand Down
1 change: 1 addition & 0 deletions src/contexts/PlayControllerContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export interface IPlayControllerContext extends BaseTreeControllerContext {
setPremove: ReturnType<typeof usePlayController>['setPremove']
clearPremove: ReturnType<typeof usePlayController>['clearPremove']
premoveResetKey: ReturnType<typeof usePlayController>['premoveResetKey']
practice?: ReturnType<typeof usePlayController>['practice']
}

const fn = () => {
Expand Down
14 changes: 14 additions & 0 deletions src/hooks/usePlayController/usePlayController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,19 @@ export const usePlayController = (
[],
)

// The time the server's clock charged each move (its move_times), in place
// of the time the board first gave it: the player's move as this page
// timed it, and Maia's as its delay.
const syncMoveTimes = useCallback(
(times: number[]) => {
const mainLine = gameTree.getMainLine()
for (let i = 1; i < mainLine.length && i <= times.length; i++) {
mainLine[i].time = times[i - 1]
}
},
[gameTree],
)

const addMoveWithTime = useCallback(
(moveUci: string, moveTime: number) => {
const lastNode = gameTree.getLastMainlineNode()
Expand Down Expand Up @@ -379,6 +392,7 @@ export const usePlayController = (
setOrientation: controller.setOrientation,

addMoveWithTime,
syncMoveTimes,
setServerTermination,
syncClocks,
clockExpired,
Expand Down
2 changes: 2 additions & 0 deletions src/hooks/usePlayController/useServerTurns.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,7 @@ export const useServerTurns = (options: Options) => {
let moveTimeout: ReturnType<typeof setTimeout> | undefined

const settle = (afterMaia: Chess | null) => {
controller.syncMoveTimes(game.move_times)
const clocks = serverClocks(game)
if (clocks) {
controller.syncClocks(clocks.white, clocks.black, clocks.running)
Expand Down Expand Up @@ -263,6 +264,7 @@ export const useServerTurns = (options: Options) => {
skipped.ply === shownPly &&
plyRef.current === shownPly
) {
controller.syncMoveTimes(skipped.move_times)
controller.syncClocks(clocks.white, clocks.black, clocks.running)
}
})
Expand Down
93 changes: 93 additions & 0 deletions src/lib/pgn.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import { Chess } from 'chess.ts'
import { GameTree } from 'src/types'
import {
formatPgnClock,
formatPgnDate,
gameTreeToPgn,
graftVariations,
hasVariations,
mainlineClocks,
pgnClocks,
parsePgnWithVariations,
pgnNameOr,
pgnPlayerName,
Expand Down Expand Up @@ -235,3 +238,93 @@ describe('pgnNameOr and playerLabel', () => {
expect(playerLabel('None', 'white', 'play')).toBe('Guest')
})
})

describe('mainlineClocks', () => {
// 1. e4 e5 2. Nf3 Nc6, each move taking the time given (ms).
const timedTree = (times: number[]) => {
const tree = new GameTree(START)
tree.addMovesToMainLine(['e2e4', 'e7e5', 'g1f3', 'b8c6'], times)
return tree
}

it('charges each move after the first two and adds the increment', () => {
const tree = timedTree([5000, 7000, 12000, 3000])
const clocks = mainlineClocks(tree, '180+2')!
expect(
tree
.getMainLine()
.slice(1)
.map((node) => clocks.get(node)),
).toEqual([180000, 180000, 170000, 179000])
})

it('has no clocks in a game without them', () => {
expect(mainlineClocks(timedTree([1, 1, 1, 1]), '-')).toBeUndefined()
expect(mainlineClocks(timedTree([1, 1, 1, 1]), undefined)).toBeUndefined()
})

it('writes them as %clk comments after each main-line move', () => {
const tree = timedTree([5000, 7000, 12000, 3000])
const pgn = gameTreeToPgn(
tree,
{ Result: '*' },
mainlineClocks(tree, '180+2'),
)
expect(movetextOf(pgn)).toBe(
'1. e4 { [%clk 0:03:00] } 1... e5 { [%clk 0:03:00] } ' +
'2. Nf3 { [%clk 0:02:50] } 2... Nc6 { [%clk 0:02:59] } *',
)
// And it reads back as the same game.
expect(parsePgnWithVariations(pgn)?.tree.toMoveArray()).toEqual([
'e2e4',
'e7e5',
'g1f3',
'b8c6',
])
})

it('formats hours and runs no lower than zero', () => {
expect(formatPgnClock(3 * 3600 * 1000 + 61500)).toBe('3:01:01')
expect(formatPgnClock(-200)).toBe('0:00:00')
})
})

describe('pgnClocks', () => {
const tree = () => {
const t = new GameTree(START)
t.addMovesToMainLine(['e2e4', 'e7e5', 'g1f3', 'b8c6'])
return t
}
const clocksOf = (t: GameTree, clocks?: Map<unknown, number>) =>
t
.getMainLine()
.slice(1)
.map((node) => clocks?.get(node))

it("reads each move's clock from the PGN's %clk comments", () => {
const t = tree()
const pgn =
'[Event "play Maia Game"]\n\n1. e4 { [%clk 0:03:00] } 1... e5 { [%clk 0:03:00] } ' +
'2. Nf3 { [%clk 0:02:50] }\n2... Nc6 { [%clk 0:02:59.5] } *'
expect(clocksOf(t, pgnClocks(t, pgn))).toEqual([
180000, 180000, 170000, 179500,
])
})

it('stops where the PGN and the tree part ways', () => {
const t = tree()
const pgn =
'1. e4 { [%clk 0:03:00] } 1... c5 { [%clk 0:03:00] } 2. Nf3 { [%clk 0:02:50] } *'
expect(clocksOf(t, pgnClocks(t, pgn))).toEqual([
180000,
undefined,
undefined,
undefined,
])
})

it('has none without a PGN or without clocks in it', () => {
expect(pgnClocks(tree(), undefined)).toBeUndefined()
expect(pgnClocks(tree(), '1. e4 e5 2. Nf3 Nc6 *')).toBeUndefined()
})
})
Loading
Loading