react-chess-core 0.1.0 → 0.1.2

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.
Files changed (35) hide show
  1. package/README.md +2 -0
  2. package/dist/features/analysis/core/AnalysisBoardCore.d.ts +8 -2
  3. package/dist/features/chessboard/ChessboardDnDProvider.d.ts +9 -0
  4. package/dist/features/chessboard/boardThemes.d.ts +19 -0
  5. package/dist/features/chessboard/chessboardTheme.d.ts +6 -2
  6. package/dist/features/chessboard/index.d.ts +2 -0
  7. package/dist/features/engine/AnalysisEngineContext.d.ts +22 -0
  8. package/dist/features/engine/index.d.ts +1 -0
  9. package/dist/features/engine/types.d.ts +10 -0
  10. package/dist/features/engine/useAnalysisEngine.d.ts +2 -0
  11. package/dist/features/navigation/PlyNavigation.d.ts +1 -1
  12. package/dist/features/navigation/index.d.ts +2 -0
  13. package/dist/features/navigation/positionKeyboardNav.d.ts +12 -0
  14. package/dist/features/navigation/types.d.ts +5 -0
  15. package/dist/features/navigation/usePositionKeyboardNav.d.ts +12 -0
  16. package/dist/features/training/expectedMoveDrop.d.ts +24 -0
  17. package/dist/features/training/index.d.ts +4 -0
  18. package/dist/features/training/miss/index.d.ts +5 -0
  19. package/dist/features/training/miss/missDisplay.d.ts +16 -0
  20. package/dist/features/training/miss/refutation.d.ts +19 -0
  21. package/dist/features/training/miss/useMissBoard.d.ts +28 -0
  22. package/dist/features/training/miss/useMissRefutation.d.ts +3 -0
  23. package/dist/features/training/miss/useMissSequence.d.ts +10 -0
  24. package/dist/features/training/uciFromDrop.d.ts +3 -0
  25. package/dist/features/training/useBoardRevision.d.ts +9 -0
  26. package/dist/index.d.ts +1 -0
  27. package/dist/index.esm.js +2406 -89
  28. package/dist/index.js +2436 -87
  29. package/dist/stories/AnalysisBoard.stories.d.ts +9 -0
  30. package/dist/stories/analysisFixtures.d.ts +5 -0
  31. package/dist/stories/regressions/StockfishAnalysisRegressions.stories.d.ts +7 -0
  32. package/dist/stories/regressions/fixtures.d.ts +17 -0
  33. package/dist/stories/regressions/regressionAnalysisContext.d.ts +6 -0
  34. package/dist/stories/storybookLayout.d.ts +4 -0
  35. package/package.json +6 -2
package/dist/index.esm.js CHANGED
@@ -1,9 +1,83 @@
1
1
  import { jsx, jsxs } from 'react/jsx-runtime';
2
- import { createContext, useContext, useState, useRef, useEffect, useLayoutEffect, useMemo, Component } from 'react';
3
- import { Chessboard, ChessboardDnDProvider } from 'react-chessboard';
2
+ import { createContext, useContext, useRef, useCallback, useEffect, useMemo, useState, useLayoutEffect, Component } from 'react';
3
+ import { ChessboardDnDProvider as ChessboardDnDProvider$1, Chessboard } from 'react-chessboard';
4
4
  import { Chess } from 'chess.js';
5
5
  import { createPortal } from 'react-dom';
6
6
 
7
+ const BOARD_THEME_IDS = [
8
+ 'classic',
9
+ 'forest',
10
+ 'marine',
11
+ 'marble',
12
+ 'ivory',
13
+ 'ocean',
14
+ 'copper',
15
+ 'bubblegum',
16
+ 'sunset',
17
+ ];
18
+ const DEFAULT_BOARD_THEME = 'classic';
19
+ const BOARD_THEMES = {
20
+ classic: {
21
+ label: 'Classic',
22
+ darkSquare: '#b58863',
23
+ lightSquare: '#f0d9b5',
24
+ },
25
+ forest: {
26
+ label: 'Forest',
27
+ darkSquare: '#769656',
28
+ lightSquare: '#eeeed2',
29
+ },
30
+ marine: {
31
+ label: 'Marine',
32
+ darkSquare: '#5b7c99',
33
+ lightSquare: '#d6e4f0',
34
+ },
35
+ marble: {
36
+ label: 'Marble',
37
+ darkSquare: '#a8a8a8',
38
+ lightSquare: '#ffffff',
39
+ },
40
+ ivory: {
41
+ label: 'Ivory',
42
+ darkSquare: '#c9a66b',
43
+ lightSquare: '#fff8e7',
44
+ },
45
+ ocean: {
46
+ label: 'Ocean',
47
+ darkSquare: '#2d6a7e',
48
+ lightSquare: '#a8dadc',
49
+ },
50
+ copper: {
51
+ label: 'Copper',
52
+ darkSquare: '#9c6644',
53
+ lightSquare: '#f4e4d4',
54
+ },
55
+ bubblegum: {
56
+ label: 'Bubblegum',
57
+ darkSquare: '#c77dff',
58
+ lightSquare: '#ffd6ff',
59
+ },
60
+ sunset: {
61
+ label: 'Sunset',
62
+ darkSquare: '#e76f51',
63
+ lightSquare: '#ffe8d6',
64
+ },
65
+ };
66
+ function isBoardThemeId(value) {
67
+ return (typeof value === 'string' &&
68
+ BOARD_THEME_IDS.includes(value));
69
+ }
70
+ function boardThemeFromLegacyUiTheme(_theme) {
71
+ return DEFAULT_BOARD_THEME;
72
+ }
73
+ function getBoardThemeStyles(boardTheme) {
74
+ const { darkSquare, lightSquare } = BOARD_THEMES[boardTheme];
75
+ return {
76
+ customDarkSquareStyle: { backgroundColor: darkSquare },
77
+ customLightSquareStyle: { backgroundColor: lightSquare },
78
+ };
79
+ }
80
+
7
81
  const ChessboardThemeContext = createContext(undefined);
