Skip to content
Open
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
273 changes: 273 additions & 0 deletions docs/stories/performance/RenderCounts.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,273 @@
import type { Meta, StoryObj } from '@storybook/react';
import { Chess, SQUARES } from 'chess.js';
import {
Profiler,
useRef,
useState,
type ProfilerOnRenderCallback,
} from 'react';
import { flushSync } from 'react-dom';

import { Chessboard, type ChessboardOptions } from '../../../src/index.js';

const scenarios = {
S1: 'Replay 60 plies',
S2: '100 parent renders with stable options',
S3: '100 parent renders with inline options and callbacks',
S4: '50 square highlight changes',
S5: '10 drags across six squares',
};

type Scenario = keyof typeof scenarios;
type Measurement = { commits: number; actualDuration: number };
type Point = { x: number; y: number };

// Kasparov–Topalov, Wijk aan Zee 1999, the first 30 moves.
const replayPgn = `
1. e4 d6 2. d4 Nf6 3. Nc3 g6 4. Be3 Bg7 5. Qd2 c6 6. f3 b5
7. Nge2 Nbd7 8. Bh6 Bxh6 9. Qxh6 Bb7 10. a3 e5 11. O-O-O Qe7
12. Kb1 a6 13. Nc1 O-O-O 14. Nb3 exd4 15. Rxd4 c5 16. Rd1 Nb6
17. g3 Kb8 18. Na5 Ba8 19. Bh3 d5 20. Qf4+ Ka7 21. Rhe1 d4
22. Nd5 Nbxd5 23. exd5 Qd6 24. Rxd4 cxd4 25. Re7+ Kb6 26. Qxd4+ Kxa5
27. b4+ Ka4 28. Qc3 Qxd5 29. Ra7 Bb7 30. Rxb7 Qc4 *
`.trim();
const dragPath = ['e2', 'e3', 'd3', 'c3', 'c4', 'd4', 'e4'];
const dropPosition =
'rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq - 0 1';

const baseOptions: ChessboardOptions = {
id: 'render-counts',
showAnimations: false,
allowDrawingArrows: false,
clearArrowsOnClick: false,
canDragPiece: () => true,
onPieceClick: () => {},
};

function afterPaint() {
return new Promise<void>((resolve) => {
requestAnimationFrame(() => {
const channel = new MessageChannel();
channel.port1.onmessage = () => {
channel.port1.close();
channel.port2.close();
resolve();
};
channel.port2.postMessage(null);
});
});
}

function dispatchDragEvent(
target: EventTarget,
phase: 'down' | 'move' | 'up',
{ x, y }: Point,
) {
const options = {
bubbles: true,
cancelable: true,
clientX: x,
clientY: y,
button: 0,
buttons: phase === 'up' ? 0 : 1,
};
// Match the browser's event sequence for either dnd-kit mouse activator.
target.dispatchEvent(
new PointerEvent(`pointer${phase}`, {
...options,
pointerId: 1,
pointerType: 'mouse',
isPrimary: true,
}),
);
target.dispatchEvent(new MouseEvent(`mouse${phase}`, options));
}

async function dragAcrossBoard(
board: HTMLElement,
step: (change: () => void) => Promise<void>,
) {
const [source, ...targets] = dragPath.map((square) => {
const cell = board.querySelector(`[data-square="${square}"]`);
if (!cell) throw new Error(`Square ${square} was not found.`);
return cell;
});
const piece = source.querySelector('[data-piece]');
if (!piece) throw new Error('The pawn on e2 was not found.');

function center(element: Element): Point {
const { left, top, width, height } = element.getBoundingClientRect();
return { x: left + width / 2, y: top + height / 2 };
}

const start = center(source);
const points = targets.map(center);
const document = board.ownerDocument;
await step(() => {
dispatchDragEvent(piece, 'down', start);
// The first move past the activation distance starts the drag.
dispatchDragEvent(document, 'move', { x: start.x + 2, y: start.y });
});
for (const point of points) {
await step(() => dispatchDragEvent(document, 'move', point));
}
await step(() =>
dispatchDragEvent(document, 'up', points[points.length - 1]),
);
}