8
82
  const useChessboardTheme = () => {
9
83
  const context = useContext(ChessboardThemeContext);
@@ -14,23 +88,1607 @@ const useChessboardTheme = () => {
14
88
  };
15
89
  /** @deprecated Use {@link useChessboardTheme}. */
16
90
  const useTheme = useChessboardTheme;
17
- const getStylesForTheme = (theme) => {
18
- if (theme === 'dark') {
91
+ /** @deprecated Use {@link getBoardThemeStyles}. */
92
+ const getStylesForTheme = (theme) => getBoardThemeStyles(boardThemeFromLegacyUiTheme());
93
+ const ThemeProvider = ({ children, theme = 'dark', boardTheme, }) => {
94
+ const resolvedBoardTheme = boardTheme !== null && boardTheme !== void 0 ? boardTheme : boardThemeFromLegacyUiTheme();
95
+ const { customDarkSquareStyle, customLightSquareStyle } = getBoardThemeStyles(resolvedBoardTheme);
96
+ return (jsx(ChessboardThemeContext.Provider, { value: { customDarkSquareStyle, customLightSquareStyle }, children: children }));
97
+ };
98
+
99
+ var E=r=>{throw TypeError(r)};var P=(r,n,e)=>n.has(r)||E("Cannot "+e);var t=(r,n,e)=>(P(r,n,"read from private field"),e?e.call(r):n.get(r)),s=(r,n,e)=>n.has(r)?E("Cannot add the same private member more than once"):n instanceof WeakSet?n.add(r):n.set(r,e),p=(r,n,e,i)=>(P(r,n,"write to private field"),n.set(r,e),e);var h,B=class{constructor(){s(this,h);this.register=n=>{t(this,h).push(n);};this.unregister=n=>{for(;t(this,h).indexOf(n)!==-1;)t(this,h).splice(t(this,h).indexOf(n),1);};this.backendChanged=n=>{for(let e of t(this,h))e.backendChanged(n);};p(this,h,[]);}};h=new WeakMap;var c$1,l,a,d,k,x,T,D,m,v,f,w=class w{constructor(n,e,i){s(this,c$1);s(this,l);s(this,a);s(this,d);s(this,k);s(this,x,(n,e,i)=>{if(!i.backend)throw new Error(`You must specify a 'backend' property in your Backend entry: ${JSON.stringify(i)}`);let u=i.backend(n,e,i.options),o=i.id,g=!i.id&&u&&u.constructor;if(g&&(o=u.constructor.name),!o)throw new Error(`You must specify an 'id' property in your Backend entry: ${JSON.stringify(i)}
100
+ see this guide: https://github.com/louisbrunner/dnd-multi-backend/tree/master/packages/react-dnd-multi-backend#migrating-from-5xx`);if(g&&console.warn(`Deprecation notice: You are using a pipeline which doesn't include backends' 'id'.
101
+ This might be unsupported in the future, please specify 'id' explicitely for every backend.`),t(this,a)[o])throw new Error(`You must specify a unique 'id' property in your Backend entry:
102
+ ${JSON.stringify(i)} (conflicts with: ${JSON.stringify(t(this,a)[o])})`);return {id:o,instance:u,preview:i.preview??false,transition:i.transition,skipDispatchOnTransition:i.skipDispatchOnTransition??false}});this.setup=()=>{if(!(typeof window>"u")){if(w.isSetUp)throw new Error("Cannot have two MultiBackends at the same time.");w.isSetUp=true,t(this,T).call(this,window),t(this,a)[t(this,c$1)].instance.setup();}};this.teardown=()=>{typeof window>"u"||(w.isSetUp=false,t(this,D).call(this,window),t(this,a)[t(this,c$1)].instance.teardown());};this.connectDragSource=(n,e,i)=>t(this,f).call(this,"connectDragSource",n,e,i);this.connectDragPreview=(n,e,i)=>t(this,f).call(this,"connectDragPreview",n,e,i);this.connectDropTarget=(n,e,i)=>t(this,f).call(this,"connectDropTarget",n,e,i);this.profile=()=>t(this,a)[t(this,c$1)].instance.profile();this.previewEnabled=()=>t(this,a)[t(this,c$1)].preview;this.previewsList=()=>t(this,l);this.backendsList=()=>t(this,d);s(this,T,n=>{for(let e of t(this,d))e.transition&&n.addEventListener(e.transition.event,t(this,m));});s(this,D,n=>{for(let e of t(this,d))e.transition&&n.removeEventListener(e.transition.event,t(this,m));});s(this,m,n=>{let e=t(this,c$1);if(t(this,d).some(i=>i.id!==t(this,c$1)&&i.transition&&i.transition.check(n)?(p(this,c$1,i.id),true):false),t(this,c$1)!==e){t(this,a)[e].instance.teardown();for(let[g,b]of Object.entries(t(this,k)))b.unsubscribe(),b.unsubscribe=t(this,v).call(this,b.func,...b.args);t(this,l).backendChanged(this);let i=t(this,a)[t(this,c$1)];if(i.instance.setup(),i.skipDispatchOnTransition)return;let u=n.constructor,o=new u(n.type,n);n.target?.dispatchEvent(o);}});s(this,v,(n,e,i,u)=>t(this,a)[t(this,c$1)].instance[n](e,i,u));s(this,f,(n,e,i,u)=>{let o=`${n}_${e}`,g=t(this,v).call(this,n,e,i,u);return t(this,k)[o]={func:n,args:[e,i,u],unsubscribe:g},()=>{t(this,k)[o].unsubscribe(),delete t(this,k)[o];}});if(!i||!i.backends||i.backends.length<1)throw new Error(`You must specify at least one Backend, if you are coming from 2.x.x (or don't understand this error)
103
+ see this guide: https://github.com/louisbrunner/dnd-multi-backend/tree/master/packages/react-dnd-multi-backend#migrating-from-2xx`);p(this,l,new B),p(this,a,{}),p(this,d,[]);for(let u of i.backends){let o=t(this,x).call(this,n,e,u);t(this,a)[o.id]=o,t(this,d).push(o);}p(this,c$1,t(this,d)[0].id),p(this,k,{});}};c$1=new WeakMap,l=new WeakMap,a=new WeakMap,d=new WeakMap,k=new WeakMap,x=new WeakMap,T=new WeakMap,D=new WeakMap,m=new WeakMap,v=new WeakMap,f=new WeakMap,w.isSetUp=false;var M=w;var S=(r,n,e)=>new M(r,n,e);var y=(r,n)=>({event:r,check:n});var L=y("touchstart",r=>{let n=r;return n.touches!==null&&n.touches!==void 0}),U=y("pointerdown",r=>r.pointerType==="mouse");
104
+
105
+ /**
106
+ * Use invariant() to assert state which your program assumes to be true.
107
+ *
108
+ * Provide sprintf-style format (only %s is supported) and arguments
109
+ * to provide information about what broke and what you were
110
+ * expecting.
111
+ *
112
+ * The invariant message will be stripped in production, but the invariant
113
+ * will remain to ensure logic does not differ in production.
114
+ */ function invariant(condition, format, ...args) {
115
+ if (isProduction()) ;
116
+ if (!condition) {
117
+ let error;
118
+ {
119
+ let argIndex = 0;
120
+ error = new Error(format.replace(/%s/g, function() {
121
+ return args[argIndex++];
122
+ }));
123
+ error.name = 'Invariant Violation';
124
+ }
125
+ error.framesToPop = 1 // we don't care about invariant's own frame
126
+ ;
127
+ throw error;
128
+ }
129
+ }
130
+ function isProduction() {
131
+ return typeof process !== 'undefined' && process.env['NODE_ENV'] === 'production';
132
+ }
133
+
134
+ // cheap lodash replacements
135
+ function memoize(fn) {
136
+ let result = null;
137
+ const memoized = ()=>{
138
+ if (result == null) {
139
+ result = fn();
140
+ }
141
+ return result;
142
+ };
143
+ return memoized;
144
+ }
145
+ /**
146
+ * drop-in replacement for _.without
147
+ */ function without(items, item) {
148
+ return items.filter((i)=>i !== item
149
+ );
150
+ }
151
+ function union(itemsA, itemsB) {
152
+ const set = new Set();
153
+ const insertItem = (item)=>set.add(item)
154
+ ;
155
+ itemsA.forEach(insertItem);
156
+ itemsB.forEach(insertItem);
157
+ const result = [];
158
+ set.forEach((key)=>result.push(key)
159
+ );
160
+ return result;
161
+ }
162
+
163
+ class EnterLeaveCounter {
164
+ enter(enteringNode) {
165
+ const previousLength = this.entered.length;
166
+ const isNodeEntered = (node)=>this.isNodeInDocument(node) && (!node.contains || node.contains(enteringNode))
167
+ ;
168
+ this.entered = union(this.entered.filter(isNodeEntered), [
169
+ enteringNode
170
+ ]);
171
+ return previousLength === 0 && this.entered.length > 0;
172
+ }
173
+ leave(leavingNode) {
174
+ const previousLength = this.entered.length;
175
+ this.entered = without(this.entered.filter(this.isNodeInDocument), leavingNode);
176
+ return previousLength > 0 && this.entered.length === 0;
177
+ }
178
+ reset() {
179
+ this.entered = [];
180
+ }
181
+ constructor(isNodeInDocument){
182
+ this.entered = [];
183
+ this.isNodeInDocument = isNodeInDocument;
184
+ }
185
+ }
186
+
187
+ class NativeDragSource {
188
+ initializeExposedProperties() {
189
+ Object.keys(this.config.exposeProperties).forEach((property)=>{
190
+ Object.defineProperty(this.item, property, {
191
+ configurable: true,
192
+ enumerable: true,
193
+ get () {
194
+ // eslint-disable-next-line no-console
195
+ console.warn(`Browser doesn't allow reading "${property}" until the drop event.`);
196
+ return null;
197
+ }
198
+ });
199
+ });
200
+ }
201
+ loadDataTransfer(dataTransfer) {
202
+ if (dataTransfer) {
203
+ const newProperties = {};
204
+ Object.keys(this.config.exposeProperties).forEach((property)=>{
205
+ const propertyFn = this.config.exposeProperties[property];
206
+ if (propertyFn != null) {
207
+ newProperties[property] = {
208
+ value: propertyFn(dataTransfer, this.config.matchesTypes),
209
+ configurable: true,
210
+ enumerable: true
211
+ };
212
+ }
213
+ });
214
+ Object.defineProperties(this.item, newProperties);
215
+ }
216
+ }
217
+ canDrag() {
218
+ return true;
219
+ }
220
+ beginDrag() {
221
+ return this.item;
222
+ }
223
+ isDragging(monitor, handle) {
224
+ return handle === monitor.getSourceId();
225
+ }
226
+ endDrag() {
227
+ // empty
228
+ }
229
+ constructor(config){
230
+ this.config = config;
231
+ this.item = {};
232
+ this.initializeExposedProperties();
233
+ }
234
+ }
235
+
236
+ const FILE = '__NATIVE_FILE__';
237
+ const URL$1 = '__NATIVE_URL__';
238
+ const TEXT = '__NATIVE_TEXT__';
239
+ const HTML = '__NATIVE_HTML__';
240
+
241
+ var NativeTypes = /*#__PURE__*/Object.freeze({
242
+ __proto__: null,
243
+ FILE: FILE,
244
+ HTML: HTML,
245
+ TEXT: TEXT,
246
+ URL: URL$1
247
+ });
248
+
249
+ function getDataFromDataTransfer(dataTransfer, typesToTry, defaultValue) {
250
+ const result = typesToTry.reduce((resultSoFar, typeToTry)=>resultSoFar || dataTransfer.getData(typeToTry)
251
+ , '');
252
+ return result != null ? result : defaultValue;
253
+ }
254
+
255
+ const nativeTypesConfig = {
256
+ [FILE]: {
257
+ exposeProperties: {
258
+ files: (dataTransfer)=>Array.prototype.slice.call(dataTransfer.files)
259
+ ,
260
+ items: (dataTransfer)=>dataTransfer.items
261
+ ,
262
+ dataTransfer: (dataTransfer)=>dataTransfer
263
+ },
264
+ matchesTypes: [
265
+ 'Files'
266
+ ]
267
+ },
268
+ [HTML]: {
269
+ exposeProperties: {
270
+ html: (dataTransfer, matchesTypes)=>getDataFromDataTransfer(dataTransfer, matchesTypes, '')
271
+ ,
272
+ dataTransfer: (dataTransfer)=>dataTransfer
273
+ },
274
+ matchesTypes: [
275
+ 'Html',
276
+ 'text/html'
277
+ ]
278
+ },
279
+ [URL$1]: {
280
+ exposeProperties: {
281
+ urls: (dataTransfer, matchesTypes)=>getDataFromDataTransfer(dataTransfer, matchesTypes, '').split('\n')
282
+ ,
283
+ dataTransfer: (dataTransfer)=>dataTransfer
284
+ },
285
+ matchesTypes: [
286
+ 'Url',
287
+ 'text/uri-list'
288
+ ]
289
+ },
290
+ [TEXT]: {
291
+ exposeProperties: {
292
+ text: (dataTransfer, matchesTypes)=>getDataFromDataTransfer(dataTransfer, matchesTypes, '')
293
+ ,
294
+ dataTransfer: (dataTransfer)=>dataTransfer
295
+ },
296
+ matchesTypes: [
297
+ 'Text',
298
+ 'text/plain'
299
+ ]
300
+ }
301
+ };
302
+
303
+ function createNativeDragSource(type, dataTransfer) {
304
+ const config = nativeTypesConfig[type];
305
+ if (!config) {
306
+ throw new Error(`native type ${type} has no configuration`);
307
+ }
308
+ const result = new NativeDragSource(config);
309
+ result.loadDataTransfer(dataTransfer);
310
+ return result;
311
+ }
312
+ function matchNativeItemType(dataTransfer) {
313
+ if (!dataTransfer) {
314
+ return null;
315
+ }
316
+ const dataTransferTypes = Array.prototype.slice.call(dataTransfer.types || []);
317
+ return Object.keys(nativeTypesConfig).filter((nativeItemType)=>{
318
+ const typeConfig = nativeTypesConfig[nativeItemType];
319
+ if (!(typeConfig === null || typeConfig === void 0 ? void 0 : typeConfig.matchesTypes)) {
320
+ return false;
321
+ }
322
+ return typeConfig.matchesTypes.some((t)=>dataTransferTypes.indexOf(t) > -1
323
+ );
324
+ })[0] || null;
325
+ }
326
+
327
+ const isFirefox = memoize(()=>/firefox/i.test(navigator.userAgent)
328
+ );
329
+ const isSafari = memoize(()=>Boolean(window.safari)
330
+ );
331
+
332
+ class MonotonicInterpolant {
333
+ interpolate(x) {
334
+ const { xs , ys , c1s , c2s , c3s } = this;
335
+ // The rightmost point in the dataset should give an exact result
336
+ let i = xs.length - 1;
337
+ if (x === xs[i]) {
338
+ return ys[i];
339
+ }
340
+ // Search for the interval x is in, returning the corresponding y if x is one of the original xs
341
+ let low = 0;
342
+ let high = c3s.length - 1;
343
+ let mid;
344
+ while(low <= high){
345
+ mid = Math.floor(0.5 * (low + high));
346
+ const xHere = xs[mid];
347
+ if (xHere < x) {
348
+ low = mid + 1;
349
+ } else if (xHere > x) {
350
+ high = mid - 1;
351
+ } else {
352
+ return ys[mid];
353
+ }
354
+ }
355
+ i = Math.max(0, high);
356
+ // Interpolate
357
+ const diff = x - xs[i];
358
+ const diffSq = diff * diff;
359
+ return ys[i] + c1s[i] * diff + c2s[i] * diffSq + c3s[i] * diff * diffSq;
360
+ }
361
+ constructor(xs, ys){
362
+ const { length } = xs;
363
+ // Rearrange xs and ys so that xs is sorted
364
+ const indexes = [];
365
+ for(let i = 0; i < length; i++){
366
+ indexes.push(i);
367
+ }
368
+ indexes.sort((a, b)=>xs[a] < xs[b] ? -1 : 1
369
+ );
370
+ const dxs = [];
371
+ const ms = [];
372
+ let dx;
373
+ let dy;
374
+ for(let i1 = 0; i1 < length - 1; i1++){
375
+ dx = xs[i1 + 1] - xs[i1];
376
+ dy = ys[i1 + 1] - ys[i1];
377
+ dxs.push(dx);
378
+ ms.push(dy / dx);
379
+ }
380
+ // Get degree-1 coefficients
381
+ const c1s = [
382
+ ms[0]
383
+ ];
384
+ for(let i2 = 0; i2 < dxs.length - 1; i2++){
385
+ const m2 = ms[i2];
386
+ const mNext = ms[i2 + 1];
387
+ if (m2 * mNext <= 0) {
388
+ c1s.push(0);
389
+ } else {
390
+ dx = dxs[i2];
391
+ const dxNext = dxs[i2 + 1];
392
+ const common = dx + dxNext;
393
+ c1s.push(3 * common / ((common + dxNext) / m2 + (common + dx) / mNext));
394
+ }
395
+ }
396
+ c1s.push(ms[ms.length - 1]);
397
+ // Get degree-2 and degree-3 coefficients
398
+ const c2s = [];
399
+ const c3s = [];
400
+ let m;
401
+ for(let i3 = 0; i3 < c1s.length - 1; i3++){
402
+ m = ms[i3];
403
+ const c1 = c1s[i3];
404
+ const invDx = 1 / dxs[i3];
405
+ const common = c1 + c1s[i3 + 1] - m - m;
406
+ c2s.push((m - c1 - common) * invDx);
407
+ c3s.push(common * invDx * invDx);
408
+ }
409
+ this.xs = xs;
410
+ this.ys = ys;
411
+ this.c1s = c1s;
412
+ this.c2s = c2s;
413
+ this.c3s = c3s;
414
+ }
415
+ }
416
+
417
+ const ELEMENT_NODE$1 = 1;
418
+ function getNodeClientOffset$1(node) {
419
+ const el = node.nodeType === ELEMENT_NODE$1 ? node : node.parentElement;
420
+ if (!el) {
421
+ return null;
422
+ }
423
+ const { top , left } = el.getBoundingClientRect();
424
+ return {
425
+ x: left,
426
+ y: top
427
+ };
428
+ }
429
+ function getEventClientOffset$1(e) {
430
+ return {
431
+ x: e.clientX,
432
+ y: e.clientY
433
+ };
434
+ }
435
+ function isImageNode(node) {
436
+ var ref;
437
+ return node.nodeName === 'IMG' && (isFirefox() || !((ref = document.documentElement) === null || ref === void 0 ? void 0 : ref.contains(node)));
438
+ }
439
+ function getDragPreviewSize(isImage, dragPreview, sourceWidth, sourceHeight) {
440
+ let dragPreviewWidth = isImage ? dragPreview.width : sourceWidth;
441
+ let dragPreviewHeight = isImage ? dragPreview.height : sourceHeight;
442
+ // Work around @2x coordinate discrepancies in browsers
443
+ if (isSafari() && isImage) {
444
+ dragPreviewHeight /= window.devicePixelRatio;
445
+ dragPreviewWidth /= window.devicePixelRatio;
446
+ }
447
+ return {
448
+ dragPreviewWidth,
449
+ dragPreviewHeight
450
+ };
451
+ }
452
+ function getDragPreviewOffset(sourceNode, dragPreview, clientOffset, anchorPoint, offsetPoint) {
453
+ // The browsers will use the image intrinsic size under different conditions.
454
+ // Firefox only cares if it's an image, but WebKit also wants it to be detached.
455
+ const isImage = isImageNode(dragPreview);
456
+ const dragPreviewNode = isImage ? sourceNode : dragPreview;
457
+ const dragPreviewNodeOffsetFromClient = getNodeClientOffset$1(dragPreviewNode);
458
+ const offsetFromDragPreview = {
459
+ x: clientOffset.x - dragPreviewNodeOffsetFromClient.x,
460
+ y: clientOffset.y - dragPreviewNodeOffsetFromClient.y
461
+ };
462
+ const { offsetWidth: sourceWidth , offsetHeight: sourceHeight } = sourceNode;
463
+ const { anchorX , anchorY } = anchorPoint;
464
+ const { dragPreviewWidth , dragPreviewHeight } = getDragPreviewSize(isImage, dragPreview, sourceWidth, sourceHeight);
465
+ const calculateYOffset = ()=>{
466
+ const interpolantY = new MonotonicInterpolant([
467
+ 0,
468
+ 0.5,
469
+ 1
470
+ ], [
471
+ // Dock to the top
472
+ offsetFromDragPreview.y,
473
+ // Align at the center
474
+ (offsetFromDragPreview.y / sourceHeight) * dragPreviewHeight,
475
+ // Dock to the bottom
476
+ offsetFromDragPreview.y + dragPreviewHeight - sourceHeight,
477
+ ]);
478
+ let y = interpolantY.interpolate(anchorY);
479
+ // Work around Safari 8 positioning bug
480
+ if (isSafari() && isImage) {
481
+ // We'll have to wait for @3x to see if this is entirely correct
482
+ y += (window.devicePixelRatio - 1) * dragPreviewHeight;
483
+ }
484
+ return y;
485
+ };
486
+ const calculateXOffset = ()=>{
487
+ // Interpolate coordinates depending on anchor point
488
+ // If you know a simpler way to do this, let me know
489
+ const interpolantX = new MonotonicInterpolant([
490
+ 0,
491
+ 0.5,
492
+ 1
493
+ ], [
494
+ // Dock to the left
495
+ offsetFromDragPreview.x,
496
+ // Align at the center
497
+ (offsetFromDragPreview.x / sourceWidth) * dragPreviewWidth,
498
+ // Dock to the right
499
+ offsetFromDragPreview.x + dragPreviewWidth - sourceWidth,
500
+ ]);
501
+ return interpolantX.interpolate(anchorX);
502
+ };
503
+ // Force offsets if specified in the options.
504
+ const { offsetX , offsetY } = offsetPoint;
505
+ const isManualOffsetX = offsetX === 0 || offsetX;
506
+ const isManualOffsetY = offsetY === 0 || offsetY;
507
+ return {
508
+ x: isManualOffsetX ? offsetX : calculateXOffset(),
509
+ y: isManualOffsetY ? offsetY : calculateYOffset()
510
+ };
511
+ }
512
+
513
+ let OptionsReader$1 = class OptionsReader {
514
+ get window() {
515
+ if (this.globalContext) {
516
+ return this.globalContext;
517
+ } else if (typeof window !== 'undefined') {
518
+ return window;
519
+ }
520
+ return undefined;
521
+ }
522
+ get document() {
523
+ var ref;
524
+ if ((ref = this.globalContext) === null || ref === void 0 ? void 0 : ref.document) {
525
+ return this.globalContext.document;
526
+ } else if (this.window) {
527
+ return this.window.document;
528
+ } else {
529
+ return undefined;
530
+ }
531
+ }
532
+ get rootElement() {
533
+ var ref;
534
+ return ((ref = this.optionsArgs) === null || ref === void 0 ? void 0 : ref.rootElement) || this.window;
535
+ }
536
+ constructor(globalContext, options){
537
+ this.ownerDocument = null;
538
+ this.globalContext = globalContext;
539
+ this.optionsArgs = options;
540
+ }
541
+ };
542
+
543
+ function _defineProperty(obj, key, value) {
544
+ if (key in obj) {
545
+ Object.defineProperty(obj, key, {
546
+ value: value,
547
+ enumerable: true,
548
+ configurable: true,
549
+ writable: true
550
+ });
551
+ } else {
552
+ obj[key] = value;
553
+ }
554
+ return obj;
555
+ }
556
+ function _objectSpread(target) {
557
+ for(var i = 1; i < arguments.length; i++){
558
+ var source = arguments[i] != null ? arguments[i] : {};
559
+ var ownKeys = Object.keys(source);
560
+ if (typeof Object.getOwnPropertySymbols === 'function') {
561
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
562
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
563
+ }));
564
+ }
565
+ ownKeys.forEach(function(key) {
566
+ _defineProperty(target, key, source[key]);
567
+ });
568
+ }
569
+ return target;
570
+ }
571
+ class HTML5BackendImpl {
572
+ /**
573
+ * Generate profiling statistics for the HTML5Backend.
574
+ */ profile() {
575
+ var ref, ref1;
19
576
  return {
20
- customDarkSquareStyle: { backgroundColor: '#838387' },
21
- customLightSquareStyle: { backgroundColor: '#e1e1e3' },
577
+ sourcePreviewNodes: this.sourcePreviewNodes.size,
578
+ sourcePreviewNodeOptions: this.sourcePreviewNodeOptions.size,
579
+ sourceNodeOptions: this.sourceNodeOptions.size,
580
+ sourceNodes: this.sourceNodes.size,
581
+ dragStartSourceIds: ((ref = this.dragStartSourceIds) === null || ref === void 0 ? void 0 : ref.length) || 0,
582
+ dropTargetIds: this.dropTargetIds.length,
583
+ dragEnterTargetIds: this.dragEnterTargetIds.length,
584
+ dragOverTargetIds: ((ref1 = this.dragOverTargetIds) === null || ref1 === void 0 ? void 0 : ref1.length) || 0
585
+ };
586
+ }
587
+ // public for test
588
+ get window() {
589
+ return this.options.window;
590
+ }
591
+ get document() {
592
+ return this.options.document;
593
+ }
594
+ /**
595
+ * Get the root element to use for event subscriptions
596
+ */ get rootElement() {
597
+ return this.options.rootElement;
598
+ }
599
+ setup() {
600
+ const root = this.rootElement;
601
+ if (root === undefined) {
602
+ return;
603
+ }
604
+ if (root.__isReactDndBackendSetUp) {
605
+ throw new Error('Cannot have two HTML5 backends at the same time.');
606
+ }
607
+ root.__isReactDndBackendSetUp = true;
608
+ this.addEventListeners(root);
609
+ }
610
+ teardown() {
611
+ const root = this.rootElement;
612
+ if (root === undefined) {
613
+ return;
614
+ }
615
+ root.__isReactDndBackendSetUp = false;
616
+ this.removeEventListeners(this.rootElement);
617
+ this.clearCurrentDragSourceNode();
618
+ if (this.asyncEndDragFrameId) {
619
+ var ref;
620
+ (ref = this.window) === null || ref === void 0 ? void 0 : ref.cancelAnimationFrame(this.asyncEndDragFrameId);
621
+ }
622
+ }
623
+ connectDragPreview(sourceId, node, options) {
624
+ this.sourcePreviewNodeOptions.set(sourceId, options);
625
+ this.sourcePreviewNodes.set(sourceId, node);
626
+ return ()=>{
627
+ this.sourcePreviewNodes.delete(sourceId);
628
+ this.sourcePreviewNodeOptions.delete(sourceId);
629
+ };
630
+ }
631
+ connectDragSource(sourceId, node, options) {
632
+ this.sourceNodes.set(sourceId, node);
633
+ this.sourceNodeOptions.set(sourceId, options);
634
+ const handleDragStart = (e)=>this.handleDragStart(e, sourceId)
635
+ ;
636
+ const handleSelectStart = (e)=>this.handleSelectStart(e)
637
+ ;
638
+ node.setAttribute('draggable', 'true');
639
+ node.addEventListener('dragstart', handleDragStart);
640
+ node.addEventListener('selectstart', handleSelectStart);
641
+ return ()=>{
642
+ this.sourceNodes.delete(sourceId);
643
+ this.sourceNodeOptions.delete(sourceId);
644
+ node.removeEventListener('dragstart', handleDragStart);
645
+ node.removeEventListener('selectstart', handleSelectStart);
646
+ node.setAttribute('draggable', 'false');
647
+ };
648
+ }
649
+ connectDropTarget(targetId, node) {
650
+ const handleDragEnter = (e)=>this.handleDragEnter(e, targetId)
651
+ ;
652
+ const handleDragOver = (e)=>this.handleDragOver(e, targetId)
653
+ ;
654
+ const handleDrop = (e)=>this.handleDrop(e, targetId)
655
+ ;
656
+ node.addEventListener('dragenter', handleDragEnter);
657
+ node.addEventListener('dragover', handleDragOver);
658
+ node.addEventListener('drop', handleDrop);
659
+ return ()=>{
660
+ node.removeEventListener('dragenter', handleDragEnter);
661
+ node.removeEventListener('dragover', handleDragOver);
662
+ node.removeEventListener('drop', handleDrop);
663
+ };
664
+ }
665
+ addEventListeners(target) {
666
+ // SSR Fix (https://github.com/react-dnd/react-dnd/pull/813
667
+ if (!target.addEventListener) {
668
+ return;
669
+ }
670
+ target.addEventListener('dragstart', this.handleTopDragStart);
671
+ target.addEventListener('dragstart', this.handleTopDragStartCapture, true);
672
+ target.addEventListener('dragend', this.handleTopDragEndCapture, true);
673
+ target.addEventListener('dragenter', this.handleTopDragEnter);
674
+ target.addEventListener('dragenter', this.handleTopDragEnterCapture, true);
675
+ target.addEventListener('dragleave', this.handleTopDragLeaveCapture, true);
676
+ target.addEventListener('dragover', this.handleTopDragOver);
677
+ target.addEventListener('dragover', this.handleTopDragOverCapture, true);
678
+ target.addEventListener('drop', this.handleTopDrop);
679
+ target.addEventListener('drop', this.handleTopDropCapture, true);
680
+ }
681
+ removeEventListeners(target) {
682
+ // SSR Fix (https://github.com/react-dnd/react-dnd/pull/813
683
+ if (!target.removeEventListener) {
684
+ return;
685
+ }
686
+ target.removeEventListener('dragstart', this.handleTopDragStart);
687
+ target.removeEventListener('dragstart', this.handleTopDragStartCapture, true);
688
+ target.removeEventListener('dragend', this.handleTopDragEndCapture, true);
689
+ target.removeEventListener('dragenter', this.handleTopDragEnter);
690
+ target.removeEventListener('dragenter', this.handleTopDragEnterCapture, true);
691
+ target.removeEventListener('dragleave', this.handleTopDragLeaveCapture, true);
692
+ target.removeEventListener('dragover', this.handleTopDragOver);
693
+ target.removeEventListener('dragover', this.handleTopDragOverCapture, true);
694
+ target.removeEventListener('drop', this.handleTopDrop);
695
+ target.removeEventListener('drop', this.handleTopDropCapture, true);
696
+ }
697
+ getCurrentSourceNodeOptions() {
698
+ const sourceId = this.monitor.getSourceId();
699
+ const sourceNodeOptions = this.sourceNodeOptions.get(sourceId);
700
+ return _objectSpread({
701
+ dropEffect: this.altKeyPressed ? 'copy' : 'move'
702
+ }, sourceNodeOptions || {});
703
+ }
704
+ getCurrentDropEffect() {
705
+ if (this.isDraggingNativeItem()) {
706
+ // It makes more sense to default to 'copy' for native resources
707
+ return 'copy';
708
+ }
709
+ return this.getCurrentSourceNodeOptions().dropEffect;
710
+ }
711
+ getCurrentSourcePreviewNodeOptions() {
712
+ const sourceId = this.monitor.getSourceId();
713
+ const sourcePreviewNodeOptions = this.sourcePreviewNodeOptions.get(sourceId);
714
+ return _objectSpread({
715
+ anchorX: 0.5,
716
+ anchorY: 0.5,
717
+ captureDraggingState: false
718
+ }, sourcePreviewNodeOptions || {});
719
+ }
720
+ isDraggingNativeItem() {
721
+ const itemType = this.monitor.getItemType();
722
+ return Object.keys(NativeTypes).some((key)=>NativeTypes[key] === itemType
723
+ );
724
+ }
725
+ beginDragNativeItem(type, dataTransfer) {
726
+ this.clearCurrentDragSourceNode();
727
+ this.currentNativeSource = createNativeDragSource(type, dataTransfer);
728
+ this.currentNativeHandle = this.registry.addSource(type, this.currentNativeSource);
729
+ this.actions.beginDrag([
730
+ this.currentNativeHandle
731
+ ]);
732
+ }
733
+ setCurrentDragSourceNode(node) {
734
+ this.clearCurrentDragSourceNode();
735
+ this.currentDragSourceNode = node;
736
+ // A timeout of > 0 is necessary to resolve Firefox issue referenced
737
+ // See:
738
+ // * https://github.com/react-dnd/react-dnd/pull/928
739
+ // * https://github.com/react-dnd/react-dnd/issues/869
740
+ const MOUSE_MOVE_TIMEOUT = 1000;
741
+ // Receiving a mouse event in the middle of a dragging operation
742
+ // means it has ended and the drag source node disappeared from DOM,
743
+ // so the browser didn't dispatch the dragend event.
744
+ //
745
+ // We need to wait before we start listening for mousemove events.
746
+ // This is needed because the drag preview needs to be drawn or else it fires an 'mousemove' event
747
+ // immediately in some browsers.
748
+ //
749
+ // See:
750
+ // * https://github.com/react-dnd/react-dnd/pull/928
751
+ // * https://github.com/react-dnd/react-dnd/issues/869
752
+ //
753
+ this.mouseMoveTimeoutTimer = setTimeout(()=>{
754
+ var ref;
755
+ return (ref = this.rootElement) === null || ref === void 0 ? void 0 : ref.addEventListener('mousemove', this.endDragIfSourceWasRemovedFromDOM, true);
756
+ }, MOUSE_MOVE_TIMEOUT);
757
+ }
758
+ clearCurrentDragSourceNode() {
759
+ if (this.currentDragSourceNode) {
760
+ this.currentDragSourceNode = null;
761
+ if (this.rootElement) {
762
+ var ref;
763
+ (ref = this.window) === null || ref === void 0 ? void 0 : ref.clearTimeout(this.mouseMoveTimeoutTimer || undefined);
764
+ this.rootElement.removeEventListener('mousemove', this.endDragIfSourceWasRemovedFromDOM, true);
765
+ }
766
+ this.mouseMoveTimeoutTimer = null;
767
+ return true;
768
+ }
769
+ return false;
770
+ }
771
+ handleDragStart(e, sourceId) {
772
+ if (e.defaultPrevented) {
773
+ return;
774
+ }
775
+ if (!this.dragStartSourceIds) {
776
+ this.dragStartSourceIds = [];
777
+ }
778
+ this.dragStartSourceIds.unshift(sourceId);
779
+ }
780
+ handleDragEnter(_e, targetId) {
781
+ this.dragEnterTargetIds.unshift(targetId);
782
+ }
783
+ handleDragOver(_e, targetId) {
784
+ if (this.dragOverTargetIds === null) {
785
+ this.dragOverTargetIds = [];
786
+ }
787
+ this.dragOverTargetIds.unshift(targetId);
788
+ }
789
+ handleDrop(_e, targetId) {
790
+ this.dropTargetIds.unshift(targetId);
791
+ }
792
+ constructor(manager, globalContext, options){
793
+ this.sourcePreviewNodes = new Map();
794
+ this.sourcePreviewNodeOptions = new Map();
795
+ this.sourceNodes = new Map();
796
+ this.sourceNodeOptions = new Map();
797
+ this.dragStartSourceIds = null;
798
+ this.dropTargetIds = [];
799
+ this.dragEnterTargetIds = [];
800
+ this.currentNativeSource = null;
801
+ this.currentNativeHandle = null;
802
+ this.currentDragSourceNode = null;
803
+ this.altKeyPressed = false;
804
+ this.mouseMoveTimeoutTimer = null;
805
+ this.asyncEndDragFrameId = null;
806
+ this.dragOverTargetIds = null;
807
+ this.lastClientOffset = null;
808
+ this.hoverRafId = null;
809
+ this.getSourceClientOffset = (sourceId)=>{
810
+ const source = this.sourceNodes.get(sourceId);
811
+ return source && getNodeClientOffset$1(source) || null;
812
+ };
813
+ this.endDragNativeItem = ()=>{
814
+ if (!this.isDraggingNativeItem()) {
815
+ return;
816
+ }
817
+ this.actions.endDrag();
818
+ if (this.currentNativeHandle) {
819
+ this.registry.removeSource(this.currentNativeHandle);
820
+ }
821
+ this.currentNativeHandle = null;
822
+ this.currentNativeSource = null;
823
+ };
824
+ this.isNodeInDocument = (node)=>{
825
+ // Check the node either in the main document or in the current context
826
+ return Boolean(node && this.document && this.document.body && this.document.body.contains(node));
827
+ };
828
+ this.endDragIfSourceWasRemovedFromDOM = ()=>{
829
+ const node = this.currentDragSourceNode;
830
+ if (node == null || this.isNodeInDocument(node)) {
831
+ return;
832
+ }
833
+ if (this.clearCurrentDragSourceNode() && this.monitor.isDragging()) {
834
+ this.actions.endDrag();
835
+ }
836
+ this.cancelHover();
837
+ };
838
+ this.scheduleHover = (dragOverTargetIds)=>{
839
+ if (this.hoverRafId === null && typeof requestAnimationFrame !== 'undefined') {
840
+ this.hoverRafId = requestAnimationFrame(()=>{
841
+ if (this.monitor.isDragging()) {
842
+ this.actions.hover(dragOverTargetIds || [], {
843
+ clientOffset: this.lastClientOffset
844
+ });
845
+ }
846
+ this.hoverRafId = null;
847
+ });
848
+ }
849
+ };
850
+ this.cancelHover = ()=>{
851
+ if (this.hoverRafId !== null && typeof cancelAnimationFrame !== 'undefined') {
852
+ cancelAnimationFrame(this.hoverRafId);
853
+ this.hoverRafId = null;
854
+ }
855
+ };
856
+ this.handleTopDragStartCapture = ()=>{
857
+ this.clearCurrentDragSourceNode();
858
+ this.dragStartSourceIds = [];
859
+ };
860
+ this.handleTopDragStart = (e)=>{
861
+ if (e.defaultPrevented) {
862
+ return;
863
+ }
864
+ const { dragStartSourceIds } = this;
865
+ this.dragStartSourceIds = null;
866
+ const clientOffset = getEventClientOffset$1(e);
867
+ // Avoid crashing if we missed a drop event or our previous drag died
868
+ if (this.monitor.isDragging()) {
869
+ this.actions.endDrag();
870
+ this.cancelHover();
871
+ }
872
+ // Don't publish the source just yet (see why below)
873
+ this.actions.beginDrag(dragStartSourceIds || [], {
874
+ publishSource: false,
875
+ getSourceClientOffset: this.getSourceClientOffset,
876
+ clientOffset
877
+ });
878
+ const { dataTransfer } = e;
879
+ const nativeType = matchNativeItemType(dataTransfer);
880
+ if (this.monitor.isDragging()) {
881
+ if (dataTransfer && typeof dataTransfer.setDragImage === 'function') {
882
+ // Use custom drag image if user specifies it.
883
+ // If child drag source refuses drag but parent agrees,
884
+ // use parent's node as drag image. Neither works in IE though.
885
+ const sourceId = this.monitor.getSourceId();
886
+ const sourceNode = this.sourceNodes.get(sourceId);
887
+ const dragPreview = this.sourcePreviewNodes.get(sourceId) || sourceNode;
888
+ if (dragPreview) {
889
+ const { anchorX , anchorY , offsetX , offsetY } = this.getCurrentSourcePreviewNodeOptions();
890
+ const anchorPoint = {
891
+ anchorX,
892
+ anchorY
893
+ };
894
+ const offsetPoint = {
895
+ offsetX,
896
+ offsetY
897
+ };
898
+ const dragPreviewOffset = getDragPreviewOffset(sourceNode, dragPreview, clientOffset, anchorPoint, offsetPoint);
899
+ dataTransfer.setDragImage(dragPreview, dragPreviewOffset.x, dragPreviewOffset.y);
900
+ }
901
+ }
902
+ try {
903
+ // Firefox won't drag without setting data
904
+ dataTransfer === null || dataTransfer === void 0 ? void 0 : dataTransfer.setData('application/json', {});
905
+ } catch (err) {
906
+ // IE doesn't support MIME types in setData
907
+ }
908
+ // Store drag source node so we can check whether
909
+ // it is removed from DOM and trigger endDrag manually.
910
+ this.setCurrentDragSourceNode(e.target);
911
+ // Now we are ready to publish the drag source.. or are we not?
912
+ const { captureDraggingState } = this.getCurrentSourcePreviewNodeOptions();
913
+ if (!captureDraggingState) {
914
+ // Usually we want to publish it in the next tick so that browser
915
+ // is able to screenshot the current (not yet dragging) state.
916
+ //
917
+ // It also neatly avoids a situation where render() returns null
918
+ // in the same tick for the source element, and browser freaks out.
919
+ setTimeout(()=>this.actions.publishDragSource()
920
+ , 0);
921
+ } else {
922
+ // In some cases the user may want to override this behavior, e.g.
923
+ // to work around IE not supporting custom drag previews.
924
+ //
925
+ // When using a custom drag layer, the only way to prevent
926
+ // the default drag preview from drawing in IE is to screenshot
927
+ // the dragging state in which the node itself has zero opacity
928
+ // and height. In this case, though, returning null from render()
929
+ // will abruptly end the dragging, which is not obvious.
930
+ //
931
+ // This is the reason such behavior is strictly opt-in.
932
+ this.actions.publishDragSource();
933
+ }
934
+ } else if (nativeType) {
935
+ // A native item (such as URL) dragged from inside the document
936
+ this.beginDragNativeItem(nativeType);
937
+ } else if (dataTransfer && !dataTransfer.types && (e.target && !e.target.hasAttribute || !e.target.hasAttribute('draggable'))) {
938
+ // Looks like a Safari bug: dataTransfer.types is null, but there was no draggable.
939
+ // Just let it drag. It's a native type (URL or text) and will be picked up in
940
+ // dragenter handler.
941
+ return;
942
+ } else {
943
+ // If by this time no drag source reacted, tell browser not to drag.
944
+ e.preventDefault();
945
+ }
946
+ };
947
+ this.handleTopDragEndCapture = ()=>{
948
+ if (this.clearCurrentDragSourceNode() && this.monitor.isDragging()) {
949
+ // Firefox can dispatch this event in an infinite loop
950
+ // if dragend handler does something like showing an alert.
951
+ // Only proceed if we have not handled it already.
952
+ this.actions.endDrag();
953
+ }
954
+ this.cancelHover();
955
+ };
956
+ this.handleTopDragEnterCapture = (e)=>{
957
+ this.dragEnterTargetIds = [];
958
+ if (this.isDraggingNativeItem()) {
959
+ var ref;
960
+ (ref = this.currentNativeSource) === null || ref === void 0 ? void 0 : ref.loadDataTransfer(e.dataTransfer);
961
+ }
962
+ const isFirstEnter = this.enterLeaveCounter.enter(e.target);
963
+ if (!isFirstEnter || this.monitor.isDragging()) {
964
+ return;
965
+ }
966
+ const { dataTransfer } = e;
967
+ const nativeType = matchNativeItemType(dataTransfer);
968
+ if (nativeType) {
969
+ // A native item (such as file or URL) dragged from outside the document
970
+ this.beginDragNativeItem(nativeType, dataTransfer);
971
+ }
972
+ };
973
+ this.handleTopDragEnter = (e)=>{
974
+ const { dragEnterTargetIds } = this;
975
+ this.dragEnterTargetIds = [];
976
+ if (!this.monitor.isDragging()) {
977
+ // This is probably a native item type we don't understand.
978
+ return;
979
+ }
980
+ this.altKeyPressed = e.altKey;
981
+ // If the target changes position as the result of `dragenter`, `dragover` might still
982
+ // get dispatched despite target being no longer there. The easy solution is to check
983
+ // whether there actually is a target before firing `hover`.
984
+ if (dragEnterTargetIds.length > 0) {
985
+ this.actions.hover(dragEnterTargetIds, {
986
+ clientOffset: getEventClientOffset$1(e)
987
+ });
988
+ }
989
+ const canDrop = dragEnterTargetIds.some((targetId)=>this.monitor.canDropOnTarget(targetId)
990
+ );
991
+ if (canDrop) {
992
+ // IE requires this to fire dragover events
993
+ e.preventDefault();
994
+ if (e.dataTransfer) {
995
+ e.dataTransfer.dropEffect = this.getCurrentDropEffect();
996
+ }
997
+ }
998
+ };
999
+ this.handleTopDragOverCapture = (e)=>{
1000
+ this.dragOverTargetIds = [];
1001
+ if (this.isDraggingNativeItem()) {
1002
+ var ref;
1003
+ (ref = this.currentNativeSource) === null || ref === void 0 ? void 0 : ref.loadDataTransfer(e.dataTransfer);
1004
+ }
1005
+ };
1006
+ this.handleTopDragOver = (e)=>{
1007
+ const { dragOverTargetIds } = this;
1008
+ this.dragOverTargetIds = [];
1009
+ if (!this.monitor.isDragging()) {
1010
+ // This is probably a native item type we don't understand.
1011
+ // Prevent default "drop and blow away the whole document" action.
1012
+ e.preventDefault();
1013
+ if (e.dataTransfer) {
1014
+ e.dataTransfer.dropEffect = 'none';
1015
+ }
1016
+ return;
1017
+ }
1018
+ this.altKeyPressed = e.altKey;
1019
+ this.lastClientOffset = getEventClientOffset$1(e);
1020
+ this.scheduleHover(dragOverTargetIds);
1021
+ const canDrop = (dragOverTargetIds || []).some((targetId)=>this.monitor.canDropOnTarget(targetId)
1022
+ );
1023
+ if (canDrop) {
1024
+ // Show user-specified drop effect.
1025
+ e.preventDefault();
1026
+ if (e.dataTransfer) {
1027
+ e.dataTransfer.dropEffect = this.getCurrentDropEffect();
1028
+ }
1029
+ } else if (this.isDraggingNativeItem()) {
1030
+ // Don't show a nice cursor but still prevent default
1031
+ // "drop and blow away the whole document" action.
1032
+ e.preventDefault();
1033
+ } else {
1034
+ e.preventDefault();
1035
+ if (e.dataTransfer) {
1036
+ e.dataTransfer.dropEffect = 'none';
1037
+ }
1038
+ }
1039
+ };
1040
+ this.handleTopDragLeaveCapture = (e)=>{
1041
+ if (this.isDraggingNativeItem()) {
1042
+ e.preventDefault();
1043
+ }
1044
+ const isLastLeave = this.enterLeaveCounter.leave(e.target);
1045
+ if (!isLastLeave) {
1046
+ return;
1047
+ }
1048
+ if (this.isDraggingNativeItem()) {
1049
+ setTimeout(()=>this.endDragNativeItem()
1050
+ , 0);
1051
+ }
1052
+ this.cancelHover();
1053
+ };
1054
+ this.handleTopDropCapture = (e)=>{
1055
+ this.dropTargetIds = [];
1056
+ if (this.isDraggingNativeItem()) {
1057
+ var ref;
1058
+ e.preventDefault();
1059
+ (ref = this.currentNativeSource) === null || ref === void 0 ? void 0 : ref.loadDataTransfer(e.dataTransfer);
1060
+ } else if (matchNativeItemType(e.dataTransfer)) {
1061
+ // Dragging some elements, like <a> and <img> may still behave like a native drag event,
1062
+ // even if the current drag event matches a user-defined type.
1063
+ // Stop the default behavior when we're not expecting a native item to be dropped.
1064
+ e.preventDefault();
1065
+ }
1066
+ this.enterLeaveCounter.reset();
22
1067
  };
1068
+ this.handleTopDrop = (e)=>{
1069
+ const { dropTargetIds } = this;
1070
+ this.dropTargetIds = [];
1071
+ this.actions.hover(dropTargetIds, {
1072
+ clientOffset: getEventClientOffset$1(e)
1073
+ });
1074
+ this.actions.drop({
1075
+ dropEffect: this.getCurrentDropEffect()
1076
+ });
1077
+ if (this.isDraggingNativeItem()) {
1078
+ this.endDragNativeItem();
1079
+ } else if (this.monitor.isDragging()) {
1080
+ this.actions.endDrag();
1081
+ }
1082
+ this.cancelHover();
1083
+ };
1084
+ this.handleSelectStart = (e)=>{
1085
+ const target = e.target;
1086
+ // Only IE requires us to explicitly say
1087
+ // we want drag drop operation to start
1088
+ if (typeof target.dragDrop !== 'function') {
1089
+ return;
1090
+ }
1091
+ // Inputs and textareas should be selectable
1092
+ if (target.tagName === 'INPUT' || target.tagName === 'SELECT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {
1093
+ return;
1094
+ }
1095
+ // For other targets, ask IE
1096
+ // to enable drag and drop
1097
+ e.preventDefault();
1098
+ target.dragDrop();
1099
+ };
1100
+ this.options = new OptionsReader$1(globalContext, options);
1101
+ this.actions = manager.getActions();
1102
+ this.monitor = manager.getMonitor();
1103
+ this.registry = manager.getRegistry();
1104
+ this.enterLeaveCounter = new EnterLeaveCounter(this.isNodeInDocument);
1105
+ }
1106
+ }
1107
+
1108
+ const HTML5Backend = function createBackend(manager, context, options) {
1109
+ return new HTML5BackendImpl(manager, context, options);
1110
+ };
1111
+
1112
+ var ListenerType;
1113
+ (function(ListenerType) {
1114
+ ListenerType["mouse"] = "mouse";
1115
+ ListenerType["touch"] = "touch";
1116
+ ListenerType["keyboard"] = "keyboard";
1117
+ })(ListenerType || (ListenerType = {}));
1118
+
1119
+ class OptionsReader {
1120
+ get delay() {
1121
+ var _delay;
1122
+ return (_delay = this.args.delay) !== null && _delay !== void 0 ? _delay : 0;
1123
+ }
1124
+ get scrollAngleRanges() {
1125
+ return this.args.scrollAngleRanges;
1126
+ }
1127
+ get getDropTargetElementsAtPoint() {
1128
+ return this.args.getDropTargetElementsAtPoint;
1129
+ }
1130
+ get ignoreContextMenu() {
1131
+ var _ignoreContextMenu;
1132
+ return (_ignoreContextMenu = this.args.ignoreContextMenu) !== null && _ignoreContextMenu !== void 0 ? _ignoreContextMenu : false;
1133
+ }
1134
+ get enableHoverOutsideTarget() {
1135
+ var _enableHoverOutsideTarget;
1136
+ return (_enableHoverOutsideTarget = this.args.enableHoverOutsideTarget) !== null && _enableHoverOutsideTarget !== void 0 ? _enableHoverOutsideTarget : false;
1137
+ }
1138
+ get enableKeyboardEvents() {
1139
+ var _enableKeyboardEvents;
1140
+ return (_enableKeyboardEvents = this.args.enableKeyboardEvents) !== null && _enableKeyboardEvents !== void 0 ? _enableKeyboardEvents : false;
1141
+ }
1142
+ get enableMouseEvents() {
1143
+ var _enableMouseEvents;
1144
+ return (_enableMouseEvents = this.args.enableMouseEvents) !== null && _enableMouseEvents !== void 0 ? _enableMouseEvents : false;
1145
+ }
1146
+ get enableTouchEvents() {
1147
+ var _enableTouchEvents;
1148
+ return (_enableTouchEvents = this.args.enableTouchEvents) !== null && _enableTouchEvents !== void 0 ? _enableTouchEvents : true;
1149
+ }
1150
+ get touchSlop() {
1151
+ return this.args.touchSlop || 0;
1152
+ }
1153
+ get delayTouchStart() {
1154
+ var ref, ref1;
1155
+ var ref2, ref3;
1156
+ return (ref3 = (ref2 = (ref = this.args) === null || ref === void 0 ? void 0 : ref.delayTouchStart) !== null && ref2 !== void 0 ? ref2 : (ref1 = this.args) === null || ref1 === void 0 ? void 0 : ref1.delay) !== null && ref3 !== void 0 ? ref3 : 0;
1157
+ }
1158
+ get delayMouseStart() {
1159
+ var ref, ref4;
1160
+ var ref5, ref6;
1161
+ return (ref6 = (ref5 = (ref = this.args) === null || ref === void 0 ? void 0 : ref.delayMouseStart) !== null && ref5 !== void 0 ? ref5 : (ref4 = this.args) === null || ref4 === void 0 ? void 0 : ref4.delay) !== null && ref6 !== void 0 ? ref6 : 0;
1162
+ }
1163
+ get window() {
1164
+ if (this.context && this.context.window) {
1165
+ return this.context.window;
1166
+ } else if (typeof window !== 'undefined') {
1167
+ return window;
1168
+ }
1169
+ return undefined;
1170
+ }
1171
+ get document() {
1172
+ var ref;
1173
+ if ((ref = this.context) === null || ref === void 0 ? void 0 : ref.document) {
1174
+ return this.context.document;
1175
+ }
1176
+ if (this.window) {
1177
+ return this.window.document;
1178
+ }
1179
+ return undefined;
1180
+ }
1181
+ get rootElement() {
1182
+ var ref;
1183
+ return ((ref = this.args) === null || ref === void 0 ? void 0 : ref.rootElement) || this.document;
1184
+ }
1185
+ constructor(args, context){
1186
+ this.args = args;
1187
+ this.context = context;
1188
+ }
1189
+ }
1190
+
1191
+ function distance(x1, y1, x2, y2) {
1192
+ return Math.sqrt(Math.pow(Math.abs(x2 - x1), 2) + Math.pow(Math.abs(y2 - y1), 2));
1193
+ }
1194
+ function inAngleRanges(x1, y1, x2, y2, angleRanges) {
1195
+ if (!angleRanges) {
1196
+ return false;
1197
+ }
1198
+ const angle = Math.atan2(y2 - y1, x2 - x1) * 180 / Math.PI + 180;
1199
+ for(let i = 0; i < angleRanges.length; ++i){
1200
+ const ar = angleRanges[i];
1201
+ if (ar && (ar.start == null || angle >= ar.start) && (ar.end == null || angle <= ar.end)) {
1202
+ return true;
1203
+ }
1204
+ }
1205
+ return false;
1206
+ }
1207
+
1208
+ // Used for MouseEvent.buttons (note the s on the end).
1209
+ const MouseButtons = {
1210
+ Left: 1};
1211
+ // Used for e.button (note the lack of an s on the end).
1212
+ const MouseButton = {
1213
+ Left: 0};
1214
+ /**
1215
+ * Only touch events and mouse events where the left button is pressed should initiate a drag.
1216
+ * @param {MouseEvent | TouchEvent} e The event
1217
+ */ function eventShouldStartDrag(e) {
1218
+ // For touch events, button will be undefined. If e.button is defined,
1219
+ // then it should be MouseButton.Left.
1220
+ return e.button === undefined || e.button === MouseButton.Left;
1221
+ }
1222
+ /**
1223
+ * Only touch events and mouse events where the left mouse button is no longer held should end a drag.
1224
+ * It's possible the user mouse downs with the left mouse button, then mouse down and ups with the right mouse button.
1225
+ * We don't want releasing the right mouse button to end the drag.
1226
+ * @param {MouseEvent | TouchEvent} e The event
1227
+ */ function eventShouldEndDrag(e) {
1228
+ // Touch events will have buttons be undefined, while mouse events will have e.buttons's left button
1229
+ // bit field unset if the left mouse button has been released
1230
+ return e.buttons === undefined || (e.buttons & MouseButtons.Left) === 0;
1231
+ }
1232
+ function isTouchEvent(e) {
1233
+ return !!e.targetTouches;
1234
+ }
1235
+
1236
+ const ELEMENT_NODE = 1;
1237
+ function getNodeClientOffset(node) {
1238
+ const el = node.nodeType === ELEMENT_NODE ? node : node.parentElement;
1239
+ if (!el) {
1240
+ return undefined;
23
1241
  }
1242
+ const { top , left } = el.getBoundingClientRect();
24
1243
  return {
25
- customDarkSquareStyle: { backgroundColor: '#b58863' },
26
- customLightSquareStyle: { backgroundColor: '#f0d9b5' },
1244
+ x: left,
1245
+ y: top
27
1246
  };
1247
+ }
1248
+ function getEventClientTouchOffset(e, lastTargetTouchFallback) {
1249
+ if (e.targetTouches.length === 1) {
1250
+ return getEventClientOffset(e.targetTouches[0]);
1251
+ } else if (lastTargetTouchFallback && e.touches.length === 1) {
1252
+ if (e.touches[0].target === lastTargetTouchFallback.target) {
1253
+ return getEventClientOffset(e.touches[0]);
1254
+ }
1255
+ }
1256
+ return;
1257
+ }
1258
+ function getEventClientOffset(e, lastTargetTouchFallback) {
1259
+ if (isTouchEvent(e)) {
1260
+ return getEventClientTouchOffset(e, lastTargetTouchFallback);
1261
+ } else {
1262
+ return {
1263
+ x: e.clientX,
1264
+ y: e.clientY
1265
+ };
1266
+ }
1267
+ }
1268
+
1269
+ const supportsPassive = (()=>{
1270
+ // simular to jQuery's test
1271
+ let supported = false;
1272
+ try {
1273
+ addEventListener('test', ()=>{
1274
+ // do nothing
1275
+ }, Object.defineProperty({}, 'passive', {
1276
+ get () {
1277
+ supported = true;
1278
+ return true;
1279
+ }
1280
+ }));
1281
+ } catch (e) {
1282
+ // do nothing
1283
+ }
1284
+ return supported;
1285
+ })();
1286
+
1287
+ const eventNames = {
1288
+ [ListenerType.mouse]: {
1289
+ start: 'mousedown',
1290
+ move: 'mousemove',
1291
+ end: 'mouseup',
1292
+ contextmenu: 'contextmenu'
1293
+ },
1294
+ [ListenerType.touch]: {
1295
+ start: 'touchstart',
1296
+ move: 'touchmove',
1297
+ end: 'touchend'
1298
+ },
1299
+ [ListenerType.keyboard]: {
1300
+ keydown: 'keydown'
1301
+ }
28
1302
  };