function RenderCountsBenchmark() {
const board = useRef<HTMLDivElement>(null);
const measurement = useRef<Measurement | null>(null);
const [running, setRunning] = useState<Scenario | null>(null);
const [runNumber, setRunNumber] = useState(0);
const [counter, setCounter] = useState(0);
const [options, setOptions] = useState(baseOptions);
const [results, setResults] = useState<
Partial<Record<Scenario, Measurement>>
>({});
const [error, setError] = useState<string | null>(null);

const onRender: ProfilerOnRenderCallback = (_, __, actualDuration) => {
if (measurement.current) {
measurement.current.commits++;
measurement.current.actualDuration += actualDuration;
}
};

async function step(change: () => void) {
if (!board.current) throw new Error('The story was closed.');
change();
await afterPaint();
}

async function run(scenario: Scenario) {
const root = board.current;
if (running || !root) return;

const sample = { commits: 0, actualDuration: 0 };
let didDrop = false;
const dragOptions: ChessboardOptions = {
...baseOptions,
onPieceDrop: ({ sourceSquare, targetSquare }) => {
didDrop = sourceSquare === 'e2' && targetSquare === 'e4';
if (didDrop) setOptions({ ...dragOptions, position: dropPosition });
return didDrop;
},
};

try {
await step(() =>
flushSync(() => {
setRunning(scenario);
setError(null);
setCounter(0);
setRunNumber((previous) => previous + 1);
setOptions(scenario === 'S5' ? dragOptions : baseOptions);
}),
);
root.scrollIntoView({ block: 'nearest' });
measurement.current = sample;

if (scenario === 'S1') {
const chess = new Chess();
chess.loadPgn(replayPgn, { strict: true });
for (const { after: position } of chess.history({ verbose: true })) {
await step(() =>
flushSync(() => setOptions({ ...baseOptions, position })),
);
}
} else if (scenario === 'S2' || scenario === 'S3') {
for (let update = 1; update <= 100; update++) {
await step(() => flushSync(() => setCounter(update)));
}
} else if (scenario === 'S4') {
for (const square of SQUARES.slice(0, 50)) {
await step(() =>
flushSync(() =>
setOptions({
...baseOptions,
squareStyles: {
[square]: { boxShadow: 'inset 0 0 0 4px #646cff' },
},
}),
),
);
}
} else {
for (let repeat = 0; repeat < 10; repeat++) {
didDrop = false;
await dragAcrossBoard(root, step);
if (!didDrop) throw new Error('The pawn did not drop on e4.');

// Exclude the position reset between drags from the profile.
measurement.current = null;
await step(() => flushSync(() => setOptions(dragOptions)));
measurement.current = sample;
}
}
setResults((previous) => ({ ...previous, [scenario]: sample }));
} catch (failure) {
if (board.current) {
setError(`${scenario} failed. ${String(failure)}`);
}
} finally {
measurement.current = null;
if (board.current) setRunning(null);
}
}

const boardOptions =
running === 'S3'
? { ...baseOptions, canDragPiece: () => true, onPieceClick: () => {} }
: options;

return (
<div style={{ maxWidth: 500, margin: '0 auto' }}>
<table>
<thead>
<tr>
<th scope="col">Scenario</th>
<th scope="col">Commits</th>
<th scope="col">Total actual duration (ms)</th>
</tr>
</thead>
<tbody>
{(Object.keys(scenarios) as Scenario[]).map((scenario) => (
<tr key={scenario}>
<th scope="row">
<button
type="button"
onClick={() => void run(scenario)}
disabled={running !== null}
>
{scenario} {scenarios[scenario]}
</button>
</th>
<td>{results[scenario]?.commits ?? '—'}</td>
<td>{results[scenario]?.actualDuration.toFixed(2) ?? '—'}</td>
</tr>
))}
</tbody>
</table>
<p role="status">
{running ? `Running ${running}…` : `Parent updates: ${counter}`}
</p>
{error && <p role="alert">{error}</p>}
<div ref={board}>
<Profiler key={runNumber} id="Chessboard" onRender={onRender}>
<Chessboard options={boardOptions} />
</Profiler>
</div>
</div>
);
}