29
- const ThemeProvider = ({ children, theme }) => {
30
- const { customDarkSquareStyle, customLightSquareStyle } = getStylesForTheme(theme);
31
- return (jsx(ChessboardThemeContext.Provider, { value: { customDarkSquareStyle, customLightSquareStyle }, children: children }));
1303
+ class TouchBackendImpl {
1304
+ /**
1305
+ * Generate profiling statistics for the HTML5Backend.
1306
+ */ profile() {
1307
+ var ref;
1308
+ return {
1309
+ sourceNodes: this.sourceNodes.size,
1310
+ sourcePreviewNodes: this.sourcePreviewNodes.size,
1311
+ sourcePreviewNodeOptions: this.sourcePreviewNodeOptions.size,
1312
+ targetNodes: this.targetNodes.size,
1313
+ dragOverTargetIds: ((ref = this.dragOverTargetIds) === null || ref === void 0 ? void 0 : ref.length) || 0
1314
+ };
1315
+ }
1316
+ // public for test
1317
+ get document() {
1318
+ return this.options.document;
1319
+ }
1320
+ setup() {
1321
+ const root = this.options.rootElement;
1322
+ if (!root) {
1323
+ return;
1324
+ }
1325
+ invariant(!TouchBackendImpl.isSetUp, 'Cannot have two Touch backends at the same time.');
1326
+ TouchBackendImpl.isSetUp = true;
1327
+ this.addEventListener(root, 'start', this.getTopMoveStartHandler());
1328
+ this.addEventListener(root, 'start', this.handleTopMoveStartCapture, true);
1329
+ this.addEventListener(root, 'move', this.handleTopMove);
1330
+ this.addEventListener(root, 'move', this.handleTopMoveCapture, true);
1331
+ this.addEventListener(root, 'end', this.handleTopMoveEndCapture, true);
1332
+ if (this.options.enableMouseEvents && !this.options.ignoreContextMenu) {
1333
+ this.addEventListener(root, 'contextmenu', this.handleTopMoveEndCapture);
1334
+ }
1335
+ if (this.options.enableKeyboardEvents) {
1336
+ this.addEventListener(root, 'keydown', this.handleCancelOnEscape, true);
1337
+ }
1338
+ }
1339
+ teardown() {
1340
+ const root = this.options.rootElement;
1341
+ if (!root) {
1342
+ return;
1343
+ }
1344
+ TouchBackendImpl.isSetUp = false;
1345
+ this._mouseClientOffset = {};
1346
+ this.removeEventListener(root, 'start', this.handleTopMoveStartCapture, true);
1347
+ this.removeEventListener(root, 'start', this.handleTopMoveStart);
1348
+ this.removeEventListener(root, 'move', this.handleTopMoveCapture, true);
1349
+ this.removeEventListener(root, 'move', this.handleTopMove);
1350
+ this.removeEventListener(root, 'end', this.handleTopMoveEndCapture, true);
1351
+ if (this.options.enableMouseEvents && !this.options.ignoreContextMenu) {
1352
+ this.removeEventListener(root, 'contextmenu', this.handleTopMoveEndCapture);
1353
+ }
1354
+ if (this.options.enableKeyboardEvents) {
1355
+ this.removeEventListener(root, 'keydown', this.handleCancelOnEscape, true);
1356
+ }
1357
+ this.uninstallSourceNodeRemovalObserver();
1358
+ }
1359
+ addEventListener(subject, event, handler, capture = false) {
1360
+ const options = supportsPassive ? {
1361
+ capture,
1362
+ passive: false
1363
+ } : capture;
1364
+ this.listenerTypes.forEach(function(listenerType) {
1365
+ const evt = eventNames[listenerType][event];
1366
+ if (evt) {
1367
+ subject.addEventListener(evt, handler, options);
1368
+ }
1369
+ });
1370
+ }
1371
+ removeEventListener(subject, event, handler, capture = false) {
1372
+ const options = supportsPassive ? {
1373
+ capture,
1374
+ passive: false
1375
+ } : capture;
1376
+ this.listenerTypes.forEach(function(listenerType) {
1377
+ const evt = eventNames[listenerType][event];
1378
+ if (evt) {
1379
+ subject.removeEventListener(evt, handler, options);
1380
+ }
1381
+ });
1382
+ }
1383
+ connectDragSource(sourceId, node) {
1384
+ const handleMoveStart = this.handleMoveStart.bind(this, sourceId);
1385
+ this.sourceNodes.set(sourceId, node);
1386
+ this.addEventListener(node, 'start', handleMoveStart);
1387
+ return ()=>{
1388
+ this.sourceNodes.delete(sourceId);
1389
+ this.removeEventListener(node, 'start', handleMoveStart);
1390
+ };
1391
+ }
1392
+ connectDragPreview(sourceId, node, options) {
1393
+ this.sourcePreviewNodeOptions.set(sourceId, options);
1394
+ this.sourcePreviewNodes.set(sourceId, node);
1395
+ return ()=>{
1396
+ this.sourcePreviewNodes.delete(sourceId);
1397
+ this.sourcePreviewNodeOptions.delete(sourceId);
1398
+ };
1399
+ }
1400
+ connectDropTarget(targetId, node) {
1401
+ const root = this.options.rootElement;
1402
+ if (!this.document || !root) {
1403
+ return ()=>{
1404
+ /* noop */ };
1405
+ }
1406
+ const handleMove = (e)=>{
1407
+ if (!this.document || !root || !this.monitor.isDragging()) {
1408
+ return;
1409
+ }
1410
+ let coords;
1411
+ /**
1412
+ * Grab the coordinates for the current mouse/touch position
1413
+ */ switch(e.type){
1414
+ case eventNames.mouse.move:
1415
+ coords = {
1416
+ x: e.clientX,
1417
+ y: e.clientY
1418
+ };
1419
+ break;
1420
+ case eventNames.touch.move:
1421
+ var ref, ref1;
1422
+ coords = {
1423
+ x: ((ref = e.touches[0]) === null || ref === void 0 ? void 0 : ref.clientX) || 0,
1424
+ y: ((ref1 = e.touches[0]) === null || ref1 === void 0 ? void 0 : ref1.clientY) || 0
1425
+ };
1426
+ break;
1427
+ }
1428
+ /**
1429
+ * Use the coordinates to grab the element the drag ended on.
1430
+ * If the element is the same as the target node (or any of it's children) then we have hit a drop target and can handle the move.
1431
+ */ const droppedOn = coords != null ? this.document.elementFromPoint(coords.x, coords.y) : undefined;
1432
+ const childMatch = droppedOn && node.contains(droppedOn);
1433
+ if (droppedOn === node || childMatch) {
1434
+ return this.handleMove(e, targetId);
1435
+ }
1436
+ };
1437
+ /**
1438
+ * Attaching the event listener to the body so that touchmove will work while dragging over multiple target elements.
1439
+ */ this.addEventListener(this.document.body, 'move', handleMove);
1440
+ this.targetNodes.set(targetId, node);
1441
+ return ()=>{
1442
+ if (this.document) {
1443
+ this.targetNodes.delete(targetId);
1444
+ this.removeEventListener(this.document.body, 'move', handleMove);
1445
+ }
1446
+ };
1447
+ }
1448
+ getTopMoveStartHandler() {
1449
+ if (!this.options.delayTouchStart && !this.options.delayMouseStart) {
1450
+ return this.handleTopMoveStart;
1451
+ }
1452
+ return this.handleTopMoveStartDelay;
1453
+ }
1454
+ installSourceNodeRemovalObserver(node) {
1455
+ this.uninstallSourceNodeRemovalObserver();
1456
+ this.draggedSourceNode = node;
1457
+ this.draggedSourceNodeRemovalObserver = new MutationObserver(()=>{
1458
+ if (node && !node.parentElement) {
1459
+ this.resurrectSourceNode();
1460
+ this.uninstallSourceNodeRemovalObserver();
1461
+ }
1462
+ });
1463
+ if (!node || !node.parentElement) {
1464
+ return;
1465
+ }
1466
+ this.draggedSourceNodeRemovalObserver.observe(node.parentElement, {
1467
+ childList: true
1468
+ });
1469
+ }
1470
+ resurrectSourceNode() {
1471
+ if (this.document && this.draggedSourceNode) {
1472
+ this.draggedSourceNode.style.display = 'none';
1473
+ this.draggedSourceNode.removeAttribute('data-reactid');
1474
+ this.document.body.appendChild(this.draggedSourceNode);
1475
+ }
1476
+ }
1477
+ uninstallSourceNodeRemovalObserver() {
1478
+ if (this.draggedSourceNodeRemovalObserver) {
1479
+ this.draggedSourceNodeRemovalObserver.disconnect();
1480
+ }
1481
+ this.draggedSourceNodeRemovalObserver = undefined;
1482
+ this.draggedSourceNode = undefined;
1483
+ }
1484
+ constructor(manager, context, options){
1485
+ this.getSourceClientOffset = (sourceId)=>{
1486
+ const element = this.sourceNodes.get(sourceId);
1487
+ return element && getNodeClientOffset(element);
1488
+ };
1489
+ this.handleTopMoveStartCapture = (e)=>{
1490
+ if (!eventShouldStartDrag(e)) {
1491
+ return;
1492
+ }
1493
+ this.moveStartSourceIds = [];
1494
+ };
1495
+ this.handleMoveStart = (sourceId)=>{
1496
+ // Just because we received an event doesn't necessarily mean we need to collect drag sources.
1497
+ // We only collect start collecting drag sources on touch and left mouse events.
1498
+ if (Array.isArray(this.moveStartSourceIds)) {
1499
+ this.moveStartSourceIds.unshift(sourceId);
1500
+ }
1501
+ };
1502
+ this.handleTopMoveStart = (e)=>{
1503
+ if (!eventShouldStartDrag(e)) {
1504
+ return;
1505
+ }
1506
+ // Don't prematurely preventDefault() here since it might:
1507
+ // 1. Mess up scrolling
1508
+ // 2. Mess up long tap (which brings up context menu)
1509
+ // 3. If there's an anchor link as a child, tap won't be triggered on link
1510
+ const clientOffset = getEventClientOffset(e);
1511
+ if (clientOffset) {
1512
+ if (isTouchEvent(e)) {
1513
+ this.lastTargetTouchFallback = e.targetTouches[0];
1514
+ }
1515
+ this._mouseClientOffset = clientOffset;
1516
+ }
1517
+ this.waitingForDelay = false;
1518
+ };
1519
+ this.handleTopMoveStartDelay = (e)=>{
1520
+ if (!eventShouldStartDrag(e)) {
1521
+ return;
1522
+ }
1523
+ const delay = e.type === eventNames.touch.start ? this.options.delayTouchStart : this.options.delayMouseStart;
1524
+ this.timeout = setTimeout(this.handleTopMoveStart.bind(this, e), delay);
1525
+ this.waitingForDelay = true;
1526
+ };
1527
+ this.handleTopMoveCapture = ()=>{
1528
+ this.dragOverTargetIds = [];
1529
+ };
1530
+ this.handleMove = (_evt, targetId)=>{
1531
+ if (this.dragOverTargetIds) {
1532
+ this.dragOverTargetIds.unshift(targetId);
1533
+ }
1534
+ };
1535
+ this.handleTopMove = (e1)=>{
1536
+ if (this.timeout) {
1537
+ clearTimeout(this.timeout);
1538
+ }
1539
+ if (!this.document || this.waitingForDelay) {
1540
+ return;
1541
+ }
1542
+ const { moveStartSourceIds , dragOverTargetIds } = this;
1543
+ const enableHoverOutsideTarget = this.options.enableHoverOutsideTarget;
1544
+ const clientOffset = getEventClientOffset(e1, this.lastTargetTouchFallback);
1545
+ if (!clientOffset) {
1546
+ return;
1547
+ }
1548
+ // If the touch move started as a scroll, or is is between the scroll angles
1549
+ if (this._isScrolling || !this.monitor.isDragging() && inAngleRanges(this._mouseClientOffset.x || 0, this._mouseClientOffset.y || 0, clientOffset.x, clientOffset.y, this.options.scrollAngleRanges)) {
1550
+ this._isScrolling = true;
1551
+ return;
1552
+ }
1553
+ // If we're not dragging and we've moved a little, that counts as a drag start
1554
+ if (!this.monitor.isDragging() && // eslint-disable-next-line no-prototype-builtins
1555
+ this._mouseClientOffset.hasOwnProperty('x') && moveStartSourceIds && distance(this._mouseClientOffset.x || 0, this._mouseClientOffset.y || 0, clientOffset.x, clientOffset.y) > (this.options.touchSlop ? this.options.touchSlop : 0)) {
1556
+ this.moveStartSourceIds = undefined;
1557
+ this.actions.beginDrag(moveStartSourceIds, {
1558
+ clientOffset: this._mouseClientOffset,
1559
+ getSourceClientOffset: this.getSourceClientOffset,
1560
+ publishSource: false
1561
+ });
1562
+ }
1563
+ if (!this.monitor.isDragging()) {
1564
+ return;
1565
+ }
1566
+ const sourceNode = this.sourceNodes.get(this.monitor.getSourceId());
1567
+ this.installSourceNodeRemovalObserver(sourceNode);
1568
+ this.actions.publishDragSource();
1569
+ if (e1.cancelable) e1.preventDefault();
1570
+ // Get the node elements of the hovered DropTargets
1571
+ const dragOverTargetNodes = (dragOverTargetIds || []).map((key)=>this.targetNodes.get(key)
1572
+ ).filter((e)=>!!e
1573
+ );
1574
+ // Get the a ordered list of nodes that are touched by
1575
+ const elementsAtPoint = this.options.getDropTargetElementsAtPoint ? this.options.getDropTargetElementsAtPoint(clientOffset.x, clientOffset.y, dragOverTargetNodes) : this.document.elementsFromPoint(clientOffset.x, clientOffset.y);
1576
+ // Extend list with parents that are not receiving elementsFromPoint events (size 0 elements and svg groups)
1577
+ const elementsAtPointExtended = [];
1578
+ for(const nodeId in elementsAtPoint){
1579
+ // eslint-disable-next-line no-prototype-builtins
1580
+ if (!elementsAtPoint.hasOwnProperty(nodeId)) {
1581
+ continue;
1582
+ }
1583
+ let currentNode = elementsAtPoint[nodeId];
1584
+ if (currentNode != null) {
1585
+ elementsAtPointExtended.push(currentNode);
1586
+ }
1587
+ while(currentNode){
1588
+ currentNode = currentNode.parentElement;
1589
+ if (currentNode && elementsAtPointExtended.indexOf(currentNode) === -1) {
1590
+ elementsAtPointExtended.push(currentNode);
1591
+ }
1592
+ }
1593
+ }
1594
+ const orderedDragOverTargetIds = elementsAtPointExtended// Filter off nodes that arent a hovered DropTargets nodes
1595
+ .filter((node)=>dragOverTargetNodes.indexOf(node) > -1
1596
+ )// Map back the nodes elements to targetIds
1597
+ .map((node)=>this._getDropTargetId(node)
1598
+ )// Filter off possible null rows
1599
+ .filter((node)=>!!node
1600
+ ).filter((id, index, ids)=>ids.indexOf(id) === index
1601
+ );
1602
+ // Invoke hover for drop targets when source node is still over and pointer is outside
1603
+ if (enableHoverOutsideTarget) {
1604
+ for(const targetId in this.targetNodes){
1605
+ const targetNode = this.targetNodes.get(targetId);
1606
+ if (sourceNode && targetNode && targetNode.contains(sourceNode) && orderedDragOverTargetIds.indexOf(targetId) === -1) {
1607
+ orderedDragOverTargetIds.unshift(targetId);
1608
+ break;
1609
+ }
1610
+ }
1611
+ }
1612
+ // Reverse order because dnd-core reverse it before calling the DropTarget drop methods
1613
+ orderedDragOverTargetIds.reverse();
1614
+ this.actions.hover(orderedDragOverTargetIds, {
1615
+ clientOffset: clientOffset
1616
+ });
1617
+ };
1618
+ /**
1619
+ *
1620
+ * visible for testing
1621
+ */ this._getDropTargetId = (node)=>{
1622
+ const keys = this.targetNodes.keys();
1623
+ let next = keys.next();
1624
+ while(next.done === false){
1625
+ const targetId = next.value;
1626
+ if (node === this.targetNodes.get(targetId)) {
1627
+ return targetId;
1628
+ } else {
1629
+ next = keys.next();
1630
+ }
1631
+ }
1632
+ return undefined;
1633
+ };
1634
+ this.handleTopMoveEndCapture = (e)=>{
1635
+ this._isScrolling = false;
1636
+ this.lastTargetTouchFallback = undefined;
1637
+ if (!eventShouldEndDrag(e)) {
1638
+ return;
1639
+ }
1640
+ if (!this.monitor.isDragging() || this.monitor.didDrop()) {
1641
+ this.moveStartSourceIds = undefined;
1642
+ return;
1643
+ }
1644
+ if (e.cancelable) e.preventDefault();
1645
+ this._mouseClientOffset = {};
1646
+ this.uninstallSourceNodeRemovalObserver();
1647
+ this.actions.drop();
1648
+ this.actions.endDrag();
1649
+ };
1650
+ this.handleCancelOnEscape = (e)=>{
1651
+ if (e.key === 'Escape' && this.monitor.isDragging()) {
1652
+ this._mouseClientOffset = {};
1653
+ this.uninstallSourceNodeRemovalObserver();
1654
+ this.actions.endDrag();
1655
+ }
1656
+ };
1657
+ this.options = new OptionsReader(options, context);
1658
+ this.actions = manager.getActions();
1659
+ this.monitor = manager.getMonitor();
1660
+ this.sourceNodes = new Map();
1661
+ this.sourcePreviewNodes = new Map();
1662
+ this.sourcePreviewNodeOptions = new Map();
1663
+ this.targetNodes = new Map();
1664
+ this.listenerTypes = [];
1665
+ this._mouseClientOffset = {};
1666
+ this._isScrolling = false;
1667
+ if (this.options.enableMouseEvents) {
1668
+ this.listenerTypes.push(ListenerType.mouse);
1669
+ }
1670
+ if (this.options.enableTouchEvents) {
1671
+ this.listenerTypes.push(ListenerType.touch);
1672
+ }
1673
+ if (this.options.enableKeyboardEvents) {
1674
+ this.listenerTypes.push(ListenerType.keyboard);
1675
+ }
1676
+ }
1677
+ }
1678
+
1679
+ const TouchBackend = function createBackend(manager, context = {}, options = {}) {
1680
+ return new TouchBackendImpl(manager, context, options);
32
1681
  };
33
1682
 
1683
+ var c={backends:[{id:"html5",backend:HTML5Backend,transition:U},{id:"touch",backend:TouchBackend,options:{enableMouseEvents:true},preview:true,transition:L}]};
1684
+
1685
+ /**
1686
+ * HTML5 for mouse (desktop + Chrome device emulation), touch backend for real
1687
+ * mobile devices. react-chessboard alone picks TouchBackend whenever
1688
+ * `ontouchstart` is in window, which breaks mouse drags in DevTools emulation.
1689
+ */
1690
+ const ChessboardDnDProvider = ({ children, }) => (jsx(ChessboardDnDProvider$1, { backend: S, options: c, children: children }));
1691
+
34
1692
  /******************************************************************************
35
1693
  Copyright (c) Microsoft Corporation.
36
1694
 
@@ -551,23 +2209,215 @@ class StockfishBrowserEngine {
551
2209
  if (generation !== this.analysisGeneration) {
552
2210
  return;
553
2211
  }
554
- const withFen = this.analysisFen.length > 0
555
- ? Object.assign(Object.assign({}, evaluation), { fen: this.analysisFen }) : evaluation;
556
- this.evaluation = withFen;
557
- this.listeners.forEach((listener) => listener(withFen));
558
- }
559
- }
2212
+ const withFen = this.analysisFen.length > 0
2213
+ ? Object.assign(Object.assign({}, evaluation), { fen: this.analysisFen }) : evaluation;
2214
+ this.evaluation = withFen;
2215
+ this.listeners.forEach((listener) => listener(withFen));
2216
+ }
2217
+ }
2218
+
2219
+ const AnalysisEngineContext = createContext(null);
2220
+ const useAnalysisEngineContext = () => useContext(AnalysisEngineContext);
2221
+ const normalizeSubscriberOptions = (fen, options = {}) => {
2222
+ var _a, _b, _c, _d;
2223
+ return ({
2224
+ fen,
2225
+ enabled: (_a = options.enabled) !== null && _a !== void 0 ? _a : true,
2226
+ depth: (_b = options.depth) !== null && _b !== void 0 ? _b : 16,
2227
+ multiPv: (_c = options.multiPv) !== null && _c !== void 0 ? _c : 2,
2228
+ priority: (_d = options.priority) !== null && _d !== void 0 ? _d : 0,
2229
+ });
2230
+ };
2231
+ const analyzingForFen = (fen, evaluation) => (Object.assign(Object.assign({}, emptyEngineEvaluation()), { status: evaluation.status === 'error'
2232
+ ? 'error'
2233
+ : evaluation.status === 'loading'
2234
+ ? 'loading'
2235
+ : 'analyzing', error: evaluation.error, fen }));
2236
+ const AnalysisEngineProvider = ({ scriptUrl = DEFAULT_STOCKFISH_SCRIPT_URL, children, }) => {
2237
+ const engineRef = useRef(null);
2238
+ const subscribersRef = useRef(new Map());
2239
+ const nextIdRef = useRef(0);
2240
+ const activeKeyRef = useRef('');
2241
+ const readyRef = useRef(false);
2242
+ const scheduleRef = useRef(null);
2243
+ const lastEvaluationRef = useRef(emptyEngineEvaluation());
2244
+ const pickActive = useCallback(() => {
2245
+ const enabled = [...subscribersRef.current.values()].filter((subscriber) => subscriber.options.enabled);
2246
+ if (enabled.length === 0) {
2247
+ return null;
2248
+ }
2249
+ return enabled.sort((left, right) => right.options.priority - left.options.priority)[0];
2250
+ }, []);
2251
+ const notifyAll = useCallback((evaluation) => {
2252
+ lastEvaluationRef.current = evaluation;
2253
+ const active = pickActive();
2254
+ for (const subscriber of subscribersRef.current.values()) {
2255
+ const { fen, enabled } = subscriber.options;
2256
+ if (!enabled) {
2257
+ subscriber.listener(emptyEngineEvaluation());
2258
+ continue;
2259
+ }
2260
+ if (evaluation.fen && evaluation.fen === fen) {
2261
+ subscriber.listener(evaluation);
2262
+ continue;
2263
+ }
2264
+ if ((active === null || active === void 0 ? void 0 : active.id) === subscriber.id) {
2265
+ subscriber.listener(analyzingForFen(fen, evaluation));
2266
+ }
2267
+ }
2268
+ }, [pickActive]);
2269
+ const syncAnalysis = useCallback(() => {
2270
+ const engine = engineRef.current;
2271
+ if (!engine || !readyRef.current) {
2272
+ return;
2273
+ }
2274
+ const active = pickActive();
2275
+ if (!active) {
2276
+ activeKeyRef.current = '';
2277
+ engine.stop();
2278
+ notifyAll(emptyEngineEvaluation());
2279
+ return;
2280
+ }
2281
+ const { fen, depth, multiPv } = active.options;
2282
+ const key = `${active.id}|${fen}|${depth}|${multiPv}`;
2283
+ if (key === activeKeyRef.current) {
2284
+ return;
2285
+ }
2286
+ activeKeyRef.current = key;
2287
+ if (scheduleRef.current !== null) {
2288
+ window.clearTimeout(scheduleRef.current);
2289
+ }
2290
+ scheduleRef.current = window.setTimeout(() => {
2291
+ scheduleRef.current = null;
2292
+ engine.analyze(fen, depth, multiPv);
2293
+ }, 75);
2294
+ }, [notifyAll, pickActive]);
2295
+ useEffect(() => {
2296
+ if (typeof Worker === 'undefined') {
2297
+ return;
2298
+ }
2299
+ const engine = new StockfishBrowserEngine(scriptUrl);
2300
+ engineRef.current = engine;
2301
+ let cancelled = false;
2302
+ const unsubscribe = engine.subscribe((evaluation) => {
2303
+ if (!cancelled) {
2304
+ notifyAll(evaluation);
2305
+ }
2306
+ });
2307
+ engine
2308
+ .init()
2309
+ .then(() => {
2310
+ if (cancelled) {
2311
+ return;
2312
+ }
2313
+ readyRef.current = true;
2314
+ syncAnalysis();
2315
+ })
2316
+ .catch((error) => {
2317
+ if (cancelled) {
2318
+ return;
2319
+ }
2320
+ const message = error instanceof Error ? error.message : 'Failed to start engine';
2321
+ notifyAll(Object.assign(Object.assign({}, emptyEngineEvaluation()), { status: 'error', error: message }));
2322
+ });
2323
+ return () => {
2324
+ cancelled = true;
2325
+ readyRef.current = false;
2326
+ activeKeyRef.current = '';
2327
+ if (scheduleRef.current !== null) {
2328
+ window.clearTimeout(scheduleRef.current);
2329
+ scheduleRef.current = null;
2330
+ }
2331
+ unsubscribe();
2332
+ engine.dispose();
2333
+ engineRef.current = null;
2334
+ };
2335
+ }, [notifyAll, scriptUrl, syncAnalysis]);
2336
+ const register = useCallback((options, listener) => {
2337
+ const id = ++nextIdRef.current;
2338
+ subscribersRef.current.set(id, { id, options, listener });
2339
+ if (options.enabled) {
2340
+ const active = pickActive();
2341
+ if ((active === null || active === void 0 ? void 0 : active.id) === id) {
2342
+ listener(analyzingForFen(options.fen, lastEvaluationRef.current));
2343
+ }
2344
+ }
2345
+ else {
2346
+ listener(emptyEngineEvaluation());
2347
+ }
2348
+ syncAnalysis();
2349
+ return id;
2350
+ }, [pickActive, syncAnalysis]);
2351
+ const update = useCallback((id, options) => {
2352
+ const subscriber = subscribersRef.current.get(id);
2353
+ if (!subscriber) {
2354
+ return;
2355
+ }
2356
+ subscriber.options = options;
2357
+ if (!options.enabled) {
2358
+ subscriber.listener(emptyEngineEvaluation());
2359
+ }
2360
+ else {
2361
+ const active = pickActive();
2362
+ if ((active === null || active === void 0 ? void 0 : active.id) === id) {
2363
+ subscriber.listener(analyzingForFen(options.fen, lastEvaluationRef.current));
2364
+ }
2365
+ }
2366
+ activeKeyRef.current = '';
2367
+ syncAnalysis();
2368
+ }, [pickActive, syncAnalysis]);
2369
+ const unregister = useCallback((id) => {
2370
+ subscribersRef.current.delete(id);
2371
+ activeKeyRef.current = '';
2372
+ syncAnalysis();
2373
+ }, [syncAnalysis]);
2374
+ const value = useMemo(() => ({
2375
+ register,
2376
+ update,
2377
+ unregister,
2378
+ }), [register, unregister, update]);
2379
+ return (jsx(AnalysisEngineContext.Provider, { value: value, children: children }));
2380
+ };
560
2381
 
561
2382
  const useAnalysisEngine = (fen, options = {}) => {
562
- const { enabled = true, depth = 16, multiPv = 2, scriptUrl = DEFAULT_STOCKFISH_SCRIPT_URL, } = options;
2383
+ var _a;
2384
+ const context = useAnalysisEngineContext();
2385
+ const useShared = ((_a = options.shared) !== null && _a !== void 0 ? _a : true) && context !== null;
2386
+ const { enabled = true, depth = 16, multiPv = 2, priority = 0, scriptUrl = DEFAULT_STOCKFISH_SCRIPT_URL, } = options;
563
2387
  const [evaluation, setEvaluation] = useState(emptyEngineEvaluation());
564
2388
  const [engineReady, setEngineReady] = useState(false);
565
2389
  const engineRef = useRef(null);
566
2390
  const mountGenerationRef = useRef(0);
2391
+ const subscriberIdRef = useRef(null);
2392
+ const subscriberOptions = useMemo(() => normalizeSubscriberOptions(fen, options), [fen, enabled, depth, multiPv, priority]);
2393
+ useLayoutEffect(() => {
2394
+ if (!useShared || !context) {
2395
+ return;
2396
+ }
2397
+ if (subscriberIdRef.current === null) {
2398
+ subscriberIdRef.current = context.register(subscriberOptions, setEvaluation);
2399
+ return;
2400
+ }
2401
+ context.update(subscriberIdRef.current, subscriberOptions);
2402
+ }, [context, subscriberOptions, useShared]);
567
2403
  useEffect(() => {
568
- if (!enabled || typeof Worker === 'undefined') {
569
- setEvaluation(emptyEngineEvaluation());
570
- setEngineReady(false);
2404
+ if (!useShared || !context) {
2405
+ return;
2406
+ }
2407
+ const contextValue = context;
2408
+ return () => {
2409
+ if (subscriberIdRef.current !== null) {
2410
+ contextValue.unregister(subscriberIdRef.current);
2411
+ subscriberIdRef.current = null;
2412
+ }
2413
+ };
2414
+ }, [context, useShared]);
2415
+ useEffect(() => {
2416
+ if (useShared || !enabled || typeof Worker === 'undefined') {
2417
+ if (!useShared && !enabled) {
2418
+ setEvaluation(emptyEngineEvaluation());
2419
+ setEngineReady(false);
2420
+ }
571
2421
  return;
572
2422
  }
573
2423
  const mountGeneration = ++mountGenerationRef.current;
@@ -603,9 +2453,9 @@ const useAnalysisEngine = (fen, options = {}) => {
603
2453
  engineRef.current = null;
604
2454
  }
605
2455
  };
606
- }, [enabled, scriptUrl]);
2456
+ }, [enabled, scriptUrl, useShared]);
607
2457
  useLayoutEffect(() => {
608
- if (!enabled || !engineReady || !engineRef.current) {
2458
+ if (useShared || !enabled || !engineReady || !engineRef.current) {
609
2459
  return;
610
2460
  }
611
2461
  const engine = engineRef.current;
@@ -615,7 +2465,7 @@ const useAnalysisEngine = (fen, options = {}) => {
615
2465
  return () => {
616
2466
  window.clearTimeout(timer);
617
2467
  };
618
- }, [enabled, engineReady, fen, depth, multiPv]);
2468
+ }, [useShared, enabled, engineReady, fen, depth, multiPv]);
619
2469
  return useMemo(() => {
620
2470
  if (evaluation.fen !== fen) {
621
2471
  return Object.assign(Object.assign({}, emptyEngineEvaluation()), { status: evaluation.status === 'error'
@@ -700,6 +2550,147 @@ class AnalysisErrorBoundary extends Component {
700
2550
  }
701
2551
  }
702
2552
 
2553
+ const navRowStyle = {
2554
+ display: 'flex',
2555
+ alignItems: 'center',
2556
+ gap: 6,
2557
+ };
2558
+ const scrubberInputStyle = {
2559
+ flex: 1,
2560
+ };
2561
+ const plyLabelStyle = {
2562
+ minWidth: 56,
2563
+ textAlign: 'center',
2564
+ fontSize: 14,
2565
+ };
2566
+ function palette(theme) {
2567
+ return {
2568
+ text: theme === 'dark' ? '#e8e8e8' : '#1a1a1a',
2569
+ border: theme === 'dark' ? '#3a3a3a' : '#d0d0d0',
2570
+ surface: theme === 'dark' ? '#262626' : '#f5f5f5',
2571
+ };
2572
+ }
2573
+ function navButtonStyle(colors) {
2574
+ return {
2575
+ padding: '4px 10px',
2576
+ borderRadius: 6,
2577
+ cursor: 'pointer',
2578
+ fontSize: 14,
2579
+ fontWeight: 600,
2580
+ border: `1px solid ${colors.border}`,
2581
+ background: colors.surface,
2582
+ color: colors.text,
2583
+ };
2584
+ }
2585
+
2586
+ /** Library-default ply navigation (inline styles). */
2587
+ const DefaultPlyNavigation = ({ plyIndex, totalPly, canPrev, canNext, onGoFirst, onGoPrev, onGoNext, onGoLast, onGoTo, theme, showScrubber, showPlyLabel, }) => {
2588
+ const colors = palette(theme);
2589
+ const buttonStyle = navButtonStyle(colors);
2590
+ return (jsxs("div", { style: navRowStyle, children: [jsx("button", { type: "button", onClick: onGoFirst, disabled: !canPrev, style: buttonStyle, "aria-label": "First move", children: "\u23EE" }), jsx("button", { type: "button", onClick: onGoPrev, disabled: !canPrev, style: buttonStyle, "aria-label": "Previous move", children: "\u25C0" }), showScrubber ? (jsx("input", { type: "range", min: 0, max: totalPly, value: plyIndex, onChange: (e) => onGoTo(Number(e.target.value)), style: scrubberInputStyle, "aria-label": "Scrub through game" })) : showPlyLabel ? (jsxs("span", { style: Object.assign(Object.assign({}, plyLabelStyle), { color: colors.text }), children: [plyIndex, " / ", totalPly] })) : null, jsx("button", { type: "button", onClick: onGoNext, disabled: !canNext, style: buttonStyle, "aria-label": "Next move", children: "\u25B6" }), jsx("button", { type: "button", onClick: onGoLast, disabled: !canNext, style: buttonStyle, "aria-label": "Last move", children: "\u23ED" })] }));
2591
+ };
2592
+ const defaultRenderPlyNavigation = (props) => (jsx(DefaultPlyNavigation, Object.assign({}, props)));
2593
+
2594
+ /** True when the event target is a field where arrow keys should type, not navigate. */
2595
+ function isEditableKeyboardTarget(target) {
2596
+ if (!(target instanceof HTMLElement)) {
2597
+ return false;
2598
+ }
2599
+ if (target.isContentEditable) {
2600
+ return true;
2601
+ }
2602
+ const tag = target.tagName;
2603
+ return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT';
2604
+ }
2605
+
2606
+ /**
2607
+ * Global keyboard shortcuts for browsing positions:
2608
+ * - ArrowLeft: previous
2609
+ * - ArrowRight: next
2610
+ * - Home: first (when {@link PositionKeyboardNavOptions.onFirst} is provided)
2611
+ * - End: last (when {@link PositionKeyboardNavOptions.onLast} is provided)
2612
+ *
2613
+ * Ignores keypresses while focus is in an input, textarea, select, or
2614
+ * contenteditable element, and ignores modified keys (Alt/Ctrl/Meta).
2615
+ */
2616
+ function usePositionKeyboardNav({ enabled = true, canPrev, canNext, onPrev, onNext, onFirst, onLast, }) {
2617
+ useEffect(() => {
2618
+ if (!enabled) {
2619
+ return;
2620
+ }
2621
+ const handleKeyDown = (event) => {
2622
+ if (isEditableKeyboardTarget(event.target)) {
2623
+ return;
2624
+ }
2625
+ if (event.altKey || event.ctrlKey || event.metaKey) {
2626
+ return;
2627
+ }
2628
+ switch (event.key) {
2629
+ case 'ArrowLeft':
2630
+ if (!canPrev) {
2631
+ return;
2632
+ }
2633
+ event.preventDefault();
2634
+ onPrev();
2635
+ break;
2636
+ case 'ArrowRight':
2637
+ if (!canNext) {
2638
+ return;
2639
+ }
2640
+ event.preventDefault();
2641
+ onNext();
2642
+ break;
2643
+ case 'Home':
2644
+ if (!onFirst || !canPrev) {
2645
+ return;
2646
+ }
2647
+ event.preventDefault();
2648
+ onFirst();
2649
+ break;
2650
+ case 'End':
2651
+ if (!onLast || !canNext) {
2652
+ return;
2653
+ }
2654
+ event.preventDefault();
2655
+ onLast();
2656
+ break;
2657
+ }
2658
+ };
2659
+ window.addEventListener('keydown', handleKeyDown);
2660
+ return () => window.removeEventListener('keydown', handleKeyDown);
2661
+ }, [enabled, canPrev, canNext, onPrev, onNext, onFirst, onLast]);
2662
+ }
2663
+
2664
+ /**
2665
+ * Step through a fixed move list. Omit {@link PlyNavigationProps.renderPlyNavigation}
2666
+ * for the default inline-styled UI, or pass a custom renderer (e.g. MUI controls).
2667
+ */
2668
+ const PlyNavigation = ({ plyIndex, totalPly, canPrev, canNext, onGoFirst, onGoPrev, onGoNext, onGoLast, onGoTo, theme = 'dark', keyboardNav = true, showScrubber = true, showPlyLabel, renderPlyNavigation = defaultRenderPlyNavigation, }) => {
2669
+ usePositionKeyboardNav({
2670
+ enabled: keyboardNav,
2671
+ canPrev,
2672
+ canNext,
2673
+ onPrev: onGoPrev,
2674
+ onNext: onGoNext,
2675
+ onFirst: onGoFirst,
2676
+ onLast: onGoLast,
2677
+ });
2678
+ return renderPlyNavigation({
2679
+ plyIndex,
2680
+ totalPly,
2681
+ canPrev,
2682
+ canNext,
2683
+ onGoFirst,
2684
+ onGoPrev,
2685
+ onGoNext,
2686
+ onGoLast,
2687
+ onGoTo,
2688
+ theme,
2689
+ showScrubber,
2690
+ showPlyLabel: showPlyLabel !== null && showPlyLabel !== void 0 ? showPlyLabel : !showScrubber,
2691
+ });
2692
+ };
2693
+
703
2694
  /** Draggable analysis board (no surrounding layout chrome). */
704
2695
  const AnalysisChessboardView = ({ model }) => {
705
2696
  var _a;
@@ -1053,12 +3044,28 @@ const useAnalysisBoardModel = ({ analysisContext, onClose, theme, boardWidth, en
1053
3044
  * No layout divs — use {@link renderMain} (e.g. `AnalysisBoardLayout` from `analysis/defaults` or a host layout).
1054
3045
  */
1055
3046
  const AnalysisBoardCore = (_a) => {
1056
- var { renderContainer, renderMain, renderSidebar, renderEngineEvaluation } = _a, modelArgs = __rest(_a, ["renderContainer", "renderMain", "renderSidebar", "renderEngineEvaluation"]);
3047
+ var { renderContainer, renderMain, renderSidebar, renderEngineEvaluation, keyboardNav = true } = _a, modelArgs = __rest(_a, ["renderContainer", "renderMain", "renderSidebar", "renderEngineEvaluation", "keyboardNav"]);
1057
3048
  const model = useAnalysisBoardModel(modelArgs);
1058
- return (jsx(AnalysisBoardCoreView, { model: model, renderContainer: renderContainer, renderMain: renderMain, renderSidebar: renderSidebar, renderEngineEvaluation: renderEngineEvaluation }));
3049
+ return (jsx(AnalysisBoardCoreView, { model: model, keyboardNav: keyboardNav, renderContainer: renderContainer, renderMain: renderMain, renderSidebar: renderSidebar, renderEngineEvaluation: renderEngineEvaluation }));
1059
3050
  };
1060
3051
  /** Pure composition (no layout styles) for testing and reuse. */
1061
- const AnalysisBoardCoreView = ({ model, renderContainer, renderMain, renderSidebar, renderEngineEvaluation, }) => {
3052
+ const AnalysisBoardCoreView = ({ model, keyboardNav, renderContainer, renderMain, renderSidebar, renderEngineEvaluation, }) => {
3053
+ const { ply, maxPly, onSelectPly } = model;
3054
+ const canPrev = ply > 0;
3055
+ const canNext = ply < maxPly;
3056
+ const goFirst = useCallback(() => onSelectPly(0), [onSelectPly]);
3057
+ const goPrev = useCallback(() => onSelectPly(ply - 1), [onSelectPly, ply]);
3058
+ const goNext = useCallback(() => onSelectPly(ply + 1), [onSelectPly, ply]);
3059
+ const goLast = useCallback(() => onSelectPly(maxPly), [maxPly, onSelectPly]);
3060
+ usePositionKeyboardNav({
3061
+ enabled: keyboardNav,
3062
+ canPrev,
3063
+ canNext,
3064
+ onPrev: goPrev,
3065
+ onNext: goNext,
3066
+ onFirst: goFirst,
3067
+ onLast: goLast,
3068
+ });
1062
3069
  const board = jsx(AnalysisChessboardView, { model: model });
1063
3070
  const engineEvaluationPanel = model.engineEnabled
1064
3071
  ? renderEngineEvaluation({
@@ -1326,66 +3333,6 @@ const closeButtonStyle = {
1326
3333
  fontSize: 14,
1327
3334
  };
1328
3335
 
1329
- const navRowStyle = {
1330
- display: 'flex',
1331
- alignItems: 'center',
1332
- gap: 6,
1333
- };
1334
- const scrubberInputStyle = {
1335
- flex: 1,
1336
- };
1337
- const plyLabelStyle = {
1338
- minWidth: 56,
1339
- textAlign: 'center',
1340
- fontSize: 14,
1341
- };
1342
- function palette(theme) {
1343
- return {
1344
- text: theme === 'dark' ? '#e8e8e8' : '#1a1a1a',
1345
- border: theme === 'dark' ? '#3a3a3a' : '#d0d0d0',
1346
- surface: theme === 'dark' ? '#262626' : '#f5f5f5',
1347
- };
1348
- }
1349
- function navButtonStyle(colors) {
1350
- return {
1351
- padding: '4px 10px',
1352
- borderRadius: 6,
1353
- cursor: 'pointer',
1354
- fontSize: 14,
1355
- fontWeight: 600,
1356
- border: `1px solid ${colors.border}`,
1357
- background: colors.surface,
1358
- color: colors.text,
1359
- };
1360
- }
1361
-
1362
- /** Library-default ply navigation (inline styles). */
1363
- const DefaultPlyNavigation = ({ plyIndex, totalPly, canPrev, canNext, onGoFirst, onGoPrev, onGoNext, onGoLast, onGoTo, theme, showScrubber, showPlyLabel, }) => {
1364
- const colors = palette(theme);
1365
- const buttonStyle = navButtonStyle(colors);
1366
- return (jsxs("div", { style: navRowStyle, children: [jsx("button", { type: "button", onClick: onGoFirst, disabled: !canPrev, style: buttonStyle, "aria-label": "First move", children: "\u23EE" }), jsx("button", { type: "button", onClick: onGoPrev, disabled: !canPrev, style: buttonStyle, "aria-label": "Previous move", children: "\u25C0" }), showScrubber ? (jsx("input", { type: "range", min: 0, max: totalPly, value: plyIndex, onChange: (e) => onGoTo(Number(e.target.value)), style: scrubberInputStyle, "aria-label": "Scrub through game" })) : showPlyLabel ? (jsxs("span", { style: Object.assign(Object.assign({}, plyLabelStyle), { color: colors.text }), children: [plyIndex, " / ", totalPly] })) : null, jsx("button", { type: "button", onClick: onGoNext, disabled: !canNext, style: buttonStyle, "aria-label": "Next move", children: "\u25B6" }), jsx("button", { type: "button", onClick: onGoLast, disabled: !canNext, style: buttonStyle, "aria-label": "Last move", children: "\u23ED" })] }));
1367
- };
1368
- const defaultRenderPlyNavigation = (props) => (jsx(DefaultPlyNavigation, Object.assign({}, props)));
1369
-
1370
- /**
1371
- * Step through a fixed move list. Omit {@link PlyNavigationProps.renderPlyNavigation}
1372
- * for the default inline-styled UI, or pass a custom renderer (e.g. MUI controls).
1373
- */
1374
- const PlyNavigation = ({ plyIndex, totalPly, canPrev, canNext, onGoFirst, onGoPrev, onGoNext, onGoLast, onGoTo, theme = 'dark', showScrubber = true, showPlyLabel, renderPlyNavigation = defaultRenderPlyNavigation, }) => renderPlyNavigation({
1375
- plyIndex,
1376
- totalPly,
1377
- canPrev,
1378
- canNext,
1379
- onGoFirst,
1380
- onGoPrev,
1381
- onGoNext,
1382
- onGoLast,
1383
- onGoTo,
1384
- theme,
1385
- showScrubber,
1386
- showPlyLabel: showPlyLabel !== null && showPlyLabel !== void 0 ? showPlyLabel : !showScrubber,
1387
- });
1388
-
1389
3336
  const DefaultAnalysisSidebar = ({ historyRows, isHistoryRowSelected, onSelectHistoryRow, ply, maxPly, onSelectPly, theme, engineEvaluationPanel, }) => {
1390
3337
  const rowBands = createSidebarRowBandCounters();
1391
3338
  const baseChipStyle = {
@@ -1393,7 +3340,7 @@ const DefaultAnalysisSidebar = ({ historyRows, isHistoryRowSelected, onSelectHis
1393
3340
  padding: '4px 8px',
1394
3341
  borderRadius: 4,
1395
3342
  };
1396
- return (jsxs("div", { style: sidebarStyle, children: [jsxs("div", { style: navBlockStyle, children: [jsx(PlyNavigation, { plyIndex: ply, totalPly: maxPly, canPrev: ply > 0, canNext: ply < maxPly, onGoFirst: () => onSelectPly(0), onGoPrev: () => onSelectPly(ply - 1), onGoNext: () => onSelectPly(ply + 1), onGoLast: () => onSelectPly(maxPly), onGoTo: onSelectPly, theme: theme, showScrubber: false }), jsx("p", { style: sectionTitleStyle, children: "Move history" })] }), jsxs("div", { style: contentRowStyle, children: [jsx("ol", { style: moveListStyle, children: historyRows.length === 0 ? (jsx("li", { style: emptyRowStyle, children: "No moves played yet." })) : (historyRows.map((row) => {
3343
+ return (jsxs("div", { style: sidebarStyle, children: [jsxs("div", { style: navBlockStyle, children: [jsx(PlyNavigation, { plyIndex: ply, totalPly: maxPly, canPrev: ply > 0, canNext: ply < maxPly, onGoFirst: () => onSelectPly(0), onGoPrev: () => onSelectPly(ply - 1), onGoNext: () => onSelectPly(ply + 1), onGoLast: () => onSelectPly(maxPly), onGoTo: onSelectPly, theme: theme, keyboardNav: false, showScrubber: false }), jsx("p", { style: sectionTitleStyle, children: "Move history" })] }), jsxs("div", { style: contentRowStyle, children: [jsx("ol", { style: moveListStyle, "aria-label": "Move history", children: historyRows.length === 0 ? (jsx("li", { style: emptyRowStyle, children: "No moves played yet." })) : (historyRows.map((row) => {
1397
3344
  const isSelected = isHistoryRowSelected(row);
1398
3345
  const isVariation = row.kind === 'variation';
1399
3346
  const backgroundColor = isSelected
@@ -1492,4 +3439,374 @@ const AnalysisBoard = (_a) => {
1492
3439
  : () => null) })));
1493
3440
  };
1494
3441
 
1495
- export { AnalysisBoard, AnalysisBoardCore, AnalysisBoardCoreView, AnalysisBoardLayout, AnalysisChessboardView, AnalysisErrorBoundary, AnalysisPosition, ChessboardThemeContext, DEFAULT_ANALYSIS_LAYOUT, DEFAULT_STOCKFISH_SCRIPT_URL, DefaultAnalysisContainer, DefaultAnalysisSidebar, DefaultPlyNavigation, EngineEvaluationPanel, HighlightChessboard, PlyNavigation, StockfishBrowserEngine, ThemeProvider, analysisBoardHighlightColors, analysisSidebarColors, applyUciMove, boardSquareHighlightColors, createSidebarRowBandCounters, defaultRenderPlyNavigation, emptyEngineEvaluation, formatEvaluation, formatPvPreview, getAnalysisModalStyles, getCheckSquareFromChess, getLastMoveSquareStyles, getSidebarRowBackground, getStylesForTheme, isAnalyzableFen, navButtonStyle, navRowStyle, normalizeEvalForWhite, normalizePvMoves, parseUciInfoLine, parseUciMove, plyLabelStyle, palette as plyNavigationPalette, resolveStockfishScriptUrl, resolveStockfishWasmUrl, resolveStockfishWorkerUrl, scrubberInputStyle, splitWorkerLines, uciPvToSan, useAnalysisBoardModel, useAnalysisEngine, useChessboardTheme, useTheme };
3442
+ /** Resolve a board drag into a legal UCI string, or null when illegal. */
3443
+ function uciFromDrop(fen, sourceSquare, targetSquare, piece) {
3444
+ var _a, _b;
3445
+ const chess = new Chess(fen);
3446
+ const pieceType = (_a = piece[1]) === null || _a === void 0 ? void 0 : _a.toLowerCase();
3447
+ const legal = chess
3448
+ .moves({ square: sourceSquare, verbose: true })
3449
+ .find((move) => move.to === targetSquare &&
3450
+ (!move.promotion || move.promotion === pieceType));
3451
+ if (!legal)
3452
+ return null;
3453
+ return `${legal.from}${legal.to}${(_b = legal.promotion) !== null && _b !== void 0 ? _b : ''}`;
3454
+ }
3455
+ function matchesExpectedUci(uci, expectedUci) {
3456
+ return uci.toLowerCase() === expectedUci.toLowerCase();
3457
+ }
3458
+
3459
+ /**
3460
+ * Evaluate a training drop without mutating board position.
3461
+ * Returns `false` for incorrect attempts so react-chessboard snaps the piece back.
3462
+ */
3463
+ function evaluateExpectedMoveDrop(fen, sourceSquare, targetSquare, piece, expectedUci, enabled) {
3464
+ if (!enabled || !expectedUci) {
3465
+ return { kind: 'ignored' };
3466
+ }
3467
+ const uci = uciFromDrop(fen, sourceSquare, targetSquare, piece);
3468
+ if (!uci) {
3469
+ return { kind: 'illegal' };
3470
+ }
3471
+ if (matchesExpectedUci(uci, expectedUci)) {
3472
+ return { kind: 'correct', uci };
3473
+ }
3474
+ return { kind: 'incorrect', uci };
3475
+ }
3476
+ function createExpectedMoveDropHandler({ fen, expectedUci, enabled, onCorrect, onIncorrect, }) {
3477
+ return (sourceSquare, targetSquare, piece) => {
3478
+ const result = evaluateExpectedMoveDrop(fen, sourceSquare, targetSquare, piece, expectedUci, enabled);
3479
+ switch (result.kind) {
3480
+ case 'correct':
3481
+ onCorrect(result.uci);
3482
+ return true;
3483
+ case 'incorrect':
3484
+ onIncorrect(result.uci);
3485
+ return false;
3486
+ default:
3487
+ return false;
3488
+ }
3489
+ };
3490
+ }
3491
+
3492
+ /**
3493
+ * Bump the revision counter to force a controlled chessboard re-render after a
3494
+ * rejected drop. Pair with returning `false` from `onPieceDrop` so the board
3495
+ * snaps back without changing the controlled `position` FEN.
3496
+ */
3497
+ function useBoardRevision() {
3498
+ const [revision, setRevision] = useState(0);
3499
+ const bumpRevision = useCallback(() => {
3500
+ setRevision((current) => current + 1);
3501
+ }, []);
3502
+ return { revision, bumpRevision };
3503
+ }
3504
+
3505
+ /** Minimum eval loss (pawns) from the wrong move before showing a refutation. */
3506
+ const REFUTATION_EVAL_GAP_PAWNS = 0.5;
3507
+ const REFUTATION_EVAL_GAP_CP = REFUTATION_EVAL_GAP_PAWNS * 100;
3508
+ const refutationEngineOptions = {
3509
+ depth: 14,
3510
+ multiPv: 1,
3511
+ };
3512
+ function fenAfterUci(fen, uci) {
3513
+ const chess = new Chess(fen);
3514
+ if (!applyUciMove(chess, uci)) {
3515
+ return null;
3516
+ }
3517
+ return chess.fen();
3518
+ }
3519
+ /** Centipawn score from side to move, comparable across sibling positions. */
3520
+ function lineEvalCpForGap(line) {
3521
+ if (!line) {
3522
+ return null;
3523
+ }
3524
+ if (line.mate !== null) {
3525
+ return line.mate > 0 ? 10000 - line.mate : -1e4 + line.mate;
3526
+ }
3527
+ return line.centipawns;
3528
+ }
3529
+ /** How much better the opponent's eval is after the wrong move vs the correct one. */
3530
+ function refutationEvalGapCp(evalAfterWrong, evalAfterCorrect) {
3531
+ const wrongCp = lineEvalCpForGap(evalAfterWrong.lines[0]);
3532
+ const correctCp = lineEvalCpForGap(evalAfterCorrect.lines[0]);
3533
+ if (wrongCp === null || correctCp === null) {
3534
+ return null;
3535
+ }
3536
+ return wrongCp - correctCp;
3537
+ }
3538
+ function refutationFromEvaluation(fenAfterWrong, evaluation, evalGapCp, evalGapApplies, evalGapLoading) {
3539
+ var _a, _b, _c, _d, _e, _f, _g;
3540
+ const loading = evaluation.status === 'loading' ||
3541
+ evaluation.status === 'analyzing' ||
3542
+ evalGapLoading;
3543
+ if (evaluation.status === 'error') {
3544
+ return {
3545
+ refutationUci: null,
3546
+ refutationSan: null,
3547
+ refutationLine: null,
3548
+ loading: false,
3549
+ error: (_a = evaluation.error) !== null && _a !== void 0 ? _a : 'Engine unavailable',
3550
+ };
3551
+ }
3552
+ const meetsThreshold = !evalGapApplies ||
3553
+ (evalGapCp !== null && evalGapCp >= REFUTATION_EVAL_GAP_CP);
3554
+ if (!meetsThreshold) {
3555
+ return {
3556
+ refutationUci: null,
3557
+ refutationSan: null,
3558
+ refutationLine: null,
3559
+ loading,
3560
+ error: null,
3561
+ };
3562
+ }
3563
+ const refutationUci = (_d = (_c = (_b = evaluation.lines[0]) === null || _b === void 0 ? void 0 : _b.pv) === null || _c === void 0 ? void 0 : _c[0]) !== null && _d !== void 0 ? _d : null;
3564
+ const refutationSan = refutationUci
3565
+ ? ((_e = uciPvToSan(fenAfterWrong, [refutationUci])[0]) !== null && _e !== void 0 ? _e : refutationUci)
3566
+ : null;
3567
+ const refutationLine = ((_g = (_f = evaluation.lines[0]) === null || _f === void 0 ? void 0 : _f.pv) === null || _g === void 0 ? void 0 : _g.length)
3568
+ ? formatPvPreview(fenAfterWrong, evaluation.lines[0].pv, 4)
3569
+ : null;
3570
+ return {
3571
+ refutationUci,
3572
+ refutationSan,
3573
+ refutationLine,
3574
+ loading,
3575
+ error: null,
3576
+ };
3577
+ }
3578
+
3579
+ const MISS_WRONG_PAUSE_MS = 450;
3580
+ const MISS_REFUTATION_PAUSE_MS = 900;
3581
+ const MISS_REFUTATION_MAX_WAIT_MS = 4000;
3582
+ const MISS_MOVE_ANIMATION_MS = 220;
3583
+ function moveArrow(uci, color) {
3584
+ if (!uci || uci.length < 4) {
3585
+ return [];
3586
+ }
3587
+ return [[uci.slice(0, 2), uci.slice(2, 4), color]];
3588
+ }
3589
+ function expectedMoveArrow(expectedUci, color) {
3590
+ return moveArrow(expectedUci, color);
3591
+ }
3592
+ function getMissDisplay(sequence, expectedUci, refutationUci, answerArrowColor) {
3593
+ var _a;
3594
+ if (!sequence) {
3595
+ return {
3596
+ fen: null,
3597
+ arrows: [],
3598
+ animating: false,
3599
+ };
3600
+ }
3601
+ const { setupFen, attemptedUci, phase } = sequence;
3602
+ const fenAfterWrong = fenAfterUci(setupFen, attemptedUci);
3603
+ switch (phase) {
3604
+ case 'wrong':
3605
+ return {
3606
+ fen: fenAfterWrong !== null && fenAfterWrong !== void 0 ? fenAfterWrong : setupFen,
3607
+ arrows: [],
3608
+ animating: false,
3609
+ };
3610
+ case 'refutation': {
3611
+ const fenAfterRefutation = fenAfterWrong && refutationUci
3612
+ ? fenAfterUci(fenAfterWrong, refutationUci)
3613
+ : null;
3614
+ return {
3615
+ fen: (_a = fenAfterRefutation !== null && fenAfterRefutation !== void 0 ? fenAfterRefutation : fenAfterWrong) !== null && _a !== void 0 ? _a : setupFen,
3616
+ arrows: [],
3617
+ animating: Boolean(fenAfterRefutation),
3618
+ };
3619
+ }
3620
+ case 'retry':
3621
+ return {
3622
+ fen: setupFen,
3623
+ arrows: [],
3624
+ animating: false,
3625
+ };
3626
+ case 'answer':
3627
+ return {
3628
+ fen: setupFen,
3629
+ arrows: expectedMoveArrow(expectedUci, answerArrowColor),
3630
+ animating: false,
3631
+ };
3632
+ default:
3633
+ return {
3634
+ fen: setupFen,
3635
+ arrows: [],
3636
+ animating: false,
3637
+ };
3638
+ }
3639
+ }
3640
+
3641
+ function useMissRefutation(setupFen, attemptedUci, expectedUci, enabled, engineOptions) {
3642
+ const fenAfterWrong = useMemo(() => {
3643
+ if (!setupFen || !attemptedUci) {
3644
+ return null;
3645
+ }
3646
+ return fenAfterUci(setupFen, attemptedUci);
3647
+ }, [setupFen, attemptedUci]);
3648
+ const fenAfterCorrect = useMemo(() => {
3649
+ if (!setupFen || !expectedUci) {
3650
+ return null;
3651
+ }
3652
+ return fenAfterUci(setupFen, expectedUci);
3653
+ }, [setupFen, expectedUci]);
3654
+ const wrongEvaluation = useAnalysisEngine(fenAfterWrong !== null && fenAfterWrong !== void 0 ? fenAfterWrong : '', Object.assign(Object.assign({}, engineOptions), { enabled: enabled && Boolean(fenAfterWrong), shared: false }));
3655
+ const correctEvaluation = useAnalysisEngine(fenAfterCorrect !== null && fenAfterCorrect !== void 0 ? fenAfterCorrect : '', Object.assign(Object.assign({}, engineOptions), { enabled: enabled && Boolean(fenAfterCorrect), shared: false }));
3656
+ return useMemo(() => {
3657
+ if (!fenAfterWrong) {
3658
+ return {
3659
+ fenAfterWrong: null,
3660
+ refutationUci: null,
3661
+ refutationSan: null,
3662
+ refutationLine: null,
3663
+ loading: false,
3664
+ error: null,
3665
+ };
3666
+ }
3667
+ const evalGapApplies = Boolean(fenAfterCorrect);
3668
+ const evalGapCp = evalGapApplies
3669
+ ? refutationEvalGapCp(wrongEvaluation, correctEvaluation)
3670
+ : null;
3671
+ const evalGapLoading = evalGapApplies &&
3672
+ evalGapCp === null &&
3673
+ wrongEvaluation.status !== 'error' &&
3674
+ correctEvaluation.status !== 'error' &&
3675
+ (correctEvaluation.status === 'loading' ||
3676
+ correctEvaluation.status === 'analyzing' ||
3677
+ wrongEvaluation.status === 'loading' ||
3678
+ wrongEvaluation.status === 'analyzing');
3679
+ return Object.assign({ fenAfterWrong }, refutationFromEvaluation(fenAfterWrong, wrongEvaluation, evalGapCp, evalGapApplies, evalGapLoading));
3680
+ }, [fenAfterCorrect, fenAfterWrong, correctEvaluation, wrongEvaluation]);
3681
+ }
3682
+
3683
+ function useMissSequence(feedback, expectedUci, engineOptions, answerArrowColor, autoShowWrongMoves) {
3684
+ var _a, _b;
3685
+ const [sequence, setSequence] = useState(null);
3686
+ const refutation = useMissRefutation((_a = sequence === null || sequence === void 0 ? void 0 : sequence.setupFen) !== null && _a !== void 0 ? _a : null, (_b = sequence === null || sequence === void 0 ? void 0 : sequence.attemptedUci) !== null && _b !== void 0 ? _b : null, expectedUci, sequence != null, engineOptions);
3687
+ const startSequence = useCallback((setupFen, attemptedUci) => {
3688
+ setSequence({
3689
+ setupFen,
3690
+ attemptedUci,
3691
+ phase: autoShowWrongMoves ? 'wrong' : 'retry',
3692
+ });
3693
+ }, [autoShowWrongMoves]);
3694
+ const clearSequence = useCallback(() => {
3695
+ setSequence(null);
3696
+ }, []);
3697
+ const prevFeedbackRef = useRef(feedback);
3698
+ useEffect(() => {
3699
+ const prevFeedback = prevFeedbackRef.current;
3700
+ prevFeedbackRef.current = feedback;
3701
+ if (prevFeedback === 'incorrect' && feedback !== 'incorrect') {
3702
+ setSequence(null);
3703
+ }
3704
+ }, [feedback]);
3705
+ useEffect(() => {
3706
+ if (!sequence || sequence.phase !== 'wrong' || !autoShowWrongMoves) {
3707
+ return undefined;
3708
+ }
3709
+ if (refutation.loading) {
3710
+ const maxWait = window.setTimeout(() => {
3711
+ setSequence((current) => (current === null || current === void 0 ? void 0 : current.phase) === 'wrong' ? Object.assign(Object.assign({}, current), { phase: 'answer' }) : current);
3712
+ }, MISS_REFUTATION_MAX_WAIT_MS);
3713
+ return () => window.clearTimeout(maxWait);
3714
+ }
3715
+ const delay = window.setTimeout(() => {
3716
+ setSequence((current) => {
3717
+ if (!current || current.phase !== 'wrong') {
3718
+ return current;
3719
+ }
3720
+ return Object.assign(Object.assign({}, current), { phase: refutation.refutationUci ? 'refutation' : 'answer' });
3721
+ });
3722
+ }, MISS_WRONG_PAUSE_MS);
3723
+ return () => window.clearTimeout(delay);
3724
+ }, [
3725
+ autoShowWrongMoves,
3726
+ refutation.loading,
3727
+ refutation.refutationUci,
3728
+ sequence,
3729
+ ]);
3730
+ useEffect(() => {
3731
+ if (!sequence || sequence.phase !== 'refutation') {
3732
+ return undefined;
3733
+ }
3734
+ const delay = window.setTimeout(() => {
3735
+ setSequence((current) => (current === null || current === void 0 ? void 0 : current.phase) === 'refutation'
3736
+ ? Object.assign(Object.assign({}, current), { phase: 'answer' }) : current);
3737
+ }, MISS_REFUTATION_PAUSE_MS);
3738
+ return () => window.clearTimeout(delay);
3739
+ }, [sequence]);
3740
+ const display = useMemo(() => getMissDisplay(sequence, expectedUci, refutation.refutationUci, answerArrowColor), [
3741
+ answerArrowColor,
3742
+ expectedUci,
3743
+ refutation.refutationUci,
3744
+ sequence,
3745
+ ]);
3746
+ return {
3747
+ sequence,
3748
+ refutation,
3749
+ display,
3750
+ startSequence,
3751
+ clearSequence,
3752
+ };
3753
+ }
3754
+
3755
+ function useMissBoard({ feedback, expectedUci, positionFen, answerArrowColor, autoShowWrongMoves = true, engineOptions, }) {
3756
+ var _a;
3757
+ const refutationEngine = useMemo(() => (Object.assign(Object.assign({}, refutationEngineOptions), engineOptions)), [engineOptions]);
3758
+ const missSequence = useMissSequence(feedback, expectedUci, refutationEngine, answerArrowColor, autoShowWrongMoves);
3759
+ const customArrows = useMemo(() => {
3760
+ if (feedback !== 'incorrect') {
3761
+ return [];
3762
+ }
3763
+ if (missSequence.sequence) {
3764
+ return missSequence.display.arrows;
3765
+ }
3766
+ if (expectedUci) {
3767
+ return [
3768
+ [
3769
+ expectedUci.slice(0, 2),
3770
+ expectedUci.slice(2, 4),
3771
+ answerArrowColor,
3772
+ ],
3773
+ ];
3774
+ }
3775
+ return [];
3776
+ }, [
3777
+ answerArrowColor,
3778
+ expectedUci,
3779
+ feedback,
3780
+ missSequence.display.arrows,
3781
+ missSequence.sequence,
3782
+ ]);
3783
+ const boardPosition = (_a = missSequence.display.fen) !== null && _a !== void 0 ? _a : positionFen;
3784
+ const wrapDropHandler = useCallback((onDrop, { enabled, dropFen = boardPosition, expectedMoveUci = expectedUci, }) => (source, target, piece) => {
3785
+ if (enabled && expectedMoveUci) {
3786
+ const uci = uciFromDrop(dropFen, source, target, piece);
3787
+ if (uci && uci.toLowerCase() !== expectedMoveUci.toLowerCase()) {
3788
+ missSequence.startSequence(dropFen, uci);
3789
+ }
3790
+ else if (uci &&
3791
+ uci.toLowerCase() === expectedMoveUci.toLowerCase()) {
3792
+ missSequence.clearSequence();
3793
+ }
3794
+ }
3795
+ return onDrop(source, target, piece);
3796
+ }, [
3797
+ boardPosition,
3798
+ expectedUci,
3799
+ missSequence.clearSequence,
3800
+ missSequence.startSequence,
3801
+ ]);
3802
+ return {
3803
+ missSequence,
3804
+ refutation: missSequence.refutation,
3805
+ customArrows,
3806
+ boardPosition,
3807
+ boardAnimating: missSequence.display.animating,
3808
+ wrapDropHandler,
3809
+ };
3810
+ }
3811
+
3812
+ export { AnalysisBoard, AnalysisBoardCore, AnalysisBoardCoreView, AnalysisBoardLayout, AnalysisChessboardView, AnalysisEngineProvider, AnalysisErrorBoundary, AnalysisPosition, BOARD_THEMES, BOARD_THEME_IDS, ChessboardDnDProvider, ChessboardThemeContext, DEFAULT_ANALYSIS_LAYOUT, DEFAULT_BOARD_THEME, DEFAULT_STOCKFISH_SCRIPT_URL, DefaultAnalysisContainer, DefaultAnalysisSidebar, DefaultPlyNavigation, EngineEvaluationPanel, HighlightChessboard, MISS_MOVE_ANIMATION_MS, MISS_REFUTATION_MAX_WAIT_MS, MISS_REFUTATION_PAUSE_MS, MISS_WRONG_PAUSE_MS, PlyNavigation, REFUTATION_EVAL_GAP_CP, REFUTATION_EVAL_GAP_PAWNS, StockfishBrowserEngine, ThemeProvider, analysisBoardHighlightColors, analysisSidebarColors, applyUciMove, boardSquareHighlightColors, boardThemeFromLegacyUiTheme, createExpectedMoveDropHandler, createSidebarRowBandCounters, defaultRenderPlyNavigation, emptyEngineEvaluation, evaluateExpectedMoveDrop, fenAfterUci, formatEvaluation, formatPvPreview, getAnalysisModalStyles, getBoardThemeStyles, getCheckSquareFromChess, getLastMoveSquareStyles, getMissDisplay, getSidebarRowBackground, getStylesForTheme, isAnalyzableFen, isBoardThemeId, isEditableKeyboardTarget, lineEvalCpForGap, matchesExpectedUci, navButtonStyle, navRowStyle, normalizeEvalForWhite, normalizePvMoves, normalizeSubscriberOptions, parseUciInfoLine, parseUciMove, plyLabelStyle, palette as plyNavigationPalette, refutationEngineOptions, refutationEvalGapCp, refutationFromEvaluation, resolveStockfishScriptUrl, resolveStockfishWasmUrl, resolveStockfishWorkerUrl, scrubberInputStyle, splitWorkerLines, uciFromDrop, uciPvToSan, useAnalysisBoardModel, useAnalysisEngine, useAnalysisEngineContext, useBoardRevision, useChessboardTheme, useMissBoard, useMissRefutation, useMissSequence, usePositionKeyboardNav, useTheme };