const meta = {
title: 'stories/Performance/RenderCounts',
component: RenderCountsBenchmark,
} satisfies Meta<typeof RenderCountsBenchmark>;

export default meta;

export const RenderCounts: StoryObj<typeof meta> = {};
15 changes: 9 additions & 6 deletions src/Arrows.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { Fragment } from 'react';
import { Fragment, use } from 'react';

import { useChessboardContext } from './ChessboardProvider.js';
import {
ChessboardLiveContext,
ChessboardSettingsContext,
} from './ChessboardProvider.js';
import { getRelativeCoords } from './utils.js';

export function Arrows() {
Expand All @@ -11,10 +14,10 @@ export function Arrows() {
boardOrientation,
chessboardColumns,
chessboardRows,
internalArrows,
newArrowStartSquare,
newArrowOverSquare,
} = useChessboardContext();
} = use(ChessboardSettingsContext)!.settings;
const { internalArrows, newArrowStartSquare, newArrowOverSquare } = use(
ChessboardLiveContext,
)!;

const viewBoxWidth = 2048;
const viewBoxHeight = viewBoxWidth * (chessboardRows / chessboardColumns);
Expand Down
47 changes: 24 additions & 23 deletions src/Board.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,31 @@
import { DragOverlay } from '@dnd-kit/core';
import { snapCenterToCursor } from '@dnd-kit/modifiers';
import { memo, use } from 'react';

import { Arrows } from './Arrows.js';
import { Draggable } from './Draggable.js';
import { Droppable } from './Droppable.js';
import { Piece } from './Piece.js';
import { Square } from './Square.js';
import { useChessboardContext } from './ChessboardProvider.js';
import {
ChessboardLiveContext,
ChessboardSettingsContext,
ChessboardSquareStylesContext,
} from './ChessboardProvider.js';
import { defaultBoardStyle } from './defaults.js';
import { preventDragOffBoard } from './modifiers.js';

export function Board() {
export const Board = memo(function Board() {
const {
allowDragOffBoard,
board,
boardStyle,
chessboardColumns,
currentPosition,
draggingPiece,
id,
} = useChessboardContext();
squareRenderer,
} = use(ChessboardSettingsContext)!.settings;
const { currentPosition, draggingPiece, positionDifferences } = use(
ChessboardLiveContext,
)!;
const squareStyles = use(ChessboardSquareStylesContext)!;

return (
<>
Expand All @@ -32,21 +38,15 @@ export function Board() {
const piece = currentPosition[square.squareId];

return (
<Droppable key={square.squareId} squareId={square.squareId}>
{({ isOver }) => (
<Square isOver={isOver} {...square}>
{piece ? (
<Draggable
isSparePiece={false}
position={square.squareId}
pieceType={piece.pieceType}
>
<Piece {...piece} position={square.squareId} />
</Draggable>
) : null}
</Square>
)}
</Droppable>
<Droppable
key={square.squareId}
{...square}
customSquareStyle={squareStyles[square.squareId]}
pieceType={piece?.pieceType}
rendererPiece={squareRenderer ? piece : undefined}
ghost={draggingPiece?.position === square.squareId}
moveTo={positionDifferences[square.squareId]}
/>
);
}),
)}
Expand All @@ -68,9 +68,10 @@ export function Board() {
clone
position={draggingPiece.position}
pieceType={draggingPiece.pieceType}
moveTo={positionDifferences[draggingPiece.position]}
/>
) : null}
</DragOverlay>
</>
);
}
});
Loading