vue-pgn-viewer 0.2.1 → 0.3.0

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.
@@ -1,22 +1,110 @@
1
1
  import { Api } from 'chessground/api';
2
2
  import { Color } from 'chessops';
3
+ import { CommentShape } from 'chessops/pgn';
3
4
  import { ComponentOptionsMixin } from 'vue';
4
5
  import { ComponentProvideOptions } from 'vue';
5
6
  import { Config } from 'chessground/config';
6
7
  import { DefineComponent } from 'vue';
8
+ import { FEN } from 'chessground/types';
9
+ import { Move } from 'chessops';
10
+ import { Node as Node_2 } from 'chessops/pgn';
11
+ import { Position } from 'chessops';
7
12
  import { PublicProps } from 'vue';
8
13
 
14
+ declare type AnyNode = Node_2<MoveData>;
15
+
16
+ declare type Clocks = {
17
+ white?: number;
18
+ black?: number;
19
+ };
20
+
9
21
  declare type ComponentProps = {
10
22
  config?: PgnViewerConfig;
11
23
  };
12
24
 
25
+ declare type Game = {
26
+ mainline: MoveData[];
27
+ initial: Initial;
28
+ moves: AnyNode;
29
+ players: Players;
30
+ metadata: Metadata;
31
+ title(): string;
32
+ hasPlayerName(): boolean;
33
+ nodeAt(path: Path): AnyNode | undefined;
34
+ dataAt(path: Path): MoveData | Initial | undefined;
35
+ pathAtMainlinePly(ply: Ply | "last"): Path;
36
+ };
37
+
13
38
  declare type GoTo = "first" | "prev" | "next" | "last";
14
39
 
15
40
  declare type Id = string;
16
41
 
42
+ declare type Initial = InitialOrMove & {
43
+ pos: Position;
44
+ };
45
+
46
+ declare type InitialOrMove = {
47
+ fen: FEN;
48
+ turn: Color;
49
+ check: boolean;
50
+ comments: string[];
51
+ shapes: CommentShape[];
52
+ clocks: Clocks;
53
+ };
54
+
17
55
  declare type Lichess = string | false;
18
56
 
19
- declare type Pane = "board" | "menu" | "pgn";
57
+ declare type Metadata = {
58
+ externalLink?: string;
59
+ isLichess: boolean;
60
+ timeControl?: {
61
+ initial: number;
62
+ increment: number;
63
+ };
64
+ orientation?: Color;
65
+ result?: string;
66
+ };
67
+
68
+ declare type MoveData = InitialOrMove & {
69
+ path: Path;
70
+ ply: number;
71
+ move: Move;
72
+ san: San;
73
+ uci: Uci;
74
+ startingComments: string[];
75
+ nags: number[];
76
+ emt?: number;
77
+ };
78
+
79
+ declare type Options = {
80
+ pgn: string;
81
+ fen?: string;
82
+ chessground: Config;
83
+ orientation?: Color;
84
+ showPlayers: ShowPlayers;
85
+ showMoves: ShowMoves;
86
+ showClocks: boolean;
87
+ showControls: boolean;
88
+ initialPly: Ply | "last";
89
+ scrollToMove: boolean;
90
+ keyboardToMove: boolean;
91
+ drawArrows: boolean;
92
+ menu: {
93
+ getPgn: {
94
+ enabled?: boolean;
95
+ fileName?: string;
96
+ };
97
+ practiceWithComputer?: {
98
+ enabled?: boolean;
99
+ };
100
+ analysisBoard?: {
101
+ enabled?: boolean;
102
+ };
103
+ };
104
+ lichess: Lichess;
105
+ classes?: string;
106
+ translate?: Translate;
107
+ };
20
108
 
21
109
  declare type Path = {
22
110
  path: string;
@@ -37,16 +125,17 @@ ready: (api: PgnViewerApi) => any;
37
125
  }, string, PublicProps, Readonly<ComponentProps> & Readonly<{
38
126
  onReady?: ((api: PgnViewerApi) => any) | undefined;
39
127
  }>, {}, {}, {}, {}, string, ComponentProvideOptions, false, {
40
- board: HTMLDivElement;
128
+ div: HTMLDivElement;
41
129
  }, HTMLDivElement>;
42
130
 
43
131
  export declare type PgnViewerApi = {
132
+ game: Game;
44
133
  path: Path;
45
134
  translate: Translate;
46
- ground: Api;
135
+ ground?: Api;
47
136
  div?: HTMLElement;
48
137
  flipped: boolean;
49
- pane: Pane;
138
+ pane: string;
50
139
  autoScrollRequested: boolean;
51
140
  focus(): void;
52
141
  orientation(): string;
@@ -61,44 +150,30 @@ export declare type PgnViewerApi = {
61
150
  setGround(api: Api): void;
62
151
  };
63
152
 
64
- export declare type PgnViewerConfig = Partial<PgnViewerOptions>;
153
+ export declare type PgnViewerConfig = Partial<Options>;
65
154
 
66
- declare type PgnViewerOptions = {
67
- pgn: string;
68
- fen?: string;
69
- chessground: Config;
70
- orientation?: Color;
71
- showPlayers: ShowPlayers;
72
- showMoves: ShowMoves;
73
- showClocks: boolean;
74
- showControls: boolean;
75
- initialPly: Ply | "last";
76
- scrollToMove: boolean;
77
- keyboardToMove: boolean;
78
- drawArrows: boolean;
79
- menu: {
80
- getPgn: {
81
- enabled?: boolean;
82
- fileName?: string;
83
- };
84
- practiceWithComputer?: {
85
- enabled?: boolean;
86
- };
87
- analysisBoard?: {
88
- enabled?: boolean;
89
- };
90
- };
91
- lichess: Lichess;
92
- classes?: string;
93
- translate?: Translate;
155
+ declare type Player = {
156
+ name?: string;
157
+ title?: string;
158
+ rating?: number;
159
+ isLichessUser: boolean;
160
+ };
161
+
162
+ declare type Players = {
163
+ white: Player;
164
+ black: Player;
94
165
  };
95
166
 
96
167
  declare type Ply = number;
97
168
 
169
+ declare type San = string;
170
+
98
171
  declare type ShowMoves = false | "right" | "bottom" | "auto";
99
172
 
100
173
  declare type ShowPlayers = true | false | "auto";
101
174
 
102
175
  declare type Translate = (key: string) => string | undefined;
103
176
 
177
+ declare type Uci = string;
178
+
104
179
  export { }
@@ -1,7 +1,7 @@
1
1
  var ai = Object.defineProperty;
2
2
  var ci = (e, t, n) => t in e ? ai(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
3
3
  var Be = (e, t, n) => ci(e, typeof t != "symbol" ? t + "" : t, n);
4
- import { defineComponent as li, ref as ui, onMounted as hi, openBlock as di, createElementBlock as fi } from "vue";
4
+ import { defineComponent as li, ref as ui, onMounted as hi, createElementBlock as di, openBlock as fi } from "vue";
5
5
  const Ie = ["a", "b", "c", "d", "e", "f", "g", "h"], un = ["1", "2", "3", "4", "5", "6", "7", "8"], X = ["white", "black"], Y = ["pawn", "knight", "bishop", "rook", "queen", "king"], pi = ["a", "h"], ve = (e) => "role" in e, y = (e) => e !== void 0, x = (e) => e === "white" ? "black" : "white", pe = (e) => e >> 3, z = (e) => e & 7, lt = (e, t) => 0 <= e && e < 8 && 0 <= t && t < 8 ? e + 8 * t : void 0, de = (e) => {
6
6
  switch (e) {
7
7
  case "pawn":
@@ -3222,7 +3222,7 @@ const Rs = (e) => {
3222
3222
  };
3223
3223
  function Ts(e, t) {
3224
3224
  const n = ns();
3225
- Un(n, t);
3225
+ Un(n, t || {});
3226
3226
  function i() {
3227
3227
  const r = "dom" in n ? n.dom.unbind : void 0, s = ws(e, n), o = ar(() => s.board.getBoundingClientRect()), a = (p) => {
3228
3228
  Es(c), s.autoPieces && Ms(c, s.autoPieces), !p && s.svg && rs(c, s.svg, s.customSvg);
@@ -3956,7 +3956,7 @@ function Bo(e, t) {
3956
3956
  class Do {
3957
3957
  constructor(t, n) {
3958
3958
  Be(this, "viewer");
3959
- this.viewer = Bo(t, n);
3959
+ this.viewer = Bo(t, { ...n });
3960
3960
  }
3961
3961
  get api() {
3962
3962
  return this.viewer;
@@ -3972,8 +3972,7 @@ class Ko {
3972
3972
  this.viewer = new Do(t, this.config);
3973
3973
  }
3974
3974
  get api() {
3975
- var t;
3976
- return (t = this.viewer) == null ? void 0 : t.api;
3975
+ return this.viewer.api;
3977
3976
  }
3978
3977
  }
3979
3978
  const Io = /* @__PURE__ */ li({
@@ -3983,9 +3982,11 @@ const Io = /* @__PURE__ */ li({
3983
3982
  },
3984
3983
  emits: ["ready"],
3985
3984
  setup(e, { emit: t }) {
3986
- const n = e, i = t, r = ui(null), s = new Ko({ ...n.config }), o = () => r.value && s.mount(r.value), a = () => s.api && i("ready", s.api);
3987
- return hi(() => o() ?? a()), (u, c) => (di(), fi("div", {
3988
- ref_key: "board",
3985
+ const n = e, i = t, r = ui(null), s = new Ko({ ...n.config }), o = () => s.mount(r.value), a = () => i("ready", s.api);
3986
+ return hi(() => {
3987
+ o(), a();
3988
+ }), (u, c) => (fi(), di("div", {
3989
+ ref_key: "div",
3989
3990
  ref: r
3990
3991
  }, null, 512));
3991
3992
  }
@@ -1,4 +1,4 @@
1
1
  (function(H,I){typeof exports=="object"&&typeof module<"u"?I(exports,require("vue")):typeof define=="function"&&define.amd?define(["exports","vue"],I):(H=typeof globalThis<"u"?globalThis:H||self,I(H.MyLib={},H.Vue))})(this,function(H,I){"use strict";var No=Object.defineProperty;var Bo=(H,I,ne)=>I in H?No(H,I,{enumerable:!0,configurable:!0,writable:!0,value:ne}):H[I]=ne;var et=(H,I,ne)=>Bo(H,typeof I!="symbol"?I+"":I,ne);const ne=["a","b","c","d","e","f","g","h"],zt=["1","2","3","4","5","6","7","8"],Q=["white","black"],X=["pawn","knight","bishop","rook","queen","king"],li=["a","h"],_e=e=>"role"in e,y=e=>e!==void 0,x=e=>e==="white"?"black":"white",pe=e=>e>>3,q=e=>e&7,tt=(e,t)=>0<=e&&e<8&&0<=t&&t<8?e+8*t:void 0,me=e=>{switch(e){case"pawn":return"p";case"knight":return"n";case"bishop":return"b";case"rook":return"r";case"queen":return"q";case"king":return"k"}};function Ke(e){switch(e.toLowerCase()){case"p":return"pawn";case"n":return"knight";case"b":return"bishop";case"r":return"rook";case"q":return"queen";case"k":return"king";default:return}}function Ae(e){if(e.length===2)return tt(e.charCodeAt(0)-97,e.charCodeAt(1)-49)}const ae=e=>ne[q(e)]+zt[pe(e)],ui=e=>_e(e)?`${me(e.role).toUpperCase()}@${ae(e.to)}`:ae(e.from)+ae(e.to)+(e.promotion?me(e.promotion):""),nt=(e,t)=>e==="white"?t==="a"?2:6:t==="a"?58:62,it=(e,t)=>e==="white"?t==="a"?3:5:t==="a"?59:61,qt=e=>(e=e-(e>>>1&1431655765),e=(e&858993459)+(e>>>2&858993459),Math.imul(e+(e>>>4)&252645135,16843009)>>24),rt=e=>(e=e>>>8&16711935|(e&16711935)<<8,e>>>16&65535|(e&65535)<<16),Wt=e=>(e=e>>>1&1431655765|(e&1431655765)<<1,e=e>>>2&858993459|(e&858993459)<<2,e=e>>>4&252645135|(e&252645135)<<4,rt(e));class l{constructor(t,n){this.lo=t|0,this.hi=n|0}static fromSquare(t){return t>=32?new l(0,1<<t-32):new l(1<<t,0)}static fromRank(t){return new l(255,0).shl64(8*t)}static fromFile(t){return new l(16843009<<t,16843009<<t)}static empty(){return new l(0,0)}static full(){return new l(4294967295,4294967295)}static corners(){return new l(129,2164260864)}static center(){return new l(402653184,24)}static backranks(){return new l(255,4278190080)}static backrank(t){return t==="white"?new l(255,0):new l(0,4278190080)}static lightSquares(){return new l(1437226410,1437226410)}static darkSquares(){return new l(2857740885,2857740885)}complement(){return new l(~this.lo,~this.hi)}xor(t){return new l(this.lo^t.lo,this.hi^t.hi)}union(t){return new l(this.lo|t.lo,this.hi|t.hi)}intersect(t){return new l(this.lo&t.lo,this.hi&t.hi)}diff(t){return new l(this.lo&~t.lo,this.hi&~t.hi)}intersects(t){return this.intersect(t).nonEmpty()}isDisjoint(t){return this.intersect(t).isEmpty()}supersetOf(t){return t.diff(this).isEmpty()}subsetOf(t){return this.diff(t).isEmpty()}shr64(t){return t>=64?l.empty():t>=32?new l(this.hi>>>t-32,0):t>0?new l(this.lo>>>t^this.hi<<32-t,this.hi>>>t):this}shl64(t){return t>=64?l.empty():t>=32?new l(0,this.lo<<t-32):t>0?new l(this.lo<<t,this.hi<<t^this.lo>>>32-t):this}bswap64(){return new l(rt(this.hi),rt(this.lo))}rbit64(){return new l(Wt(this.hi),Wt(this.lo))}minus64(t){const n=this.lo-t.lo,i=(n&t.lo&1)+(t.lo>>>1)+(n>>>1)>>>31;return new l(n,this.hi-(t.hi+i))}equals(t){return this.lo===t.lo&&this.hi===t.hi}size(){return qt(this.lo)+qt(this.hi)}isEmpty(){return this.lo===0&&this.hi===0}nonEmpty(){return this.lo!==0||this.hi!==0}has(t){return(t>=32?this.hi&1<<t-32:this.lo&1<<t)!==0}set(t,n){return n?this.with(t):this.without(t)}with(t){return t>=32?new l(this.lo,this.hi|1<<t-32):new l(this.lo|1<<t,this.hi)}without(t){return t>=32?new l(this.lo,this.hi&~(1<<t-32)):new l(this.lo&~(1<<t),this.hi)}toggle(t){return t>=32?new l(this.lo,this.hi^1<<t-32):new l(this.lo^1<<t,this.hi)}last(){if(this.hi!==0)return 63-Math.clz32(this.hi);if(this.lo!==0)return 31-Math.clz32(this.lo)}first(){if(this.lo!==0)return 31-Math.clz32(this.lo&-this.lo);if(this.hi!==0)return 63-Math.clz32(this.hi&-this.hi)}withoutFirst(){return this.lo!==0?new l(this.lo&this.lo-1,this.hi):new l(0,this.hi&this.hi-1)}moreThanOne(){return this.hi!==0&&this.lo!==0||(this.lo&this.lo-1)!==0||(this.hi&this.hi-1)!==0}singleSquare(){return this.moreThanOne()?void 0:this.last()}*[Symbol.iterator](){let t=this.lo,n=this.hi;for(;t!==0;){const i=31-Math.clz32(t&-t);t^=1<<i,yield i}for(;n!==0;){const i=31-Math.clz32(n&-n);n^=1<<i,yield 32+i}}*reversed(){let t=this.lo,n=this.hi;for(;n!==0;){const i=31-Math.clz32(n);n^=1<<i,yield 32+i}for(;t!==0;){const i=31-Math.clz32(t);t^=1<<i,yield i}}}const Le=(e,t)=>{let n=l.empty();for(const i of t){const r=e+i;0<=r&&r<64&&Math.abs(q(e)-q(r))<=2&&(n=n.with(r))}return n},ce=e=>{const t=[];for(let n=0;n<64;n++)t[n]=e(n);return t},hi=ce(e=>Le(e,[-9,-8,-7,-1,1,7,8,9])),di=ce(e=>Le(e,[-17,-15,-10,-6,6,10,15,17])),fi={white:ce(e=>Le(e,[7,9])),black:ce(e=>Le(e,[-7,-9]))},ge=e=>hi[e],$e=e=>di[e],Ee=(e,t)=>fi[e][t],st=ce(e=>l.fromFile(q(e)).without(e)),ot=ce(e=>l.fromRank(pe(e)).without(e)),at=ce(e=>{const t=new l(134480385,2151686160),n=8*(pe(e)-q(e));return(n>=0?t.shl64(n):t.shr64(-n)).without(e)}),ct=ce(e=>{const t=new l(270549120,16909320),n=8*(pe(e)+q(e)-7);return(n>=0?t.shl64(n):t.shr64(-n)).without(e)}),lt=(e,t,n)=>{let i=n.intersect(t),r=i.bswap64();return i=i.minus64(e),r=r.minus64(e.bswap64()),i.xor(r.bswap64()).intersect(t)},pi=(e,t)=>lt(l.fromSquare(e),st[e],t),mi=(e,t)=>{const n=ot[e];let i=t.intersect(n),r=i.rbit64();return i=i.minus64(l.fromSquare(e)),r=r.minus64(l.fromSquare(63-e)),i.xor(r.rbit64()).intersect(n)},Se=(e,t)=>{const n=l.fromSquare(e);return lt(n,at[e],t).xor(lt(n,ct[e],t))},Pe=(e,t)=>pi(e,t).xor(mi(e,t)),ut=(e,t)=>Se(e,t).xor(Pe(e,t)),Ft=(e,t,n)=>{switch(e.role){case"pawn":return Ee(e.color,t);case"knight":return $e(t);case"bishop":return Se(t,n);case"rook":return Pe(t,n);case"queen":return ut(t,n);case"king":return ge(t)}},Gt=(e,t)=>{const n=l.fromSquare(t);return ot[e].intersects(n)?ot[e].with(e):ct[e].intersects(n)?ct[e].with(e):at[e].intersects(n)?at[e].with(e):st[e].intersects(n)?st[e].with(e):l.empty()},xe=(e,t)=>Gt(e,t).intersect(l.full().shl64(e).xor(l.full().shl64(t))).withoutFirst();class le{constructor(){}static default(){const t=new le;return t.reset(),t}reset(){this.occupied=new l(65535,4294901760),this.promoted=l.empty(),this.white=new l(65535,0),this.black=new l(0,4294901760),this.pawn=new l(65280,16711680),this.knight=new l(66,1107296256),this.bishop=new l(36,603979776),this.rook=new l(129,2164260864),this.queen=new l(8,134217728),this.king=new l(16,268435456)}static empty(){const t=new le;return t.clear(),t}clear(){this.occupied=l.empty(),this.promoted=l.empty();for(const t of Q)this[t]=l.empty();for(const t of X)this[t]=l.empty()}clone(){const t=new le;t.occupied=this.occupied,t.promoted=this.promoted;for(const n of Q)t[n]=this[n];for(const n of X)t[n]=this[n];return t}getColor(t){if(this.white.has(t))return"white";if(this.black.has(t))return"black"}getRole(t){for(const n of X)if(this[n].has(t))return n}get(t){const n=this.getColor(t);if(!n)return;const i=this.getRole(t),r=this.promoted.has(t);return{color:n,role:i,promoted:r}}take(t){const n=this.get(t);return n&&(this.occupied=this.occupied.without(t),this[n.color]=this[n.color].without(t),this[n.role]=this[n.role].without(t),n.promoted&&(this.promoted=this.promoted.without(t))),n}set(t,n){const i=this.take(t);return this.occupied=this.occupied.with(t),this[n.color]=this[n.color].with(t),this[n.role]=this[n.role].with(t),n.promoted&&(this.promoted=this.promoted.with(t)),i}has(t){return this.occupied.has(t)}*[Symbol.iterator](){for(const t of this.occupied)yield[t,this.get(t)]}pieces(t,n){return this[t].intersect(this[n])}rooksAndQueens(){return this.rook.union(this.queen)}bishopsAndQueens(){return this.bishop.union(this.queen)}kingOf(t){return this.pieces(t,"king").singleSquare()}}class j{constructor(){}static empty(){const t=new j;for(const n of X)t[n]=0;return t}static fromBoard(t,n){const i=new j;for(const r of X)i[r]=t.pieces(n,r).size();return i}clone(){const t=new j;for(const n of X)t[n]=this[n];return t}equals(t){return X.every(n=>this[n]===t[n])}add(t){const n=new j;for(const i of X)n[i]=this[i]+t[i];return n}subtract(t){const n=new j;for(const i of X)n[i]=this[i]-t[i];return n}nonEmpty(){return X.some(t=>this[t]>0)}isEmpty(){return!this.nonEmpty()}hasPawns(){return this.pawn>0}hasNonPawns(){return this.knight>0||this.bishop>0||this.rook>0||this.queen>0||this.king>0}size(){return this.pawn+this.knight+this.bishop+this.rook+this.queen+this.king}}class ie{constructor(t,n){this.white=t,this.black=n}static empty(){return new ie(j.empty(),j.empty())}static fromBoard(t){return new ie(j.fromBoard(t,"white"),j.fromBoard(t,"black"))}clone(){return new ie(this.white.clone(),this.black.clone())}equals(t){return this.white.equals(t.white)&&this.black.equals(t.black)}add(t){return new ie(this.white.add(t.white),this.black.add(t.black))}subtract(t){return new ie(this.white.subtract(t.white),this.black.subtract(t.black))}count(t){return this.white[t]+this.black[t]}size(){return this.white.size()+this.black.size()}isEmpty(){return this.white.isEmpty()&&this.black.isEmpty()}nonEmpty(){return!this.isEmpty()}hasPawns(){return this.white.hasPawns()||this.black.hasPawns()}hasNonPawns(){return this.white.hasNonPawns()||this.black.hasNonPawns()}}class ke{constructor(t,n){this.white=t,this.black=n}static default(){return new ke(3,3)}clone(){return new ke(this.white,this.black)}equals(t){return this.white===t.white&&this.black===t.black}}class Ut{unwrap(t,n){const i=this._chain(r=>k.ok(t?t(r):r),r=>n?k.ok(n(r)):k.err(r));if(i.isErr)throw i.error;return i.value}map(t,n){return this._chain(i=>k.ok(t(i)),i=>k.err(n?n(i):i))}chain(t,n){return this._chain(t,n||(i=>k.err(i)))}}class gi extends Ut{constructor(t){super(),this.value=void 0,this.isOk=!0,this.isErr=!1,this.value=t}_chain(t,n){return t(this.value)}}class ki extends Ut{constructor(t){super(),this.error=void 0,this.isOk=!1,this.isErr=!0,this.error=t}_chain(t,n){return n(this.error)}}var k;(function(e){e.ok=function(t){return new gi(t)},e.err=function(t){return new ki(t||new Error)},e.all=function(t){if(Array.isArray(t)){const r=[];for(let s=0;s<t.length;s++){const o=t[s];if(o.isErr)return o;r.push(o.value)}return e.ok(r)}const n={},i=Object.keys(t);for(let r=0;r<i.length;r++){const s=t[i[r]];if(s.isErr)return s;n[i[r]]=s.value}return e.ok(n)}})(k||(k={}));var N;(function(e){e.Empty="ERR_EMPTY",e.OppositeCheck="ERR_OPPOSITE_CHECK",e.PawnsOnBackrank="ERR_PAWNS_ON_BACKRANK",e.Kings="ERR_KINGS",e.Variant="ERR_VARIANT"})(N||(N={}));class D extends Error{}const bi=(e,t,n,i)=>n[t].intersect(Pe(e,i).intersect(n.rooksAndQueens()).union(Se(e,i).intersect(n.bishopsAndQueens())).union($e(e).intersect(n.knight)).union(ge(e).intersect(n.king)).union(Ee(x(t),e).intersect(n.pawn)));class V{constructor(){}static default(){const t=new V;return t.castlingRights=l.corners(),t.rook={white:{a:0,h:7},black:{a:56,h:63}},t.path={white:{a:new l(14,0),h:new l(96,0)},black:{a:new l(0,234881024),h:new l(0,1610612736)}},t}static empty(){const t=new V;return t.castlingRights=l.empty(),t.rook={white:{a:void 0,h:void 0},black:{a:void 0,h:void 0}},t.path={white:{a:l.empty(),h:l.empty()},black:{a:l.empty(),h:l.empty()}},t}clone(){const t=new V;return t.castlingRights=this.castlingRights,t.rook={white:{a:this.rook.white.a,h:this.rook.white.h},black:{a:this.rook.black.a,h:this.rook.black.h}},t.path={white:{a:this.path.white.a,h:this.path.white.h},black:{a:this.path.black.a,h:this.path.black.h}},t}add(t,n,i,r){const s=nt(t,n),o=it(t,n);this.castlingRights=this.castlingRights.with(r),this.rook[t][n]=r,this.path[t][n]=xe(r,o).with(o).union(xe(i,s).with(s)).without(i).without(r)}static fromSetup(t){const n=V.empty(),i=t.castlingRights.intersect(t.board.rook);for(const r of Q){const s=l.backrank(r),o=t.board.kingOf(r);if(!y(o)||!s.has(o))continue;const a=i.intersect(t.board[r]).intersect(s),u=a.first();y(u)&&u<o&&n.add(r,"a",o,u);const c=a.last();y(c)&&o<c&&n.add(r,"h",o,c)}return n}discardRook(t){if(this.castlingRights.has(t)){this.castlingRights=this.castlingRights.without(t);for(const n of Q)for(const i of li)this.rook[n][i]===t&&(this.rook[n][i]=void 0)}}discardColor(t){this.castlingRights=this.castlingRights.diff(l.backrank(t)),this.rook[t].a=void 0,this.rook[t].h=void 0}}class ue{constructor(t){this.rules=t}reset(){this.board=le.default(),this.pockets=void 0,this.turn="white",this.castles=V.default(),this.epSquare=void 0,this.remainingChecks=void 0,this.halfmoves=0,this.fullmoves=1}setupUnchecked(t){this.board=t.board.clone(),this.board.promoted=l.empty(),this.pockets=void 0,this.turn=t.turn,this.castles=V.fromSetup(t),this.epSquare=wi(this,t.epSquare),this.remainingChecks=void 0,this.halfmoves=t.halfmoves,this.fullmoves=t.fullmoves}kingAttackers(t,n,i){return bi(t,n,this.board,i)}playCaptureAt(t,n){this.halfmoves=0,n.role==="rook"&&this.castles.discardRook(t),this.pockets&&this.pockets[x(n.color)][n.promoted?"pawn":n.role]++}ctx(){const t=this.isVariantEnd(),n=this.board.kingOf(this.turn);if(!y(n))return{king:n,blockers:l.empty(),checkers:l.empty(),variantEnd:t,mustCapture:!1};const i=Pe(n,l.empty()).intersect(this.board.rooksAndQueens()).union(Se(n,l.empty()).intersect(this.board.bishopsAndQueens())).intersect(this.board[x(this.turn)]);let r=l.empty();for(const o of i){const a=xe(n,o).intersect(this.board.occupied);a.moreThanOne()||(r=r.union(a))}const s=this.kingAttackers(n,x(this.turn),this.board.occupied);return{king:n,blockers:r,checkers:s,variantEnd:t,mustCapture:!1}}clone(){var t,n;const i=new this.constructor;return i.board=this.board.clone(),i.pockets=(t=this.pockets)===null||t===void 0?void 0:t.clone(),i.turn=this.turn,i.castles=this.castles.clone(),i.epSquare=this.epSquare,i.remainingChecks=(n=this.remainingChecks)===null||n===void 0?void 0:n.clone(),i.halfmoves=this.halfmoves,i.fullmoves=this.fullmoves,i}validate(){if(this.board.occupied.isEmpty())return k.err(new D(N.Empty));if(this.board.king.size()!==2)return k.err(new D(N.Kings));if(!y(this.board.kingOf(this.turn)))return k.err(new D(N.Kings));const t=this.board.kingOf(x(this.turn));return y(t)?this.kingAttackers(t,this.turn,this.board.occupied).nonEmpty()?k.err(new D(N.OppositeCheck)):l.backranks().intersects(this.board.pawn)?k.err(new D(N.PawnsOnBackrank)):k.ok(void 0):k.err(new D(N.Kings))}dropDests(t){return l.empty()}dests(t,n){if(n=n||this.ctx(),n.variantEnd)return l.empty();const i=this.board.get(t);if(!i||i.color!==this.turn)return l.empty();let r,s;if(i.role==="pawn"){r=Ee(this.turn,t).intersect(this.board[x(this.turn)]);const o=this.turn==="white"?8:-8,a=t+o;if(0<=a&&a<64&&!this.board.occupied.has(a)){r=r.with(a);const u=this.turn==="white"?t<16:t>=48,c=a+o;u&&!this.board.occupied.has(c)&&(r=r.with(c))}y(this.epSquare)&&vi(this,t,n)&&(s=l.fromSquare(this.epSquare))}else i.role==="bishop"?r=Se(t,this.board.occupied):i.role==="knight"?r=$e(t):i.role==="rook"?r=Pe(t,this.board.occupied):i.role==="queen"?r=ut(t,this.board.occupied):r=ge(t);if(r=r.diff(this.board[this.turn]),y(n.king)){if(i.role==="king"){const o=this.board.occupied.without(t);for(const a of r)this.kingAttackers(a,x(this.turn),o).nonEmpty()&&(r=r.without(a));return r.union(Ie(this,"a",n)).union(Ie(this,"h",n))}if(n.checkers.nonEmpty()){const o=n.checkers.singleSquare();if(!y(o))return l.empty();r=r.intersect(xe(o,n.king).with(o))}n.blockers.has(t)&&(r=r.intersect(Gt(t,n.king)))}return s&&(r=r.union(s)),r}isVariantEnd(){return!1}variantOutcome(t){}hasInsufficientMaterial(t){return this.board[t].intersect(this.board.pawn.union(this.board.rooksAndQueens())).nonEmpty()?!1:this.board[t].intersects(this.board.knight)?this.board[t].size()<=2&&this.board[x(t)].diff(this.board.king).diff(this.board.queen).isEmpty():this.board[t].intersects(this.board.bishop)?(!this.board.bishop.intersects(l.darkSquares())||!this.board.bishop.intersects(l.lightSquares()))&&this.board.pawn.isEmpty()&&this.board.knight.isEmpty():!0}toSetup(){var t,n;return{board:this.board.clone(),pockets:(t=this.pockets)===null||t===void 0?void 0:t.clone(),turn:this.turn,castlingRights:this.castles.castlingRights,epSquare:yi(this),remainingChecks:(n=this.remainingChecks)===null||n===void 0?void 0:n.clone(),halfmoves:Math.min(this.halfmoves,150),fullmoves:Math.min(Math.max(this.fullmoves,1),9999)}}isInsufficientMaterial(){return Q.every(t=>this.hasInsufficientMaterial(t))}hasDests(t){t=t||this.ctx();for(const n of this.board[this.turn])if(this.dests(n,t).nonEmpty())return!0;return this.dropDests(t).nonEmpty()}isLegal(t,n){if(_e(t))return!this.pockets||this.pockets[this.turn][t.role]<=0||t.role==="pawn"&&l.backranks().has(t.to)?!1:this.dropDests(n).has(t.to);{if(t.promotion==="pawn"||t.promotion==="king"&&this.rules!=="antichess"||!!t.promotion!==(this.board.pawn.has(t.from)&&l.backranks().has(t.to)))return!1;const i=this.dests(t.from,n);return i.has(t.to)||i.has(Ci(this,t).to)}}isCheck(){const t=this.board.kingOf(this.turn);return y(t)&&this.kingAttackers(t,x(this.turn),this.board.occupied).nonEmpty()}isEnd(t){return(t?t.variantEnd:this.isVariantEnd())?!0:this.isInsufficientMaterial()||!this.hasDests(t)}isCheckmate(t){return t=t||this.ctx(),!t.variantEnd&&t.checkers.nonEmpty()&&!this.hasDests(t)}isStalemate(t){return t=t||this.ctx(),!t.variantEnd&&t.checkers.isEmpty()&&!this.hasDests(t)}outcome(t){const n=this.variantOutcome(t);return n||(t=t||this.ctx(),this.isCheckmate(t)?{winner:x(this.turn)}:this.isInsufficientMaterial()||this.isStalemate(t)?{winner:void 0}:void 0)}allDests(t){t=t||this.ctx();const n=new Map;if(t.variantEnd)return n;for(const i of this.board[this.turn])n.set(i,this.dests(i,t));return n}play(t){const n=this.turn,i=this.epSquare,r=jt(this,t);if(this.epSquare=void 0,this.halfmoves+=1,n==="black"&&(this.fullmoves+=1),this.turn=x(n),_e(t))this.board.set(t.to,{role:t.role,color:n}),this.pockets&&this.pockets[n][t.role]--,t.role==="pawn"&&(this.halfmoves=0);else{const s=this.board.take(t.from);if(!s)return;let o;if(s.role==="pawn"){this.halfmoves=0,t.to===i&&(o=this.board.take(t.to+(n==="white"?-8:8)));const a=t.from-t.to;Math.abs(a)===16&&8<=t.from&&t.from<=55&&(this.epSquare=t.from+t.to>>1),t.promotion&&(s.role=t.promotion,s.promoted=!!this.pockets)}else if(s.role==="rook")this.castles.discardRook(t.from);else if(s.role==="king"){if(r){const a=this.castles.rook[n][r];if(y(a)){const u=this.board.take(a);this.board.set(nt(n,r),s),u&&this.board.set(it(n,r),u)}}this.castles.discardColor(n)}if(!r){const a=this.board.set(t.to,s)||o;a&&this.playCaptureAt(t.to,a)}}this.remainingChecks&&this.isCheck()&&(this.remainingChecks[n]=Math.max(this.remainingChecks[n]-1,0))}}class Ht extends ue{constructor(){super("chess")}static default(){const t=new this;return t.reset(),t}static fromSetup(t){const n=new this;return n.setupUnchecked(t),n.validate().map(i=>n)}clone(){return super.clone()}}const wi=(e,t)=>{if(!y(t))return;const n=e.turn==="white"?5:2,i=e.turn==="white"?8:-8;if(pe(t)!==n||e.board.occupied.has(t+i))return;const r=t-i;if(!(!e.board.pawn.has(r)||!e.board[x(e.turn)].has(r)))return t},yi=e=>{if(!y(e.epSquare))return;const t=e.ctx(),i=e.board.pieces(e.turn,"pawn").intersect(Ee(x(e.turn),e.epSquare));for(const r of i)if(e.dests(r,t).has(e.epSquare))return e.epSquare},vi=(e,t,n)=>{if(!y(e.epSquare)||!Ee(e.turn,t).has(e.epSquare))return!1;if(!y(n.king))return!0;const i=e.turn==="white"?8:-8,r=e.epSquare-i;return e.kingAttackers(n.king,x(e.turn),e.board.occupied.toggle(t).toggle(r).with(e.epSquare)).without(r).isEmpty()},Ie=(e,t,n)=>{if(!y(n.king)||n.checkers.nonEmpty())return l.empty();const i=e.castles.rook[e.turn][t];if(!y(i)||e.castles.path[e.turn][t].intersects(e.board.occupied))return l.empty();const r=nt(e.turn,t),s=xe(n.king,r),o=e.board.occupied.without(n.king);for(const c of s)if(e.kingAttackers(c,x(e.turn),o).nonEmpty())return l.empty();const a=it(e.turn,t),u=e.board.occupied.toggle(n.king).toggle(i).toggle(a);return e.kingAttackers(r,x(e.turn),u).nonEmpty()?l.empty():l.fromSquare(i)},ht=(e,t,n)=>{if(n.variantEnd)return l.empty();const i=e.board.get(t);if(!i||i.color!==e.turn)return l.empty();let r=Ft(i,t,e.board.occupied);if(i.role==="pawn"){let s=e.board[x(e.turn)];y(e.epSquare)&&(s=s.with(e.epSquare)),r=r.intersect(s);const o=e.turn==="white"?8:-8,a=t+o;if(0<=a&&a<64&&!e.board.occupied.has(a)){r=r.with(a);const u=e.turn==="white"?t<16:t>=48,c=a+o;u&&!e.board.occupied.has(c)&&(r=r.with(c))}return r}else r=r.diff(e.board[e.turn]);return t===n.king?r.union(Ie(e,"a",n)).union(Ie(e,"h",n)):r},jt=(e,t)=>{if(_e(t))return;const n=t.to-t.from;if(!(Math.abs(n)!==2&&!e.board[e.turn].has(t.to))&&e.board.king.has(t.from))return n>0?"h":"a"},Ci=(e,t)=>{const n=jt(e,t);if(!n)return t;const i=e.castles.rook[e.turn][n];return{from:t.from,to:y(i)?i:t.to}},_i=e=>_e(e)?String.fromCharCode(35+e.to,99+8*5+["queen","rook","bishop","knight","pawn"].indexOf(e.role)):String.fromCharCode(35+e.from,e.promotion?99+8*["queen","rook","bishop","knight","king"].indexOf(e.promotion)+q(e.to):35+e.to);var K;(function(e){e.Fen="ERR_FEN",e.Board="ERR_BOARD",e.Pockets="ERR_POCKETS",e.Turn="ERR_TURN",e.Castling="ERR_CASTLING",e.EpSquare="ERR_EP_SQUARE",e.RemainingChecks="ERR_REMAINING_CHECKS",e.Halfmoves="ERR_HALFMOVES",e.Fullmoves="ERR_FULLMOVES"})(K||(K={}));class z extends Error{}const Ei=(e,t,n)=>{let i=e.indexOf(t);for(;n-- >0&&i!==-1;)i=e.indexOf(t,i+t.length);return i},Me=e=>/^\d{1,4}$/.test(e)?parseInt(e,10):void 0,Vt=e=>{const t=Ke(e);return t&&{role:t,color:e.toLowerCase()===e?"black":"white"}},dt=e=>{const t=le.empty();let n=7,i=0;for(let r=0;r<e.length;r++){const s=e[r];if(s==="/"&&i===8)i=0,n--;else{const o=parseInt(s,10);if(o>0)i+=o;else{if(i>=8||n<0)return k.err(new z(K.Board));const a=i+n*8,u=Vt(s);if(!u)return k.err(new z(K.Board));e[r+1]==="~"&&(u.promoted=!0,r++),t.set(a,u),i++}}}return n!==0||i!==8?k.err(new z(K.Board)):k.ok(t)},Zt=e=>{if(e.length>64)return k.err(new z(K.Pockets));const t=ie.empty();for(const n of e){const i=Vt(n);if(!i)return k.err(new z(K.Pockets));t[i.color][i.role]++}return k.ok(t)},Si=(e,t)=>{let n=l.empty();if(t==="-")return k.ok(n);for(const i of t){const r=i.toLowerCase(),s=i===r?"black":"white",o=s==="white"?0:7;if("a"<=r&&r<="h")n=n.with(tt(r.charCodeAt(0)-97,o));else if(r==="k"||r==="q"){const a=e[s].intersect(l.backrank(s)).intersect(e.rook.union(e.king)),u=r==="k"?a.last():a.first();n=n.with(y(u)&&e.rook.has(u)?u:tt(r==="k"?7:0,o))}else return k.err(new z(K.Castling))}return Q.some(i=>l.backrank(i).intersect(n).size()>2)?k.err(new z(K.Castling)):k.ok(n)},Yt=e=>{const t=e.split("+");if(t.length===3&&t[0]===""){const n=Me(t[1]),i=Me(t[2]);return!y(n)||n>3||!y(i)||i>3?k.err(new z(K.RemainingChecks)):k.ok(new ke(3-n,3-i))}else if(t.length===2){const n=Me(t[0]),i=Me(t[1]);return!y(n)||n>3||!y(i)||i>3?k.err(new z(K.RemainingChecks)):k.ok(new ke(n,i))}else return k.err(new z(K.RemainingChecks))},Pi=e=>{const t=e.split(/[\s_]+/),n=t.shift();let i,r=k.ok(void 0);if(n.endsWith("]")){const a=n.indexOf("[");if(a===-1)return k.err(new z(K.Fen));i=dt(n.slice(0,a)),r=Zt(n.slice(a+1,-1))}else{const a=Ei(n,"/",7);a===-1?i=dt(n):(i=dt(n.slice(0,a)),r=Zt(n.slice(a+1)))}let s;const o=t.shift();if(!y(o)||o==="w")s="white";else if(o==="b")s="black";else return k.err(new z(K.Turn));return i.chain(a=>{const u=t.shift(),c=y(u)?Si(a,u):k.ok(l.empty()),p=t.shift();let f;if(y(p)&&p!=="-"&&(f=Ae(p),!y(f)))return k.err(new z(K.EpSquare));let _=t.shift(),m;y(_)&&_.includes("+")&&(m=Yt(_),_=t.shift());const h=y(_)?Me(_):0;if(!y(h))return k.err(new z(K.Halfmoves));const d=t.shift(),b=y(d)?Me(d):1;if(!y(b))return k.err(new z(K.Fullmoves));const g=t.shift();let v=k.ok(void 0);if(y(g)){if(y(m))return k.err(new z(K.RemainingChecks));v=Yt(g)}else y(m)&&(v=m);return t.length>0?k.err(new z(K.Fen)):r.chain(P=>c.chain(C=>v.map(E=>({board:a,pockets:P,turn:s,castlingRights:C,remainingChecks:E,epSquare:f,halfmoves:h,fullmoves:Math.max(1,b)}))))})},xi=e=>{let t=me(e.role);return e.color==="white"&&(t=t.toUpperCase()),e.promoted&&(t+="~"),t},Mi=e=>{let t="",n=0;for(let i=7;i>=0;i--)for(let r=0;r<8;r++){const s=r+i*8,o=e.get(s);o?(n>0&&(t+=n,n=0),t+=xi(o)):n++,r===7&&(n>0&&(t+=n,n=0),i!==0&&(t+="/"))}return t},Qt=e=>X.map(t=>me(t).repeat(e[t])).join(""),Ai=e=>Qt(e.white).toUpperCase()+Qt(e.black),Oi=(e,t)=>{let n="";for(const i of Q){const r=l.backrank(i);let s=e.kingOf(i);y(s)&&!r.has(s)&&(s=void 0);const o=e.pieces(i,"rook").intersect(r);for(const a of t.intersect(r).reversed())if(a===o.first()&&y(s)&&a<s)n+=i==="white"?"Q":"q";else if(a===o.last()&&y(s)&&s<a)n+=i==="white"?"K":"k";else{const u=ne[q(a)];n+=i==="white"?u.toUpperCase():u}}return n||"-"},Ri=e=>`${e.white}+${e.black}`,Xt=(e,t)=>[Mi(e.board)+(e.pockets?`[${Ai(e.pockets)}]`:""),e.turn[0],Oi(e.board,e.castlingRights),y(e.epSquare)?ae(e.epSquare):"-",...e.remainingChecks?[Ri(e.remainingChecks)]:[],Math.max(0,Math.min(e.halfmoves,9999)),Math.max(1,Math.min(e.fullmoves,9999))].join(" "),Ti=(e,t)=>{let n="";if(_e(t))t.role!=="pawn"&&(n=me(t.role).toUpperCase()),n+="@"+ae(t.to);else{const i=e.board.getRole(t.from);if(!i)return"--";if(i==="king"&&(e.board[e.turn].has(t.to)||Math.abs(t.to-t.from)===2))n=t.to>t.from?"O-O":"O-O-O";else{const r=e.board.occupied.has(t.to)||i==="pawn"&&q(t.from)!==q(t.to);if(i!=="pawn"){n=me(i).toUpperCase();let s;if(i==="king"?s=ge(t.to).intersect(e.board.king):i==="queen"?s=ut(t.to,e.board.occupied).intersect(e.board.queen):i==="rook"?s=Pe(t.to,e.board.occupied).intersect(e.board.rook):i==="bishop"?s=Se(t.to,e.board.occupied).intersect(e.board.bishop):s=$e(t.to).intersect(e.board.knight),s=s.intersect(e.board[e.turn]).without(t.from),s.nonEmpty()){const o=e.ctx();for(const a of s)e.dests(a,o).has(t.to)||(s=s.without(a));if(s.nonEmpty()){let a=!1,u=s.intersects(l.fromRank(pe(t.from)));s.intersects(l.fromFile(q(t.from)))?a=!0:u=!0,u&&(n+=ne[q(t.from)]),a&&(n+=zt[pe(t.from)])}}}else r&&(n=ne[q(t.from)]);r&&(n+="x"),n+=ae(t.to),t.promotion&&(n+="="+me(t.promotion).toUpperCase())}}return n},Ni=(e,t)=>{var n;const i=Ti(e,t);return e.play(t),!((n=e.outcome())===null||n===void 0)&&n.winner?i+"#":e.isCheck()?i+"+":i},Bi=(e,t)=>{const n=e.ctx(),i=t.match(/^([NBRQK])?([a-h])?([1-8])?[-x]?([a-h][1-8])(?:=?([nbrqkNBRQK]))?[+#]?$/);if(!i){let p;if(t==="O-O"||t==="O-O+"||t==="O-O#"?p="h":(t==="O-O-O"||t==="O-O-O+"||t==="O-O-O#")&&(p="a"),p){const m=e.castles.rook[e.turn][p];return!y(n.king)||!y(m)||!e.dests(n.king,n).has(m)?void 0:{from:n.king,to:m}}const f=t.match(/^([pnbrqkPNBRQK])?@([a-h][1-8])[+#]?$/);if(!f)return;const _={role:f[1]?Ke(f[1]):"pawn",to:Ae(f[2])};return e.isLegal(_,n)?_:void 0}const r=i[1]?Ke(i[1]):"pawn",s=Ae(i[4]),o=i[5]?Ke(i[5]):void 0;if(!!o!==(r==="pawn"&&l.backranks().has(s))||o==="king"&&e.rules!=="antichess")return;let a=e.board.pieces(e.turn,r);r==="pawn"&&!i[2]?a=a.intersect(l.fromFile(q(s))):i[2]&&(a=a.intersect(l.fromFile(i[2].charCodeAt(0)-97))),i[3]&&(a=a.intersect(l.fromRank(i[3].charCodeAt(0)-49)));const u=r==="pawn"?l.fromFile(q(s)):l.empty();a=a.intersect(u.union(Ft({color:x(e.turn),role:r},s,e.board.occupied)));let c;for(const p of a)if(e.dests(p,n).has(s)){if(y(c))return;c=p}if(y(c))return{from:c,to:s,promotion:o}};class Jt extends ue{constructor(){super("crazyhouse")}reset(){super.reset(),this.pockets=ie.empty()}setupUnchecked(t){super.setupUnchecked(t),this.board.promoted=t.board.promoted.intersect(t.board.occupied).diff(t.board.king).diff(t.board.pawn),this.pockets=t.pockets?t.pockets.clone():ie.empty()}static default(){const t=new this;return t.reset(),t}static fromSetup(t){const n=new this;return n.setupUnchecked(t),n.validate().map(i=>n)}clone(){return super.clone()}validate(){return super.validate().chain(t=>{var n,i;return!((n=this.pockets)===null||n===void 0)&&n.count("king")?k.err(new D(N.Kings)):(((i=this.pockets)===null||i===void 0?void 0:i.size())||0)+this.board.occupied.size()>64?k.err(new D(N.Variant)):k.ok(void 0)})}hasInsufficientMaterial(t){return this.pockets?this.board.occupied.size()+this.pockets.size()<=3&&this.board.pawn.isEmpty()&&this.board.promoted.isEmpty()&&this.board.rooksAndQueens().isEmpty()&&this.pockets.count("pawn")<=0&&this.pockets.count("rook")<=0&&this.pockets.count("queen")<=0:super.hasInsufficientMaterial(t)}dropDests(t){var n,i;const r=this.board.occupied.complement().intersect(!((n=this.pockets)===null||n===void 0)&&n[this.turn].hasNonPawns()?l.full():!((i=this.pockets)===null||i===void 0)&&i[this.turn].hasPawns()?l.backranks().complement():l.empty());if(t=t||this.ctx(),y(t.king)&&t.checkers.nonEmpty()){const s=t.checkers.singleSquare();return y(s)?r.intersect(xe(s,t.king)):l.empty()}else return r}}class en extends ue{constructor(){super("atomic")}static default(){const t=new this;return t.reset(),t}static fromSetup(t){const n=new this;return n.setupUnchecked(t),n.validate().map(i=>n)}clone(){return super.clone()}validate(){if(this.board.occupied.isEmpty())return k.err(new D(N.Empty));if(this.board.king.size()>2)return k.err(new D(N.Kings));const t=this.board.kingOf(x(this.turn));return y(t)?this.kingAttackers(t,this.turn,this.board.occupied).nonEmpty()?k.err(new D(N.OppositeCheck)):l.backranks().intersects(this.board.pawn)?k.err(new D(N.PawnsOnBackrank)):k.ok(void 0):k.err(new D(N.Kings))}kingAttackers(t,n,i){const r=this.board.pieces(n,"king");return r.isEmpty()||ge(t).intersects(r)?l.empty():super.kingAttackers(t,n,i)}playCaptureAt(t,n){super.playCaptureAt(t,n),this.board.take(t);for(const i of ge(t).intersect(this.board.occupied).diff(this.board.pawn)){const r=this.board.take(i);(r==null?void 0:r.role)==="rook"&&this.castles.discardRook(i),(r==null?void 0:r.role)==="king"&&this.castles.discardColor(r.color)}}hasInsufficientMaterial(t){if(this.board.pieces(x(t),"king").isEmpty())return!1;if(this.board[t].diff(this.board.king).isEmpty())return!0;if(this.board[x(t)].diff(this.board.king).nonEmpty()){if(this.board.occupied.equals(this.board.bishop.union(this.board.king))){if(!this.board.bishop.intersect(this.board.white).intersects(l.darkSquares()))return!this.board.bishop.intersect(this.board.black).intersects(l.lightSquares());if(!this.board.bishop.intersect(this.board.white).intersects(l.lightSquares()))return!this.board.bishop.intersect(this.board.black).intersects(l.darkSquares())}return!1}return this.board.queen.nonEmpty()||this.board.pawn.nonEmpty()?!1:this.board.knight.union(this.board.bishop).union(this.board.rook).size()===1?!0:this.board.occupied.equals(this.board.knight.union(this.board.king))?this.board.knight.size()<=2:!1}dests(t,n){n=n||this.ctx();let i=l.empty();for(const r of ht(this,t,n)){const s=this.clone();s.play({from:t,to:r});const o=s.board.kingOf(this.turn);y(o)&&(!y(s.board.kingOf(s.turn))||s.kingAttackers(o,s.turn,s.board.occupied).isEmpty())&&(i=i.with(r))}return i}isVariantEnd(){return!!this.variantOutcome()}variantOutcome(t){for(const n of Q)if(this.board.pieces(n,"king").isEmpty())return{winner:x(n)}}}class tn extends ue{constructor(){super("antichess")}reset(){super.reset(),this.castles=V.empty()}setupUnchecked(t){super.setupUnchecked(t),this.castles=V.empty()}static default(){const t=new this;return t.reset(),t}static fromSetup(t){const n=new this;return n.setupUnchecked(t),n.validate().map(i=>n)}clone(){return super.clone()}validate(){return this.board.occupied.isEmpty()?k.err(new D(N.Empty)):l.backranks().intersects(this.board.pawn)?k.err(new D(N.PawnsOnBackrank)):k.ok(void 0)}kingAttackers(t,n,i){return l.empty()}ctx(){const t=super.ctx();if(y(this.epSquare)&&Ee(x(this.turn),this.epSquare).intersects(this.board.pieces(this.turn,"pawn")))return t.mustCapture=!0,t;const n=this.board[x(this.turn)];for(const i of this.board[this.turn])if(ht(this,i,t).intersects(n))return t.mustCapture=!0,t;return t}dests(t,n){n=n||this.ctx();const i=ht(this,t,n),r=this.board[x(this.turn)];return i.intersect(n.mustCapture?y(this.epSquare)&&this.board.getRole(t)==="pawn"?r.with(this.epSquare):r:l.full())}hasInsufficientMaterial(t){if(this.board[t].isEmpty())return!1;if(this.board[x(t)].isEmpty())return!0;if(this.board.occupied.equals(this.board.bishop)){const n=this.board[t].intersects(l.lightSquares()),i=this.board[t].intersects(l.darkSquares()),r=this.board[x(t)].isDisjoint(l.lightSquares()),s=this.board[x(t)].isDisjoint(l.darkSquares());return n&&r||i&&s}return this.board.occupied.equals(this.board.knight)&&this.board.occupied.size()===2?this.board.white.intersects(l.lightSquares())!==this.board.black.intersects(l.darkSquares())!=(this.turn===t):!1}isVariantEnd(){return this.board[this.turn].isEmpty()}variantOutcome(t){if(t=t||this.ctx(),t.variantEnd||this.isStalemate(t))return{winner:this.turn}}}class nn extends ue{constructor(){super("kingofthehill")}static default(){const t=new this;return t.reset(),t}static fromSetup(t){const n=new this;return n.setupUnchecked(t),n.validate().map(i=>n)}clone(){return super.clone()}hasInsufficientMaterial(t){return!1}isVariantEnd(){return this.board.king.intersects(l.center())}variantOutcome(t){for(const n of Q)if(this.board.pieces(n,"king").intersects(l.center()))return{winner:n}}}class rn extends ue{constructor(){super("3check")}reset(){super.reset(),this.remainingChecks=ke.default()}setupUnchecked(t){var n;super.setupUnchecked(t),this.remainingChecks=((n=t.remainingChecks)===null||n===void 0?void 0:n.clone())||ke.default()}static default(){const t=new this;return t.reset(),t}static fromSetup(t){const n=new this;return n.setupUnchecked(t),n.validate().map(i=>n)}clone(){return super.clone()}hasInsufficientMaterial(t){return this.board.pieces(t,"king").equals(this.board[t])}isVariantEnd(){return!!this.remainingChecks&&(this.remainingChecks.white<=0||this.remainingChecks.black<=0)}variantOutcome(t){if(this.remainingChecks){for(const n of Q)if(this.remainingChecks[n]<=0)return{winner:n}}}}const Di=()=>{const e=le.empty();return e.occupied=new l(65535,0),e.promoted=l.empty(),e.white=new l(61680,0),e.black=new l(3855,0),e.pawn=l.empty(),e.knight=new l(6168,0),e.bishop=new l(9252,0),e.rook=new l(16962,0),e.queen=new l(129,0),e.king=new l(33024,0),e};class sn extends ue{constructor(){super("racingkings")}reset(){this.board=Di(),this.pockets=void 0,this.turn="white",this.castles=V.empty(),this.epSquare=void 0,this.remainingChecks=void 0,this.halfmoves=0,this.fullmoves=1}setupUnchecked(t){super.setupUnchecked(t),this.castles=V.empty()}static default(){const t=new this;return t.reset(),t}static fromSetup(t){const n=new this;return n.setupUnchecked(t),n.validate().map(i=>n)}clone(){return super.clone()}validate(){return this.isCheck()||this.board.pawn.nonEmpty()?k.err(new D(N.Variant)):super.validate()}dests(t,n){if(n=n||this.ctx(),t===n.king)return super.dests(t,n);let i=l.empty();for(const r of super.dests(t,n)){const s={from:t,to:r},o=this.clone();o.play(s),o.isCheck()||(i=i.with(r))}return i}hasInsufficientMaterial(t){return!1}isVariantEnd(){const t=l.fromRank(7),n=this.board.king.intersect(t);if(n.isEmpty())return!1;if(this.turn==="white"||n.intersects(this.board.black))return!0;const i=this.board.kingOf("black");if(y(i)){const r=this.board.occupied.without(i);for(const s of ge(i).intersect(t).diff(this.board.black))if(this.kingAttackers(s,"white",r).isEmpty())return!1}return!0}variantOutcome(t){if(t?!t.variantEnd:!this.isVariantEnd())return;const n=l.fromRank(7),i=this.board.pieces("black","king").intersects(n),r=this.board.pieces("white","king").intersects(n);return i&&!r?{winner:"black"}:r&&!i?{winner:"white"}:{winner:void 0}}}const Ki=()=>{const e=le.empty();return e.occupied=new l(4294967295,4294901862),e.promoted=l.empty(),e.white=new l(4294967295,102),e.black=new l(0,4294901760),e.pawn=new l(4294967295,16711782),e.knight=new l(0,1107296256),e.bishop=new l(0,603979776),e.rook=new l(0,2164260864),e.queen=new l(0,134217728),e.king=new l(0,268435456),e};class on extends ue{constructor(){super("horde")}reset(){this.board=Ki(),this.pockets=void 0,this.turn="white",this.castles=V.default(),this.castles.discardColor("white"),this.epSquare=void 0,this.remainingChecks=void 0,this.halfmoves=0,this.fullmoves=1}static default(){const t=new this;return t.reset(),t}static fromSetup(t){const n=new this;return n.setupUnchecked(t),n.validate().map(i=>n)}clone(){return super.clone()}validate(){if(this.board.occupied.isEmpty())return k.err(new D(N.Empty));if(this.board.king.size()!==1)return k.err(new D(N.Kings));const t=this.board.kingOf(x(this.turn));if(y(t)&&this.kingAttackers(t,this.turn,this.board.occupied).nonEmpty())return k.err(new D(N.OppositeCheck));for(const n of Q){const i=this.board.pieces(n,"king").isEmpty()?l.backrank(x(n)):l.backranks();if(this.board.pieces(n,"pawn").intersects(i))return k.err(new D(N.PawnsOnBackrank))}return k.ok(void 0)}hasInsufficientMaterial(t){if(this.board.pieces(t,"king").nonEmpty())return!1;const n=m=>m==="light"?"dark":"light",i=m=>m==="light"?l.lightSquares():l.darkSquares(),r=m=>{const h=this.board.pieces(m,"bishop");return h.intersects(l.darkSquares())&&h.intersects(l.lightSquares())},s=j.fromBoard(this.board,t),o=m=>i(m).intersect(this.board.pieces(t,"bishop")).size(),a=o("light")>=1?"light":"dark",u=s.pawn+s.knight+s.rook+s.queen+Math.min(o("dark"),2)+Math.min(o("light"),2),c=j.fromBoard(this.board,x(t)),p=m=>i(m).intersect(this.board.pieces(x(t),"bishop")).size(),f=c.size(),_=m=>f-m;if(u===0)return!0;if(u>=4||(s.pawn>=1||s.queen>=1)&&u>=2||s.rook>=1&&u>=2&&!(u===2&&s.rook===1&&s.bishop===1&&_(p(a))===1))return!1;if(u===1){if(f===1)return!0;if(s.queen===1)return!(c.pawn>=1||c.rook>=1||p("light")>=2||p("dark")>=2);if(s.pawn===1){const m=this.board.pieces(t,"pawn").last(),h=this.clone();h.board.set(m,{color:t,role:"queen"});const d=this.clone();return d.board.set(m,{color:t,role:"knight"}),h.hasInsufficientMaterial(t)&&d.hasInsufficientMaterial(t)}else{if(s.rook===1)return!(c.pawn>=2||c.rook>=1&&c.pawn>=1||c.rook>=1&&c.knight>=1||c.pawn>=1&&c.knight>=1);if(s.bishop===1)return!(p(n(a))>=2||p(n(a))>=1&&c.pawn>=1||c.pawn>=2);if(s.knight===1)return!(f>=4&&(c.knight>=2||c.pawn>=2||c.rook>=1&&c.knight>=1||c.rook>=1&&c.bishop>=1||c.knight>=1&&c.bishop>=1||c.rook>=1&&c.pawn>=1||c.knight>=1&&c.pawn>=1||c.bishop>=1&&c.pawn>=1||r(x(t))&&c.pawn>=1)&&(p("dark")<2||_(p("dark"))>=3)&&(p("light")<2||_(p("light"))>=3))}}else{if(u===2)return f===1?!0:s.knight===2?c.pawn+c.bishop+c.knight<1:r(t)?!(c.pawn>=1||c.bishop>=1||c.knight>=1&&c.rook+c.queen>=1):s.bishop>=1&&s.knight>=1?!(c.pawn>=1||p(n(a))>=1||_(p(a))>=3):!(c.pawn>=1&&p(n(a))>=1||c.pawn>=1&&c.knight>=1||p(n(a))>=1&&c.knight>=1||p(n(a))>=2||c.knight>=2||c.pawn>=2);if(u===3)return s.knight===2&&s.bishop===1||s.knight===3||r(t)?!1:f===1}return!0}isVariantEnd(){return this.board.white.isEmpty()||this.board.black.isEmpty()}variantOutcome(t){if(this.board.white.isEmpty())return{winner:"black"};if(this.board.black.isEmpty())return{winner:"white"}}}const Li=e=>{switch(e){case"chess":return Ht.default();case"antichess":return tn.default();case"atomic":return en.default();case"horde":return on.default();case"racingkings":return sn.default();case"kingofthehill":return nn.default();case"3check":return rn.default();case"crazyhouse":return Jt.default()}},$i=(e,t)=>{switch(e){case"chess":return Ht.fromSetup(t);case"antichess":return tn.fromSetup(t);case"atomic":return en.fromSetup(t);case"horde":return on.fromSetup(t);case"racingkings":return sn.fromSetup(t);case"kingofthehill":return nn.fromSetup(t);case"3check":return rn.fromSetup(t);case"crazyhouse":return Jt.fromSetup(t)}},Ii=(e=pt)=>({headers:e(),moves:new ft});class ft{constructor(){this.children=[]}*mainlineNodes(){let t=this;for(;t.children.length;){const n=t.children[0];yield n,t=n}}*mainline(){for(const t of this.mainlineNodes())yield t.data}end(){let t=this;for(;t.children.length;)t=t.children[0];return t}}class an extends ft{constructor(t){super(),this.data=t}}const zi=(e,t,n)=>{const i=new ft,r=[{before:e,after:i,ctx:t}];let s;for(;s=r.pop();)for(let o=0;o<s.before.children.length;o++){const a=o<s.before.children.length-1?s.ctx.clone():s.ctx,u=s.before.children[o],c=n(a,u.data,o);if(y(c)){const p=new an(c);s.after.children.push(p),r.push({before:u,after:p,ctx:a})}}return i},qi=e=>e?e.winner==="white"?"1-0":e.winner==="black"?"0-1":"1/2-1/2":"*",Wi=e=>e==="1-0"||e==="1–0"||e==="1—0"?{winner:"white"}:e==="0-1"||e==="0–1"||e==="0—1"?{winner:"black"}:e==="1/2-1/2"||e==="1/2–1/2"||e==="1/2—1/2"?{winner:void 0}:void 0,pt=()=>new Map([["Event","?"],["Site","?"],["Date","????.??.??"],["Round","?"],["White","?"],["Black","?"],["Result","*"]]),cn="\uFEFF",mt=e=>/^\s*$/.test(e),gt=e=>e.startsWith("%");class Fi extends Error{}class Gi{constructor(t,n=pt,i=1e6){this.emitGame=t,this.initHeaders=n,this.maxBudget=i,this.lineBuf=[],this.resetGame(),this.state=0}resetGame(){this.budget=this.maxBudget,this.found=!1,this.state=1,this.game=Ii(this.initHeaders),this.stack=[{parent:this.game.moves,root:!0}],this.commentBuf=[]}consumeBudget(t){if(this.budget-=t,this.budget<0)throw new Fi("ERR_PGN_BUDGET")}parse(t,n){if(!(this.budget<0))try{let i=0;for(;;){const r=t.indexOf(`
2
2
  `,i);if(r===-1)break;const s=r>i&&t[r-1]==="\r"?r-1:r;this.consumeBudget(r-i),this.lineBuf.push(t.slice(i,s)),i=r+1,this.handleLine()}this.consumeBudget(t.length-i),this.lineBuf.push(t.slice(i)),n!=null&&n.stream||(this.handleLine(),this.emit(void 0))}catch(i){this.emit(i)}}handleLine(){let t=!0,n=this.lineBuf.join("");this.lineBuf=[];e:for(;;)switch(this.state){case 0:n.startsWith(cn)&&(n=n.slice(cn.length)),this.state=1;case 1:if(mt(n)||gt(n))return;this.found=!0,this.state=2;case 2:{if(gt(n))return;let i=!0;for(;i;)i=!1,n=n.replace(/^\s*\[([A-Za-z0-9][A-Za-z0-9_+#=:-]*)\s+"((?:[^"\\]|\\"|\\\\)*)"\]/,(r,s,o)=>(this.consumeBudget(200),this.handleHeader(s,o.replace(/\\"/g,'"').replace(/\\\\/g,"\\")),i=!0,t=!1,""));if(mt(n))return;this.state=3}case 3:{if(t){if(gt(n))return;if(mt(n))return this.emit(void 0)}const i=/(?:[NBKRQ]?[a-h]?[1-8]?[-x]?[a-h][1-8](?:=?[nbrqkNBRQK])?|[pnbrqkPNBRQK]?@[a-h][1-8]|[O0o][-–—][O0o](?:[-–—][O0o])?)[+#]?|--|Z0|0000|@@@@|{|;|\$\d{1,4}|[?!]{1,2}|\(|\)|\*|1[-–—]0|0[-–—]1|1\/2[-–—]1\/2/g;let r;for(;r=i.exec(n);){const s=this.stack[this.stack.length-1];let o=r[0];if(o===";")return;if(o.startsWith("$"))this.handleNag(parseInt(o.slice(1),10));else if(o==="!")this.handleNag(1);else if(o==="?")this.handleNag(2);else if(o==="!!")this.handleNag(3);else if(o==="??")this.handleNag(4);else if(o==="!?")this.handleNag(5);else if(o==="?!")this.handleNag(6);else if(o==="1-0"||o==="1–0"||o==="1—0"||o==="0-1"||o==="0–1"||o==="0—1"||o==="1/2-1/2"||o==="1/2–1/2"||o==="1/2—1/2"||o==="*")this.stack.length===1&&o!=="*"&&this.handleHeader("Result",o);else if(o==="(")this.consumeBudget(100),this.stack.push({parent:s.parent,root:!1});else if(o===")")this.stack.length>1&&this.stack.pop();else if(o==="{"){const a=i.lastIndex,u=n[a]===" "?a+1:a;n=n.slice(u),this.state=4;continue e}else this.consumeBudget(100),o.startsWith("O")||o.startsWith("0")||o.startsWith("o")?o=o.replace(/[0o]/g,"O").replace(/[–—]/g,"-"):(o==="Z0"||o==="0000"||o==="@@@@")&&(o="--"),s.node&&(s.parent=s.node),s.node=new an({san:o,startingComments:s.startingComments}),s.startingComments=void 0,s.root=!1,s.parent.children.push(s.node)}return}case 4:{const i=n.indexOf("}");if(i===-1){this.commentBuf.push(n);return}else{const r=i>0&&n[i-1]===" "?i-1:i;this.commentBuf.push(n.slice(0,r)),this.handleComment(),n=n.slice(i),this.state=3,t=!1}}}}handleHeader(t,n){this.game.headers.set(t,t==="Result"?qi(Wi(n)):n)}handleNag(t){var n;this.consumeBudget(50);const i=this.stack[this.stack.length-1];i.node&&((n=i.node.data).nags||(n.nags=[]),i.node.data.nags.push(t))}handleComment(){var t,n;this.consumeBudget(100);const i=this.stack[this.stack.length-1],r=this.commentBuf.join(`
3
- `);this.commentBuf=[],i.node?((t=i.node.data).comments||(t.comments=[]),i.node.data.comments.push(r)):i.root?((n=this.game).comments||(n.comments=[]),this.game.comments.push(r)):(i.startingComments||(i.startingComments=[]),i.startingComments.push(r))}emit(t){if(this.state===4&&this.handleComment(),t)return this.emitGame(this.game,t);this.found&&this.emitGame(this.game,void 0),this.resetGame()}}const ln=(e,t=pt)=>{const n=[];return new Gi(i=>n.push(i),t,NaN).parse(e),n},Ui=e=>{switch((e||"chess").toLowerCase()){case"chess":case"chess960":case"chess 960":case"standard":case"from position":case"classical":case"normal":case"fischerandom":case"fischerrandom":case"fischer random":case"wild/0":case"wild/1":case"wild/2":case"wild/3":case"wild/4":case"wild/5":case"wild/6":case"wild/7":case"wild/8":case"wild/8a":return"chess";case"crazyhouse":case"crazy house":case"house":case"zh":return"crazyhouse";case"king of the hill":case"koth":case"kingofthehill":return"kingofthehill";case"three-check":case"three check":case"threecheck":case"three check chess":case"3-check":case"3 check":case"3check":return"3check";case"antichess":case"anti chess":case"anti":return"antichess";case"atomic":case"atom":case"atomic chess":return"atomic";case"horde":case"horde chess":return"horde";case"racing kings":case"racingkings":case"racing":case"race":return"racingkings";default:return}},Hi=e=>{const t=Ui(e.get("Variant"));if(!t)return k.err(new D(N.Variant));const n=e.get("FEN");return n?Pi(n).chain(i=>$i(t,i)):k.ok(Li(t))};function ji(e){switch(e){case"G":return"green";case"R":return"red";case"Y":return"yellow";case"B":return"blue";default:return}}const Vi=e=>{const t=ji(e.slice(0,1)),n=Ae(e.slice(1,3)),i=Ae(e.slice(3,5));if(!(!t||!y(n))){if(e.length===3)return{color:t,from:n,to:n};if(e.length===5&&y(i))return{color:t,from:n,to:i}}},Zi=e=>{let t,n,i;const r=[];return{text:e.replace(/\s?\[%(emt|clk)\s(\d{1,5}):(\d{1,2}):(\d{1,2}(?:\.\d{0,3})?)\]\s?/g,(o,a,u,c,p)=>{const f=parseInt(u,10)*3600+parseInt(c,10)*60+parseFloat(p);return a==="emt"?t=f:a==="clk"&&(n=f)," "}).replace(/\s?\[%(?:csl|cal)\s([RGYB][a-h][1-8](?:[a-h][1-8])?(?:,[RGYB][a-h][1-8](?:[a-h][1-8])?)*)\]\s?/g,(o,a)=>{for(const u of a.split(","))r.push(Vi(u));return" "}).replace(/\s?\[%eval\s(?:#([+-]?\d{1,5})|([+-]?(?:\d{1,5}|\d{0,5}\.\d{1,2})))(?:,(\d{1,5}))?\]\s?/g,(o,a,u,c)=>{const p=c&&parseInt(c,10);return i=a?{mate:parseInt(a,10),depth:p}:{pawns:parseFloat(u),depth:p}," "}).trim(),shapes:r,emt:t,clock:n,evaluation:i}};function Yi(e){return t=>e&&e(t)||Qi(t)}const Qi=e=>Xi[e],Xi={flipTheBoard:"Flip the board",analysisBoard:"Analysis board",practiceWithComputer:"Practice with computer",getPgn:"Get PGN",download:"Download",viewOnLichess:"View on Lichess",viewOnSite:"View on site"},Ji=["white","black"],ze=["a","b","c","d","e","f","g","h"],qe=["1","2","3","4","5","6","7","8"],er=[...qe].reverse(),kt=Array.prototype.concat(...ze.map(e=>qe.map(t=>e+t))),Z=e=>kt[8*e[0]+e[1]],B=e=>[e.charCodeAt(0)-97,e.charCodeAt(1)-49],tr=e=>{if(e)return e[1]==="@"?[e.slice(2,4)]:[e.slice(0,2),e.slice(2,4)]},un=kt.map(B);function nr(e){let t;const n=()=>(t===void 0&&(t=e()),t);return n.clear=()=>{t=void 0},n}const ir=()=>{let e;return{start(){e=performance.now()},cancel(){e=void 0},stop(){if(!e)return 0;const t=performance.now()-e;return e=void 0,t}}},bt=e=>e==="white"?"black":"white",Oe=(e,t)=>{const n=e[0]-t[0],i=e[1]-t[1];return n*n+i*i},wt=(e,t)=>e.role===t.role&&e.color===t.color,Re=e=>(t,n)=>[(n?t[0]:7-t[0])*e.width/8,(n?7-t[1]:t[1])*e.height/8],te=(e,t)=>{e.style.transform=`translate(${t[0]}px,${t[1]}px)`},hn=(e,t,n=1)=>{e.style.transform=`translate(${t[0]}px,${t[1]}px) scale(${n})`},yt=(e,t)=>{e.style.visibility=t?"visible":"hidden"},be=e=>{var t;if(e.clientX||e.clientX===0)return[e.clientX,e.clientY];if(!((t=e.targetTouches)===null||t===void 0)&&t[0])return[e.targetTouches[0].clientX,e.targetTouches[0].clientY]},dn=e=>e.button===2,re=(e,t)=>{const n=document.createElement(e);return t&&(n.className=t),n};function fn(e,t,n){const i=B(e);return t||(i[0]=7-i[0],i[1]=7-i[1]),[n.left+n.width*i[0]/8+n.width/16,n.top+n.height*(7-i[1])/8+n.height/16]}class J{constructor(t){this.path=t,this.size=()=>this.path.length/2,this.head=()=>this.path.slice(0,2),this.tail=()=>new J(this.path.slice(2)),this.init=()=>new J(this.path.slice(0,-2)),this.last=()=>this.path.slice(-2),this.empty=()=>this.path=="",this.contains=n=>this.path.startsWith(n.path),this.isChildOf=n=>this.init()===n,this.append=n=>new J(this.path+n),this.equals=n=>this.path==n.path}}J.root=new J("");class rr{constructor(t,n,i,r){this.initial=t,this.moves=n,this.players=i,this.metadata=r,this.nodeAt=s=>pn(this.moves,s),this.dataAt=s=>{const o=this.nodeAt(s);return o?or(o)?o.data:this.initial:void 0},this.title=()=>this.players.white.name?[this.players.white.title,this.players.white.name,"vs",this.players.black.title,this.players.black.name].filter(s=>s&&!!s.trim()).join("_").replace(" ","-"):"lichess-pgn-viewer",this.pathAtMainlinePly=s=>{var o;return s==0?J.root:((o=this.mainline[Math.max(0,Math.min(this.mainline.length-1,s=="last"?9999:s-1))])===null||o===void 0?void 0:o.path)||J.root},this.hasPlayerName=()=>{var s,o;return!!(!((s=this.players.white)===null||s===void 0)&&s.name||!((o=this.players.black)===null||o===void 0)&&o.name)},this.mainline=Array.from(this.moves.mainline())}}const sr=(e,t)=>e.children.find(n=>n.data.path.last()==t),pn=(e,t)=>{if(t.empty())return e;const n=sr(e,t.head());return n?pn(n,t.tail()):void 0},or=e=>"data"in e,ar=e=>"uci"in e;class vt{constructor(t,n,i){this.pos=t,this.path=n,this.clocks=i,this.clone=()=>new vt(this.pos.clone(),this.path,{...this.clocks})}}const Ct=e=>{const t=e.map(Zi),n=i=>i.reduce((r,s)=>typeof s==null?r:s,void 0);return{texts:t.map(i=>i.text).filter(i=>!!i),shapes:t.flatMap(i=>i.shapes),clock:n(t.map(i=>i.clock)),emt:n(t.map(i=>i.emt))}},cr=(e,t=!1)=>{var n,i;const r=ln(e)[0]||ln("*")[0],s=Hi(r.headers).unwrap(),o=Xt(s.toSetup()),a=Ct(r.comments||[]),u=new Map(Array.from(r.headers,([m,h])=>[m.toLowerCase(),h])),c=dr(u,t),p={fen:o,turn:s.turn,check:s.isCheck(),pos:s.clone(),comments:a.texts,shapes:a.shapes,clocks:{white:((n=c.timeControl)===null||n===void 0?void 0:n.initial)||a.clock,black:((i=c.timeControl)===null||i===void 0?void 0:i.initial)||a.clock}},f=lr(s,r.moves,c),_=hr(u,c);return new rr(p,f,_,c)},lr=(e,t,n)=>zi(t,new vt(e,J.root,{}),(i,r,s)=>{const o=Bi(i.pos,r.san);if(!o)return;const a=_i(o),u=i.path.append(a),c=Ni(i.pos,o);i.path=u;const p=i.pos.toSetup(),f=Ct(r.comments||[]),_=Ct(r.startingComments||[]),m=[...f.shapes,..._.shapes],h=(p.fullmoves-1)*2+(i.pos.turn==="white"?0:1);let d=i.clocks=ur(i.clocks,i.pos.turn,f.clock);return h<2&&n.timeControl&&(d={white:n.timeControl.initial,black:n.timeControl.initial,...d}),{path:u,ply:h,move:o,san:c,uci:ui(o),fen:Xt(i.pos.toSetup()),turn:i.pos.turn,check:i.pos.isCheck(),comments:f.texts,startingComments:_.texts,nags:r.nags||[],shapes:m,clocks:d,emt:f.emt}}),ur=(e,t,n)=>t=="white"?{...e,black:n}:{...e,white:n};function hr(e,t){const n=(r,s)=>{const o=e.get(`${r}${s}`);return o=="?"||o==""?void 0:o},i=r=>{const s=n(r,"");return{name:s,title:n(r,"title"),rating:parseInt(n(r,"elo")||"")||void 0,isLichessUser:t.isLichess&&!!(s!=null&&s.match(/^[a-z0-9][a-z0-9_-]{0,28}[a-z0-9]$/i))}};return{white:i("white"),black:i("black")}}function dr(e,t){var n;const i=e.get("source")||e.get("site"),r=(n=e.get("timecontrol"))===null||n===void 0?void 0:n.split("+").map(a=>parseInt(a)),s=r&&r[0]?{initial:r[0],increment:r[1]||0}:void 0,o=e.get("orientation");return{externalLink:i&&i.match(/^https?:\/\//)?i:void 0,isLichess:!!(t&&(i!=null&&i.startsWith(t))),timeControl:s,orientation:o==="white"||o==="black"?o:void 0,result:e.get("result")}}class fr{constructor(t,n){this.opts=t,this.redraw=n,this.flipped=!1,this.pane="board",this.autoScrollRequested=!1,this.curNode=()=>this.game.nodeAt(this.path)||this.game.moves,this.curData=()=>this.game.dataAt(this.path)||this.game.initial,this.goTo=(i,r=!0)=>{var s,o;const a=i=="first"?J.root:i=="prev"?this.path.init():i=="next"?(o=(s=this.game.nodeAt(this.path))===null||s===void 0?void 0:s.children[0])===null||o===void 0?void 0:o.data.path:this.game.pathAtMainlinePly("last");this.toPath(a||this.path,r)},this.canGoTo=i=>i=="prev"||i=="first"?!this.path.empty():!!this.curNode().children[0],this.toPath=(i,r=!0)=>{this.path=i,this.pane="board",this.autoScrollRequested=!0,this.redrawGround(),this.redraw(),r&&this.focus()},this.focus=()=>{var i;return(i=this.div)===null||i===void 0?void 0:i.focus()},this.toggleMenu=()=>{this.pane=this.pane=="board"?"menu":"board",this.redraw()},this.togglePgn=()=>{this.pane=this.pane=="pgn"?"board":"pgn",this.redraw()},this.orientation=()=>{const i=this.opts.orientation||"white";return this.flipped?x(i):i},this.flip=()=>{this.flipped=!this.flipped,this.pane="board",this.redrawGround(),this.redraw()},this.cgState=()=>{var i;const r=this.curData(),s=ar(r)?tr(r.uci):(i=this.opts.chessground)===null||i===void 0?void 0:i.lastMove;return{fen:r.fen,orientation:this.orientation(),check:r.check,lastMove:s,turnColor:r.turn}},this.analysisUrl=()=>this.game.metadata.isLichess&&this.game.metadata.externalLink||`https://lichess.org/analysis/${this.curData().fen.replace(" ","_")}?color=${this.orientation()}`,this.practiceUrl=()=>`${this.analysisUrl()}#practice`,this.setGround=i=>{this.ground=i,this.redrawGround()},this.redrawGround=()=>this.withGround(i=>{i.set(this.cgState()),i.setShapes(this.curData().shapes.map(r=>({orig:ae(r.from),dest:ae(r.to),brush:r.color})))}),this.withGround=i=>this.ground&&i(this.ground),this.game=cr(t.pgn,t.lichess),t.orientation=t.orientation||this.game.metadata.orientation,this.translate=Yi(t.translate),this.path=this.game.pathAtMainlinePly(t.initialPly)}}const we=(e,t)=>Math.abs(e-t),pr=e=>(t,n,i,r)=>we(t,i)<2&&(e==="white"?r===n+1||n<=1&&r===n+2&&t===i:r===n-1||n>=6&&r===n-2&&t===i),mn=(e,t,n,i)=>{const r=we(e,n),s=we(t,i);return r===1&&s===2||r===2&&s===1},gn=(e,t,n,i)=>we(e,n)===we(t,i),kn=(e,t,n,i)=>e===n||t===i,bn=(e,t,n,i)=>gn(e,t,n,i)||kn(e,t,n,i),mr=(e,t,n)=>(i,r,s,o)=>we(i,s)<2&&we(r,o)<2||n&&r===o&&r===(e==="white"?0:7)&&(i===4&&(s===2&&t.includes(0)||s===6&&t.includes(7))||t.includes(s));function gr(e,t){const n=t==="white"?"1":"8",i=[];for(const[r,s]of e)r[1]===n&&s.color===t&&s.role==="rook"&&i.push(B(r)[0]);return i}function wn(e,t,n){const i=e.get(t);if(!i)return[];const r=B(t),s=i.role,o=s==="pawn"?pr(i.color):s==="knight"?mn:s==="bishop"?gn:s==="rook"?kn:s==="queen"?bn:mr(i.color,gr(e,i.color),n);return un.filter(a=>(r[0]!==a[0]||r[1]!==a[1])&&o(r[0],r[1],a[0],a[1])).map(Z)}function F(e,...t){e&&setTimeout(()=>e(...t),1)}function kr(e){e.orientation=bt(e.orientation),e.animation.current=e.draggable.current=e.selected=void 0}function br(e,t){for(const[n,i]of t)i?e.pieces.set(n,i):e.pieces.delete(n)}function wr(e,t){if(e.check=void 0,t===!0&&(t=e.turnColor),t)for(const[n,i]of e.pieces)i.role==="king"&&i.color===t&&(e.check=n)}function yr(e,t,n,i){de(e),e.premovable.current=[t,n],F(e.premovable.events.set,t,n,i)}function he(e){e.premovable.current&&(e.premovable.current=void 0,F(e.premovable.events.unset))}function vr(e,t,n){he(e),e.predroppable.current={role:t,key:n},F(e.predroppable.events.set,t,n)}function de(e){const t=e.predroppable;t.current&&(t.current=void 0,F(t.events.unset))}function Cr(e,t,n){if(!e.autoCastle)return!1;const i=e.pieces.get(t);if(!i||i.role!=="king")return!1;const r=B(t),s=B(n);if(r[1]!==0&&r[1]!==7||r[1]!==s[1])return!1;r[0]===4&&!e.pieces.has(n)&&(s[0]===6?n=Z([7,s[1]]):s[0]===2&&(n=Z([0,s[1]])));const o=e.pieces.get(n);return!o||o.color!==i.color||o.role!=="rook"?!1:(e.pieces.delete(t),e.pieces.delete(n),r[0]<s[0]?(e.pieces.set(Z([6,s[1]]),i),e.pieces.set(Z([5,s[1]]),o)):(e.pieces.set(Z([2,s[1]]),i),e.pieces.set(Z([3,s[1]]),o)),!0)}function yn(e,t,n){const i=e.pieces.get(t),r=e.pieces.get(n);if(t===n||!i)return!1;const s=r&&r.color!==i.color?r:void 0;return n===e.selected&&Y(e),F(e.events.move,t,n,s),Cr(e,t,n)||(e.pieces.set(n,i),e.pieces.delete(t)),e.lastMove=[t,n],e.check=void 0,F(e.events.change),s||!0}function _t(e,t,n,i){if(e.pieces.has(n))if(i)e.pieces.delete(n);else return!1;return F(e.events.dropNewPiece,t,n),e.pieces.set(n,t),e.lastMove=[n],e.check=void 0,F(e.events.change),e.movable.dests=void 0,e.turnColor=bt(e.turnColor),!0}function vn(e,t,n){const i=yn(e,t,n);return i&&(e.movable.dests=void 0,e.turnColor=bt(e.turnColor),e.animation.current=void 0),i}function Cn(e,t,n){if(St(e,t,n)){const i=vn(e,t,n);if(i){const r=e.hold.stop();Y(e);const s={premove:!1,ctrlKey:e.stats.ctrlKey,holdTime:r};return i!==!0&&(s.captured=i),F(e.movable.events.after,t,n,s),!0}}else if(Er(e,t,n))return yr(e,t,n,{ctrlKey:e.stats.ctrlKey}),Y(e),!0;return Y(e),!1}function _n(e,t,n,i){const r=e.pieces.get(t);r&&(_r(e,t,n)||i)?(e.pieces.delete(t),_t(e,r,n,i),F(e.movable.events.afterNewPiece,r.role,n,{premove:!1,predrop:!1})):r&&Sr(e,t,n)?vr(e,r.role,n):(he(e),de(e)),e.pieces.delete(t),Y(e)}function Et(e,t,n){if(F(e.events.select,t),e.selected){if(e.selected===t&&!e.draggable.enabled){Y(e),e.hold.cancel();return}else if((e.selectable.enabled||n)&&e.selected!==t&&Cn(e,e.selected,t)){e.stats.dragged=!1;return}}(e.selectable.enabled||e.draggable.enabled)&&(Sn(e,t)||Pt(e,t))&&(En(e,t),e.hold.start())}function En(e,t){e.selected=t,Pt(e,t)?e.premovable.customDests||(e.premovable.dests=wn(e.pieces,t,e.premovable.castle)):e.premovable.dests=void 0}function Y(e){e.selected=void 0,e.premovable.dests=void 0,e.hold.cancel()}function Sn(e,t){const n=e.pieces.get(t);return!!n&&(e.movable.color==="both"||e.movable.color===n.color&&e.turnColor===n.color)}const St=(e,t,n)=>{var i,r;return t!==n&&Sn(e,t)&&(e.movable.free||!!(!((r=(i=e.movable.dests)===null||i===void 0?void 0:i.get(t))===null||r===void 0)&&r.includes(n)))};function _r(e,t,n){const i=e.pieces.get(t);return!!i&&(t===n||!e.pieces.has(n))&&(e.movable.color==="both"||e.movable.color===i.color&&e.turnColor===i.color)}function Pt(e,t){const n=e.pieces.get(t);return!!n&&e.premovable.enabled&&e.movable.color===n.color&&e.turnColor!==n.color}function Er(e,t,n){var i,r;const s=(r=(i=e.premovable.customDests)===null||i===void 0?void 0:i.get(t))!==null&&r!==void 0?r:wn(e.pieces,t,e.premovable.castle);return t!==n&&Pt(e,t)&&s.includes(n)}function Sr(e,t,n){const i=e.pieces.get(t),r=e.pieces.get(n);return!!i&&(!r||r.color!==e.movable.color)&&e.predroppable.enabled&&(i.role!=="pawn"||n[1]!=="1"&&n[1]!=="8")&&e.movable.color===i.color&&e.turnColor!==i.color}function Pr(e,t){const n=e.pieces.get(t);return!!n&&e.draggable.enabled&&(e.movable.color==="both"||e.movable.color===n.color&&(e.turnColor===n.color||e.premovable.enabled))}function xr(e){const t=e.premovable.current;if(!t)return!1;const n=t[0],i=t[1];let r=!1;if(St(e,n,i)){const s=vn(e,n,i);if(s){const o={premove:!0};s!==!0&&(o.captured=s),F(e.movable.events.after,n,i,o),r=!0}}return he(e),r}function Mr(e,t){const n=e.predroppable.current;let i=!1;if(!n)return!1;if(t(n)){const r={role:n.role,color:e.movable.color};_t(e,r,n.key)&&(F(e.movable.events.afterNewPiece,n.role,n.key,{premove:!1,predrop:!0}),i=!0)}return de(e),i}function xt(e){he(e),de(e),Y(e)}function Pn(e){e.movable.color=e.movable.dests=e.animation.current=void 0,xt(e)}function ye(e,t,n){let i=Math.floor(8*(e[0]-n.left)/n.width);t||(i=7-i);let r=7-Math.floor(8*(e[1]-n.top)/n.height);return t||(r=7-r),i>=0&&i<8&&r>=0&&r<8?Z([i,r]):void 0}function Ar(e,t,n,i){const r=B(e),s=un.filter(c=>bn(r[0],r[1],c[0],c[1])||mn(r[0],r[1],c[0],c[1])),a=s.map(c=>fn(Z(c),n,i)).map(c=>Oe(t,c)),[,u]=a.reduce((c,p,f)=>c[0]<p?c:[p,f],[a[0],0]);return Z(s[u])}const G=e=>e.orientation==="white",xn="rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR",Or={p:"pawn",r:"rook",n:"knight",b:"bishop",q:"queen",k:"king"},Rr={pawn:"p",rook:"r",knight:"n",bishop:"b",queen:"q",king:"k"};function Mn(e){e==="start"&&(e=xn);const t=new Map;let n=7,i=0;for(const r of e)switch(r){case" ":case"[":return t;case"/":if(--n,n<0)return t;i=0;break;case"~":{const s=t.get(Z([i-1,n]));s&&(s.promoted=!0);break}default:{const s=r.charCodeAt(0);if(s<57)i+=s-48;else{const o=r.toLowerCase();t.set(Z([i,n]),{role:Or[o],color:r===o?"black":"white"}),++i}}}return t}function Tr(e){return er.map(t=>ze.map(n=>{const i=e.get(n+t);if(i){let r=Rr[i.role];return i.color==="white"&&(r=r.toUpperCase()),i.promoted&&(r+="~"),r}else return"1"}).join("")).join("/").replace(/1{2,}/g,t=>t.length.toString())}function An(e,t){t.animation&&(Mt(e.animation,t.animation),(e.animation.duration||0)<70&&(e.animation.enabled=!1))}function On(e,t){var n,i,r;if(!((n=t.movable)===null||n===void 0)&&n.dests&&(e.movable.dests=void 0),!((i=t.drawable)===null||i===void 0)&&i.autoShapes&&(e.drawable.autoShapes=[]),Mt(e,t),t.fen&&(e.pieces=Mn(t.fen),e.drawable.shapes=((r=t.drawable)===null||r===void 0?void 0:r.shapes)||[]),"check"in t&&wr(e,t.check||!1),"lastMove"in t&&!t.lastMove?e.lastMove=void 0:t.lastMove&&(e.lastMove=t.lastMove),e.selected&&En(e,e.selected),An(e,t),!e.movable.rookCastle&&e.movable.dests){const s=e.movable.color==="white"?"1":"8",o="e"+s,a=e.movable.dests.get(o),u=e.pieces.get(o);if(!a||!u||u.role!=="king")return;e.movable.dests.set(o,a.filter(c=>!(c==="a"+s&&a.includes("c"+s))&&!(c==="h"+s&&a.includes("g"+s))))}}function Mt(e,t){for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(Object.prototype.hasOwnProperty.call(e,n)&&Rn(e[n])&&Rn(t[n])?Mt(e[n],t[n]):e[n]=t[n])}function Rn(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}const ve=(e,t)=>t.animation.enabled?Dr(e,t):fe(e,t);function fe(e,t){const n=e(t);return t.dom.redraw(),n}const At=(e,t)=>({key:e,pos:B(e),piece:t}),Nr=(e,t)=>t.sort((n,i)=>Oe(e.pos,n.pos)-Oe(e.pos,i.pos))[0];function Br(e,t){const n=new Map,i=[],r=new Map,s=[],o=[],a=new Map;let u,c,p;for(const[f,_]of e)a.set(f,At(f,_));for(const f of kt)u=t.pieces.get(f),c=a.get(f),u?c?wt(u,c.piece)||(s.push(c),o.push(At(f,u))):o.push(At(f,u)):c&&s.push(c);for(const f of o)c=Nr(f,s.filter(_=>wt(f.piece,_.piece))),c&&(p=[c.pos[0]-f.pos[0],c.pos[1]-f.pos[1]],n.set(f.key,p.concat(p)),i.push(c.key));for(const f of s)i.includes(f.key)||r.set(f.key,f.piece);return{anims:n,fadings:r}}function Tn(e,t){const n=e.animation.current;if(n===void 0){e.dom.destroyed||e.dom.redrawNow();return}const i=1-(t-n.start)*n.frequency;if(i<=0)e.animation.current=void 0,e.dom.redrawNow();else{const r=Kr(i);for(const s of n.plan.anims.values())s[2]=s[0]*r,s[3]=s[1]*r;e.dom.redrawNow(!0),requestAnimationFrame((s=performance.now())=>Tn(e,s))}}function Dr(e,t){const n=new Map(t.pieces),i=e(t),r=Br(n,t);if(r.anims.size||r.fadings.size){const s=t.animation.current&&t.animation.current.start;t.animation.current={start:performance.now(),frequency:1/t.animation.duration,plan:r},s||Tn(t,performance.now())}else t.dom.redraw();return i}const Kr=e=>e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1,Lr=["green","red","blue","yellow"];function $r(e,t){if(t.touches&&t.touches.length>1)return;t.stopPropagation(),t.preventDefault(),t.ctrlKey?Y(e):xt(e);const n=be(t),i=ye(n,G(e),e.dom.bounds());i&&(e.drawable.current={orig:i,pos:n,brush:Wr(t),snapToValidMove:e.drawable.defaultSnapToValidMove},Nn(e))}function Nn(e){requestAnimationFrame(()=>{const t=e.drawable.current;if(t){const n=ye(t.pos,G(e),e.dom.bounds());n||(t.snapToValidMove=!1);const i=t.snapToValidMove?Ar(t.orig,t.pos,G(e),e.dom.bounds()):n;i!==t.mouseSq&&(t.mouseSq=i,t.dest=i!==t.orig?i:void 0,e.dom.redrawNow()),Nn(e)}})}function Ir(e,t){e.drawable.current&&(e.drawable.current.pos=be(t))}function zr(e){const t=e.drawable.current;t&&(t.mouseSq&&Fr(e.drawable,t),Bn(e))}function Bn(e){e.drawable.current&&(e.drawable.current=void 0,e.dom.redraw())}function qr(e){e.drawable.shapes.length&&(e.drawable.shapes=[],e.dom.redraw(),Dn(e.drawable))}function Wr(e){var t;const n=(e.shiftKey||e.ctrlKey)&&dn(e),i=e.altKey||e.metaKey||((t=e.getModifierState)===null||t===void 0?void 0:t.call(e,"AltGraph"));return Lr[(n?1:0)+(i?2:0)]}function Fr(e,t){const n=r=>r.orig===t.orig&&r.dest===t.dest,i=e.shapes.find(n);i&&(e.shapes=e.shapes.filter(r=>!n(r))),(!i||i.brush!==t.brush)&&e.shapes.push({orig:t.orig,dest:t.dest,brush:t.brush}),Dn(e)}function Dn(e){e.onChange&&e.onChange(e.shapes)}function Gr(e,t){if(!(e.trustAllEvents||t.isTrusted)||t.buttons!==void 0&&t.buttons>1||t.touches&&t.touches.length>1)return;const n=e.dom.bounds(),i=be(t),r=ye(i,G(e),n);if(!r)return;const s=e.pieces.get(r),o=e.selected;if(!o&&e.drawable.enabled&&(e.drawable.eraseOnClick||!s||s.color!==e.turnColor)&&qr(e),t.cancelable!==!1&&(!t.touches||e.blockTouchScroll||s||o||Ur(e,i)))t.preventDefault();else if(t.touches)return;const a=!!e.premovable.current,u=!!e.predroppable.current;e.stats.ctrlKey=t.ctrlKey,e.selected&&St(e,e.selected,r)?ve(f=>Et(f,r),e):Et(e,r);const c=e.selected===r,p=Ln(e,r);if(s&&p&&c&&Pr(e,r)){e.draggable.current={orig:r,piece:s,origPos:i,pos:i,started:e.draggable.autoDistance&&e.stats.dragged,element:p,previouslySelected:o,originTarget:t.target,keyHasChanged:!1},p.cgDragging=!0,p.classList.add("dragging");const f=e.dom.elements.ghost;f&&(f.className=`ghost ${s.color} ${s.role}`,te(f,Re(n)(B(r),G(e))),yt(f,!0)),Ot(e)}else a&&he(e),u&&de(e);e.dom.redraw()}function Ur(e,t){const n=G(e),i=e.dom.bounds(),r=Math.pow(i.width/8,2);for(const s of e.pieces.keys()){const o=fn(s,n,i);if(Oe(o,t)<=r)return!0}return!1}function Hr(e,t,n,i){const r="a0";e.pieces.set(r,t),e.dom.redraw();const s=be(n);e.draggable.current={orig:r,piece:t,origPos:s,pos:s,started:!0,element:()=>Ln(e,r),originTarget:n.target,newPiece:!0,force:!!i,keyHasChanged:!1},Ot(e)}function Ot(e){requestAnimationFrame(()=>{var t;const n=e.draggable.current;if(!n)return;!((t=e.animation.current)===null||t===void 0)&&t.plan.anims.has(n.orig)&&(e.animation.current=void 0);const i=e.pieces.get(n.orig);if(!i||!wt(i,n.piece))We(e);else if(!n.started&&Oe(n.pos,n.origPos)>=Math.pow(e.draggable.distance,2)&&(n.started=!0),n.started){if(typeof n.element=="function"){const s=n.element();if(!s)return;s.cgDragging=!0,s.classList.add("dragging"),n.element=s}const r=e.dom.bounds();te(n.element,[n.pos[0]-r.left-r.width/16,n.pos[1]-r.top-r.height/16]),n.keyHasChanged||(n.keyHasChanged=n.orig!==ye(n.pos,G(e),r))}Ot(e)})}function jr(e,t){e.draggable.current&&(!t.touches||t.touches.length<2)&&(e.draggable.current.pos=be(t))}function Vr(e,t){const n=e.draggable.current;if(!n)return;if(t.type==="touchend"&&t.cancelable!==!1&&t.preventDefault(),t.type==="touchend"&&n.originTarget!==t.target&&!n.newPiece){e.draggable.current=void 0;return}he(e),de(e);const i=be(t)||n.pos,r=ye(i,G(e),e.dom.bounds());r&&n.started&&n.orig!==r?n.newPiece?_n(e,n.orig,r,n.force):(e.stats.ctrlKey=t.ctrlKey,Cn(e,n.orig,r)&&(e.stats.dragged=!0)):n.newPiece?e.pieces.delete(n.orig):e.draggable.deleteOnDropOff&&!r&&(e.pieces.delete(n.orig),F(e.events.change)),(n.orig===n.previouslySelected||n.keyHasChanged)&&(n.orig===r||!r)?Y(e):e.selectable.enabled||Y(e),Kn(e),e.draggable.current=void 0,e.dom.redraw()}function We(e){const t=e.draggable.current;t&&(t.newPiece&&e.pieces.delete(t.orig),e.draggable.current=void 0,Y(e),Kn(e),e.dom.redraw())}function Kn(e){const t=e.dom.elements;t.ghost&&yt(t.ghost,!1)}function Ln(e,t){let n=e.dom.elements.board.firstChild;for(;n;){if(n.cgKey===t&&n.tagName==="PIECE")return n;n=n.nextSibling}}function Zr(e,t){e.exploding={stage:1,keys:t},e.dom.redraw(),setTimeout(()=>{$n(e,2),setTimeout(()=>$n(e,void 0),120)},120)}function $n(e,t){e.exploding&&(t?e.exploding.stage=t:e.exploding=void 0,e.dom.redraw())}function Yr(e,t){function n(){kr(e),t()}return{set(i){i.orientation&&i.orientation!==e.orientation&&n(),An(e,i),(i.fen?ve:fe)(r=>On(r,i),e)},state:e,getFen:()=>Tr(e.pieces),toggleOrientation:n,setPieces(i){ve(r=>br(r,i),e)},selectSquare(i,r){i?ve(s=>Et(s,i,r),e):e.selected&&(Y(e),e.dom.redraw())},move(i,r){ve(s=>yn(s,i,r),e)},newPiece(i,r){ve(s=>_t(s,i,r),e)},playPremove(){if(e.premovable.current){if(ve(xr,e))return!0;e.dom.redraw()}return!1},playPredrop(i){if(e.predroppable.current){const r=Mr(e,i);return e.dom.redraw(),r}return!1},cancelPremove(){fe(he,e)},cancelPredrop(){fe(de,e)},cancelMove(){fe(i=>{xt(i),We(i)},e)},stop(){fe(i=>{Pn(i),We(i)},e)},explode(i){Zr(e,i)},setAutoShapes(i){fe(r=>r.drawable.autoShapes=i,e)},setShapes(i){fe(r=>r.drawable.shapes=i,e)},getKeyAtDomPos(i){return ye(i,G(e),e.dom.bounds())},redrawAll:t,dragNewPiece(i,r,s){Hr(e,i,r,s)},destroy(){Pn(e),e.dom.unbind&&e.dom.unbind(),e.dom.destroyed=!0}}}function Qr(){return{pieces:Mn(xn),orientation:"white",turnColor:"white",coordinates:!0,coordinatesOnSquares:!1,ranksPosition:"right",autoCastle:!0,viewOnly:!1,disableContextMenu:!1,addPieceZIndex:!1,blockTouchScroll:!1,pieceKey:!1,trustAllEvents:!1,highlight:{lastMove:!0,check:!0},animation:{enabled:!0,duration:200},movable:{free:!0,color:"both",showDests:!0,events:{},rookCastle:!0},premovable:{enabled:!0,showDests:!0,castle:!0,events:{}},predroppable:{enabled:!1,events:{}},draggable:{enabled:!0,distance:3,autoDistance:!0,showGhost:!0,deleteOnDropOff:!1},dropmode:{active:!1},selectable:{enabled:!0},stats:{dragged:!("ontouchstart"in window)},events:{},drawable:{enabled:!0,visible:!0,defaultSnapToValidMove:!0,eraseOnClick:!0,shapes:[],autoShapes:[],brushes:{green:{key:"g",color:"#15781B",opacity:1,lineWidth:10},red:{key:"r",color:"#882020",opacity:1,lineWidth:10},blue:{key:"b",color:"#003088",opacity:1,lineWidth:10},yellow:{key:"y",color:"#e68f00",opacity:1,lineWidth:10},paleBlue:{key:"pb",color:"#003088",opacity:.4,lineWidth:15},paleGreen:{key:"pg",color:"#15781B",opacity:.4,lineWidth:15},paleRed:{key:"pr",color:"#882020",opacity:.4,lineWidth:15},paleGrey:{key:"pgr",color:"#4a4a4a",opacity:.35,lineWidth:15},purple:{key:"purple",color:"#68217a",opacity:.65,lineWidth:10},pink:{key:"pink",color:"#ee2080",opacity:.5,lineWidth:10},white:{key:"white",color:"white",opacity:1,lineWidth:10}},prevSvgHash:""},hold:ir()}}const In={hilitePrimary:{key:"hilitePrimary",color:"#3291ff",opacity:1,lineWidth:1},hiliteWhite:{key:"hiliteWhite",color:"#ffffff",opacity:1,lineWidth:1}};function Xr(){const e=L("defs"),t=W(L("filter"),{id:"cg-filter-blur"});return t.appendChild(W(L("feGaussianBlur"),{stdDeviation:"0.019"})),e.appendChild(t),e}function Jr(e,t,n){var i;const r=e.drawable,s=r.current,o=s&&s.mouseSq?s:void 0,a=new Map,u=e.dom.bounds(),c=r.autoShapes.filter(m=>!m.piece);for(const m of r.shapes.concat(c).concat(o?[o]:[])){if(!m.dest)continue;const h=(i=a.get(m.dest))!==null&&i!==void 0?i:new Set,d=Ue(Ge(B(m.orig),e.orientation),u),b=Ue(Ge(B(m.dest),e.orientation),u);h.add(Tt(d,b)),a.set(m.dest,h)}const p=r.shapes.concat(c).map(m=>({shape:m,current:!1,hash:zn(m,Rt(m.dest,a),!1,u)}));o&&p.push({shape:o,current:!0,hash:zn(o,Rt(o.dest,a),!0,u)});const f=p.map(m=>m.hash).join(";");if(f===e.drawable.prevSvgHash)return;e.drawable.prevSvgHash=f;const _=t.querySelector("defs");es(r,p,_),ts(p,t.querySelector("g"),n.querySelector("g"),m=>rs(e,m,r.brushes,a,u))}function es(e,t,n){var i;const r=new Map;let s;for(const u of t.filter(c=>c.shape.dest&&c.shape.brush))s=Wn(e.brushes[u.shape.brush],u.shape.modifiers),!((i=u.shape.modifiers)===null||i===void 0)&&i.hilite&&r.set(Fe(s).key,Fe(s)),r.set(s.key,s);const o=new Set;let a=n.firstElementChild;for(;a;)o.add(a.getAttribute("cgKey")),a=a.nextElementSibling;for(const[u,c]of r.entries())o.has(u)||n.appendChild(as(c))}function ts(e,t,n,i){const r=new Map;for(const s of e)r.set(s.hash,!1);for(const s of[t,n]){const o=[];let a=s.firstElementChild,u;for(;a;)u=a.getAttribute("cgHash"),r.has(u)?r.set(u,!0):o.push(a),a=a.nextElementSibling;for(const c of o)s.removeChild(c)}for(const s of e.filter(o=>!r.get(o.hash)))for(const o of i(s))o.isCustom?n.appendChild(o.el):t.appendChild(o.el)}function zn({orig:e,dest:t,brush:n,piece:i,modifiers:r,customSvg:s,label:o},a,u,c){var p,f;return[c.width,c.height,u,e,t,n,a&&"-",i&&ns(i),r&&is(r),s&&`custom-${qn(s.html)},${(f=(p=s.center)===null||p===void 0?void 0:p[0])!==null&&f!==void 0?f:"o"}`,o&&`label-${qn(o.text)}`].filter(_=>_).join(",")}function ns(e){return[e.color,e.role,e.scale].filter(t=>t).join(",")}function is(e){return[e.lineWidth,e.hilite&&"*"].filter(t=>t).join(",")}function qn(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)>>>0;return t.toString()}function rs(e,{shape:t,current:n,hash:i},r,s,o){var a,u;const c=Ue(Ge(B(t.orig),e.orientation),o),p=t.dest?Ue(Ge(B(t.dest),e.orientation),o):c,f=t.brush&&Wn(r[t.brush],t.modifiers),_=s.get(t.dest),m=[];if(f){const h=W(L("g"),{cgHash:i});m.push({el:h}),c[0]!==p[0]||c[1]!==p[1]?h.appendChild(os(t,f,c,p,n,Rt(t.dest,s))):h.appendChild(ss(r[t.brush],c,n,o))}if(t.label){const h=t.label;(a=h.fill)!==null&&a!==void 0||(h.fill=t.brush&&r[t.brush].color);const d=t.brush?void 0:"tr";m.push({el:cs(h,i,c,p,_,d),isCustom:!0})}if(t.customSvg){const h=(u=t.customSvg.center)!==null&&u!==void 0?u:"orig",[d,b]=h==="label"?Gn(c,p,_).map(v=>v-.5):h==="dest"?p:c,g=W(L("g"),{transform:`translate(${d},${b})`,cgHash:i});g.innerHTML=`<svg width="1" height="1" viewBox="0 0 100 100">${t.customSvg.html}</svg>`,m.push({el:g,isCustom:!0})}return m}function ss(e,t,n,i){const r=ls(),s=(i.width+i.height)/(4*Math.max(i.width,i.height));return W(L("circle"),{stroke:e.color,"stroke-width":r[n?0:1],fill:"none",opacity:Fn(e,n),cx:t[0],cy:t[1],r:s-r[1]/2})}function Fe(e){return["#ffffff","#fff","white"].includes(e.color)?In.hilitePrimary:In.hiliteWhite}function os(e,t,n,i,r,s){var o;function a(p){var f;const _=hs(s&&!r),m=i[0]-n[0],h=i[1]-n[1],d=Math.atan2(h,m),b=Math.cos(d)*_,g=Math.sin(d)*_;return W(L("line"),{stroke:p?Fe(t).color:t.color,"stroke-width":us(t,r)+(p?.04:0),"stroke-linecap":"round","marker-end":`url(#arrowhead-${p?Fe(t).key:t.key})`,opacity:!((f=e.modifiers)===null||f===void 0)&&f.hilite?1:Fn(t,r),x1:n[0],y1:n[1],x2:i[0]-b,y2:i[1]-g})}if(!(!((o=e.modifiers)===null||o===void 0)&&o.hilite))return a(!1);const u=L("g"),c=W(L("g"),{filter:"url(#cg-filter-blur)"});return c.appendChild(ds(n,i)),c.appendChild(a(!0)),u.appendChild(c),u.appendChild(a(!1)),u}function as(e){const t=W(L("marker"),{id:"arrowhead-"+e.key,orient:"auto",overflow:"visible",markerWidth:4,markerHeight:4,refX:e.key.startsWith("hilite")?1.86:2.05,refY:2});return t.appendChild(W(L("path"),{d:"M0,0 V4 L3,2 Z",fill:e.color})),t.setAttribute("cgKey",e.key),t}function cs(e,t,n,i,r,s){var o;const u=.4*.75**e.text.length,c=Gn(n,i,r),p=s==="tr"?.4:0,f=W(L("g"),{transform:`translate(${c[0]+p},${c[1]-p})`,cgHash:t});f.appendChild(W(L("circle"),{r:.4/2,"fill-opacity":s?1:.8,"stroke-opacity":s?1:.7,"stroke-width":.03,fill:(o=e.fill)!==null&&o!==void 0?o:"#666",stroke:"white"}));const _=W(L("text"),{"font-size":u,"font-family":"Noto Sans","text-anchor":"middle",fill:"white",y:.13*.75**e.text.length});return _.innerHTML=e.text,f.appendChild(_),f}function Ge(e,t){return t==="white"?e:[7-e[0],7-e[1]]}function Rt(e,t){return(e&&t.has(e)&&t.get(e).size>1)===!0}function L(e){return document.createElementNS("http://www.w3.org/2000/svg",e)}function W(e,t){for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.setAttribute(n,t[n]);return e}function Wn(e,t){return t?{color:e.color,opacity:Math.round(e.opacity*10)/10,lineWidth:Math.round(t.lineWidth||e.lineWidth),key:[e.key,t.lineWidth].filter(n=>n).join("")}:e}function ls(){return[3/64,4/64]}function us(e,t){return(e.lineWidth||10)*(t?.85:1)/64}function Fn(e,t){return(e.opacity||1)*(t?.9:1)}function hs(e){return(e?20:10)/64}function Ue(e,t){const n=Math.min(1,t.width/t.height),i=Math.min(1,t.height/t.width);return[(e[0]-3.5)*n,(3.5-e[1])*i]}function ds(e,t){const n={from:[Math.floor(Math.min(e[0],t[0])),Math.floor(Math.min(e[1],t[1]))],to:[Math.ceil(Math.max(e[0],t[0])),Math.ceil(Math.max(e[1],t[1]))]};return W(L("rect"),{x:n.from[0],y:n.from[1],width:n.to[0]-n.from[0],height:n.to[1]-n.from[1],fill:"none",stroke:"none"})}function Tt(e,t,n=!0){const i=Math.atan2(t[1]-e[1],t[0]-e[0])+Math.PI;return n?(Math.round(i*8/Math.PI)+16)%16:i}function fs(e,t){return Math.sqrt([e[0]-t[0],e[1]-t[1]].reduce((n,i)=>n+i*i,0))}function Gn(e,t,n){let i=fs(e,t);const r=Tt(e,t,!1);if(n&&(i-=33/64,n.size>1)){i-=10/64;const s=Tt(e,t);(n.has((s+1)%16)||n.has((s+15)%16))&&s&1&&(i-=.4)}return[e[0]-Math.cos(r)*i,e[1]-Math.sin(r)*i].map(s=>s+.5)}function ps(e,t){e.innerHTML="",e.classList.add("cg-wrap");for(const u of Ji)e.classList.toggle("orientation-"+u,t.orientation===u);e.classList.toggle("manipulable",!t.viewOnly);const n=re("cg-container");e.appendChild(n);const i=re("cg-board");n.appendChild(i);let r,s,o;if(t.drawable.visible&&(r=W(L("svg"),{class:"cg-shapes",viewBox:"-4 -4 8 8",preserveAspectRatio:"xMidYMid slice"}),r.appendChild(Xr()),r.appendChild(L("g")),s=W(L("svg"),{class:"cg-custom-svgs",viewBox:"-3.5 -3.5 8 8",preserveAspectRatio:"xMidYMid slice"}),s.appendChild(L("g")),o=re("cg-auto-pieces"),n.appendChild(r),n.appendChild(s),n.appendChild(o)),t.coordinates){const u=t.orientation==="black"?" black":"",c=t.ranksPosition==="left"?" left":"";if(t.coordinatesOnSquares){const p=t.orientation==="white"?f=>f+1:f=>8-f;ze.forEach((f,_)=>n.appendChild(Nt(qe.map(m=>f+m),"squares rank"+p(_)+u+c)))}else n.appendChild(Nt(qe,"ranks"+u+c)),n.appendChild(Nt(ze,"files"+u))}let a;return t.draggable.enabled&&t.draggable.showGhost&&(a=re("piece","ghost"),yt(a,!1),n.appendChild(a)),{board:i,container:n,wrap:e,ghost:a,svg:r,customSvg:s,autoPieces:o}}function Nt(e,t){const n=re("coords",t);let i;for(const r of e)i=re("coord"),i.textContent=r,n.appendChild(i);return n}function ms(e,t){if(!e.dropmode.active)return;he(e),de(e);const n=e.dropmode.piece;if(n){e.pieces.set("a0",n);const i=be(t),r=i&&ye(i,G(e),e.dom.bounds());r&&_n(e,"a0",r)}e.dom.redraw()}function gs(e,t){const n=e.dom.elements.board;if("ResizeObserver"in window&&new ResizeObserver(t).observe(e.dom.elements.wrap),(e.disableContextMenu||e.drawable.enabled)&&n.addEventListener("contextmenu",r=>r.preventDefault()),e.viewOnly)return;const i=bs(e);n.addEventListener("touchstart",i,{passive:!1}),n.addEventListener("mousedown",i,{passive:!1})}function ks(e,t){const n=[];if("ResizeObserver"in window||n.push(Te(document.body,"chessground.resize",t)),!e.viewOnly){const i=Un(e,jr,Ir),r=Un(e,Vr,zr);for(const o of["touchmove","mousemove"])n.push(Te(document,o,i));for(const o of["touchend","mouseup"])n.push(Te(document,o,r));const s=()=>e.dom.bounds.clear();n.push(Te(document,"scroll",s,{capture:!0,passive:!0})),n.push(Te(window,"resize",s,{passive:!0}))}return()=>n.forEach(i=>i())}function Te(e,t,n,i){return e.addEventListener(t,n,i),()=>e.removeEventListener(t,n,i)}const bs=e=>t=>{e.draggable.current?We(e):e.drawable.current?Bn(e):t.shiftKey||dn(t)?e.drawable.enabled&&$r(e,t):e.viewOnly||(e.dropmode.active?ms(e,t):Gr(e,t))},Un=(e,t,n)=>i=>{e.drawable.current?e.drawable.enabled&&n(e,i):e.viewOnly||t(e,i)};function ws(e){const t=G(e),n=Re(e.dom.bounds()),i=e.dom.elements.board,r=e.pieces,s=e.animation.current,o=s?s.plan.anims:new Map,a=s?s.plan.fadings:new Map,u=e.draggable.current,c=vs(e),p=new Set,f=new Set,_=new Map,m=new Map;let h,d,b,g,v,P,C,E,S,A;for(d=i.firstChild;d;){if(h=d.cgKey,jn(d))if(b=r.get(h),v=o.get(h),P=a.get(h),g=d.cgPiece,d.cgDragging&&(!u||u.orig!==h)&&(d.classList.remove("dragging"),te(d,n(B(h),t)),d.cgDragging=!1),!P&&d.cgFading&&(d.cgFading=!1,d.classList.remove("fading")),b){if(v&&d.cgAnimating&&g===Ne(b)){const w=B(h);w[0]+=v[2],w[1]+=v[3],d.classList.add("anim"),te(d,n(w,t))}else d.cgAnimating&&(d.cgAnimating=!1,d.classList.remove("anim"),te(d,n(B(h),t)),e.addPieceZIndex&&(d.style.zIndex=Bt(B(h),t)));g===Ne(b)&&(!P||!d.cgFading)?p.add(h):P&&g===Ne(P)?(d.classList.add("fading"),d.cgFading=!0):Dt(_,g,d)}else Dt(_,g,d);else if(Vn(d)){const w=d.className;c.get(h)===w?f.add(h):Dt(m,w,d)}d=d.nextSibling}for(const[w,O]of c)if(!f.has(w)){S=m.get(O),A=S&&S.pop();const T=n(B(w),t);if(A)A.cgKey=w,te(A,T);else{const R=re("square",O);R.cgKey=w,te(R,T),i.insertBefore(R,i.firstChild)}}for(const[w,O]of r)if(v=o.get(w),!p.has(w))if(C=_.get(Ne(O)),E=C&&C.pop(),E){E.cgKey=w,E.cgFading&&(E.classList.remove("fading"),E.cgFading=!1);const T=B(w);e.addPieceZIndex&&(E.style.zIndex=Bt(T,t)),v&&(E.cgAnimating=!0,E.classList.add("anim"),T[0]+=v[2],T[1]+=v[3]),te(E,n(T,t))}else{const T=Ne(O),R=re("piece",T),$=B(w);R.cgPiece=T,R.cgKey=w,v&&(R.cgAnimating=!0,$[0]+=v[2],$[1]+=v[3]),te(R,n($,t)),e.addPieceZIndex&&(R.style.zIndex=Bt($,t)),i.appendChild(R)}for(const w of _.values())Zn(e,w);for(const w of m.values())Zn(e,w)}function ys(e){const t=G(e),n=Re(e.dom.bounds());let i=e.dom.elements.board.firstChild;for(;i;)(jn(i)&&!i.cgAnimating||Vn(i))&&te(i,n(B(i.cgKey),t)),i=i.nextSibling}function Hn(e){var t,n;const i=e.dom.elements.wrap.getBoundingClientRect(),r=e.dom.elements.container,s=i.height/i.width,o=Math.floor(i.width*window.devicePixelRatio/8)*8/window.devicePixelRatio,a=o*s;r.style.width=o+"px",r.style.height=a+"px",e.dom.bounds.clear(),(t=e.addDimensionsCssVarsTo)===null||t===void 0||t.style.setProperty("---cg-width",o+"px"),(n=e.addDimensionsCssVarsTo)===null||n===void 0||n.style.setProperty("---cg-height",a+"px")}const jn=e=>e.tagName==="PIECE",Vn=e=>e.tagName==="SQUARE";function Zn(e,t){for(const n of t)e.dom.elements.board.removeChild(n)}function Bt(e,t){const i=e[1];return`${t?10-i:3+i}`}const Ne=e=>`${e.color} ${e.role}`;function vs(e){var t,n,i;const r=new Map;if(e.lastMove&&e.highlight.lastMove)for(const a of e.lastMove)se(r,a,"last-move");if(e.check&&e.highlight.check&&se(r,e.check,"check"),e.selected&&(se(r,e.selected,"selected"),e.movable.showDests)){const a=(t=e.movable.dests)===null||t===void 0?void 0:t.get(e.selected);if(a)for(const c of a)se(r,c,"move-dest"+(e.pieces.has(c)?" oc":""));const u=(i=(n=e.premovable.customDests)===null||n===void 0?void 0:n.get(e.selected))!==null&&i!==void 0?i:e.premovable.dests;if(u)for(const c of u)se(r,c,"premove-dest"+(e.pieces.has(c)?" oc":""))}const s=e.premovable.current;if(s)for(const a of s)se(r,a,"current-premove");else e.predroppable.current&&se(r,e.predroppable.current.key,"current-premove");const o=e.exploding;if(o)for(const a of o.keys)se(r,a,"exploding"+o.stage);return e.highlight.custom&&e.highlight.custom.forEach((a,u)=>{se(r,u,a)}),r}function se(e,t,n){const i=e.get(t);i?e.set(t,`${i} ${n}`):e.set(t,n)}function Dt(e,t,n){const i=e.get(t);i?i.push(n):e.set(t,[n])}function Cs(e,t,n){const i=new Map,r=[];for(const a of e)i.set(a.hash,!1);let s=t.firstElementChild,o;for(;s;)o=s.getAttribute("cgHash"),i.has(o)?i.set(o,!0):r.push(s),s=s.nextElementSibling;for(const a of r)t.removeChild(a);for(const a of e)i.get(a.hash)||t.appendChild(n(a))}function _s(e,t){const i=e.drawable.autoShapes.filter(r=>r.piece).map(r=>({shape:r,hash:Ps(r),current:!1}));Cs(i,t,r=>Ss(e,r,e.dom.bounds()))}function Es(e){var t;const n=G(e),i=Re(e.dom.bounds());let r=(t=e.dom.elements.autoPieces)===null||t===void 0?void 0:t.firstChild;for(;r;)hn(r,i(B(r.cgKey),n),r.cgScale),r=r.nextSibling}function Ss(e,{shape:t,hash:n},i){var r,s,o;const a=t.orig,u=(r=t.piece)===null||r===void 0?void 0:r.role,c=(s=t.piece)===null||s===void 0?void 0:s.color,p=(o=t.piece)===null||o===void 0?void 0:o.scale,f=re("piece",`${u} ${c}`);return f.setAttribute("cgHash",n),f.cgKey=a,f.cgScale=p,hn(f,Re(i)(B(a),G(e)),p),f}const Ps=e=>{var t,n,i;return[e.orig,(t=e.piece)===null||t===void 0?void 0:t.role,(n=e.piece)===null||n===void 0?void 0:n.color,(i=e.piece)===null||i===void 0?void 0:i.scale].join(",")};function xs(e,t){const n=Qr();On(n,t);function i(){const r="dom"in n?n.dom.unbind:void 0,s=ps(e,n),o=nr(()=>s.board.getBoundingClientRect()),a=p=>{ws(c),s.autoPieces&&_s(c,s.autoPieces),!p&&s.svg&&Jr(c,s.svg,s.customSvg)},u=()=>{Hn(c),ys(c),s.autoPieces&&Es(c)},c=n;return c.dom={elements:s,bounds:o,redraw:Ms(a),redrawNow:a,unbind:r},c.drawable.prevSvgHash="",Hn(c),a(!1),gs(c,u),r||(c.dom.unbind=ks(c,u)),c.events.insert&&c.events.insert(s),c}return Yr(i(),i)}function Ms(e){let t=!1;return()=>{t||(t=!0,requestAnimationFrame(()=>{e(),t=!1}))}}function As(e,t){return document.createElement(e,t)}function Os(e,t,n){return document.createElementNS(e,t,n)}function Rs(){return Ce(document.createDocumentFragment())}function Ts(e){return document.createTextNode(e)}function Ns(e){return document.createComment(e)}function Bs(e,t,n){if(oe(e)){let i=e;for(;i&&oe(i);)i=Ce(i).parent;e=i??e}oe(t)&&(t=Ce(t,e)),n&&oe(n)&&(n=Ce(n).firstChildNode),e.insertBefore(t,n)}function Ds(e,t){e.removeChild(t)}function Ks(e,t){oe(t)&&(t=Ce(t,e)),e.appendChild(t)}function Yn(e){if(oe(e)){for(;e&&oe(e);)e=Ce(e).parent;return e??null}return e.parentNode}function Ls(e){var t;if(oe(e)){const n=Ce(e),i=Yn(n);if(i&&n.lastChildNode){const r=Array.from(i.childNodes),s=r.indexOf(n.lastChildNode);return(t=r[s+1])!==null&&t!==void 0?t:null}return null}return e.nextSibling}function $s(e){return e.tagName}function Is(e,t){e.textContent=t}function zs(e){return e.textContent}function qs(e){return e.nodeType===1}function Ws(e){return e.nodeType===3}function Fs(e){return e.nodeType===8}function oe(e){return e.nodeType===11}function Ce(e,t){var n,i,r;const s=e;return(n=s.parent)!==null&&n!==void 0||(s.parent=t??null),(i=s.firstChildNode)!==null&&i!==void 0||(s.firstChildNode=e.firstChild),(r=s.lastChildNode)!==null&&r!==void 0||(s.lastChildNode=e.lastChild),s}const Gs={createElement:As,createElementNS:Os,createTextNode:Ts,createDocumentFragment:Rs,createComment:Ns,insertBefore:Bs,removeChild:Ds,appendChild:Ks,parentNode:Yn,nextSibling:Ls,tagName:$s,setTextContent:Is,getTextContent:zs,isElement:qs,isText:Ws,isComment:Fs,isDocumentFragment:oe};function Be(e,t,n,i,r){const s=t===void 0?void 0:t.key;return{sel:e,data:t,children:n,text:i,elm:r,key:s}}const He=Array.isArray;function je(e){return typeof e=="string"||typeof e=="number"||e instanceof String||e instanceof Number}function Ve(e){return e===void 0}function U(e){return e!==void 0}const Kt=Be("",{},[],void 0,void 0);function De(e,t){var n,i;const r=e.key===t.key,s=((n=e.data)===null||n===void 0?void 0:n.is)===((i=t.data)===null||i===void 0?void 0:i.is),o=e.sel===t.sel,a=!e.sel&&e.sel===t.sel?typeof e.text==typeof t.text:!0;return o&&r&&s&&a}function Us(){throw new Error("The document fragment is not supported on this platform.")}function Hs(e,t){return e.isElement(t)}function js(e,t){return e.isDocumentFragment(t)}function Vs(e,t,n){var i;const r={};for(let s=t;s<=n;++s){const o=(i=e[s])===null||i===void 0?void 0:i.key;o!==void 0&&(r[o]=s)}return r}const Zs=["create","update","remove","destroy","pre","post"];function Ys(e,t,n){const i={create:[],update:[],remove:[],destroy:[],pre:[],post:[]},r=Gs;for(const h of Zs)for(const d of e){const b=d[h];b!==void 0&&i[h].push(b)}function s(h){const d=h.id?"#"+h.id:"",b=h.getAttribute("class"),g=b?"."+b.split(" ").join("."):"";return Be(r.tagName(h).toLowerCase()+d+g,{},[],void 0,h)}function o(h){return Be(void 0,{},[],void 0,h)}function a(h,d){return function(){if(--d===0){const g=r.parentNode(h);g!==null&&r.removeChild(g,h)}}}function u(h,d){var b,g,v,P;let C,E=h.data;if(E!==void 0){const w=(b=E.hook)===null||b===void 0?void 0:b.init;U(w)&&(w(h),E=h.data)}const S=h.children,A=h.sel;if(A==="!")Ve(h.text)&&(h.text=""),h.elm=r.createComment(h.text);else if(A==="")h.elm=r.createTextNode(h.text);else if(A!==void 0){const w=A.indexOf("#"),O=A.indexOf(".",w),T=w>0?w:A.length,R=O>0?O:A.length,$=w!==-1||O!==-1?A.slice(0,Math.min(T,R)):A,ee=h.elm=U(E)&&U(C=E.ns)?r.createElementNS(C,$,E):r.createElement($,E);for(T<R&&ee.setAttribute("id",A.slice(T+1,R)),O>0&&ee.setAttribute("class",A.slice(R+1).replace(/\./g," ")),C=0;C<i.create.length;++C)i.create[C](Kt,h);if(je(h.text)&&(!He(S)||S.length===0)&&r.appendChild(ee,r.createTextNode(h.text)),He(S))for(C=0;C<S.length;++C){const ci=S[C];ci!=null&&r.appendChild(ee,u(ci,d))}const Je=h.data.hook;U(Je)&&((g=Je.create)===null||g===void 0||g.call(Je,Kt,h),Je.insert&&d.push(h))}else if(!((v=void 0)===null||v===void 0)&&v.fragments&&h.children){for(h.elm=((P=r.createDocumentFragment)!==null&&P!==void 0?P:Us)(),C=0;C<i.create.length;++C)i.create[C](Kt,h);for(C=0;C<h.children.length;++C){const w=h.children[C];w!=null&&r.appendChild(h.elm,u(w,d))}}else h.elm=r.createTextNode(h.text);return h.elm}function c(h,d,b,g,v,P){for(;g<=v;++g){const C=b[g];C!=null&&r.insertBefore(h,u(C,P),d)}}function p(h){var d,b;const g=h.data;if(g!==void 0){(b=(d=g==null?void 0:g.hook)===null||d===void 0?void 0:d.destroy)===null||b===void 0||b.call(d,h);for(let v=0;v<i.destroy.length;++v)i.destroy[v](h);if(h.children!==void 0)for(let v=0;v<h.children.length;++v){const P=h.children[v];P!=null&&typeof P!="string"&&p(P)}}}function f(h,d,b,g){for(var v,P;b<=g;++b){let C,E;const S=d[b];if(S!=null)if(U(S.sel)){p(S),C=i.remove.length+1,E=a(S.elm,C);for(let w=0;w<i.remove.length;++w)i.remove[w](S,E);const A=(P=(v=S==null?void 0:S.data)===null||v===void 0?void 0:v.hook)===null||P===void 0?void 0:P.remove;U(A)?A(S,E):E()}else S.children?(p(S),f(h,S.children,0,S.children.length-1)):r.removeChild(h,S.elm)}}function _(h,d,b,g){let v=0,P=0,C=d.length-1,E=d[0],S=d[C],A=b.length-1,w=b[0],O=b[A],T,R,$,ee;for(;v<=C&&P<=A;)E==null?E=d[++v]:S==null?S=d[--C]:w==null?w=b[++P]:O==null?O=b[--A]:De(E,w)?(m(E,w,g),E=d[++v],w=b[++P]):De(S,O)?(m(S,O,g),S=d[--C],O=b[--A]):De(E,O)?(m(E,O,g),r.insertBefore(h,E.elm,r.nextSibling(S.elm)),E=d[++v],O=b[--A]):De(S,w)?(m(S,w,g),r.insertBefore(h,S.elm,E.elm),S=d[--C],w=b[++P]):(T===void 0&&(T=Vs(d,v,C)),R=T[w.key],Ve(R)?(r.insertBefore(h,u(w,g),E.elm),w=b[++P]):Ve(T[O.key])?(r.insertBefore(h,u(O,g),r.nextSibling(S.elm)),O=b[--A]):($=d[R],$.sel!==w.sel?r.insertBefore(h,u(w,g),E.elm):(m($,w,g),d[R]=void 0,r.insertBefore(h,$.elm,E.elm)),w=b[++P]));P<=A&&(ee=b[A+1]==null?null:b[A+1].elm,c(h,ee,b,P,A,g)),v<=C&&f(h,d,v,C)}function m(h,d,b){var g,v,P,C,E,S,A,w;const O=(g=d.data)===null||g===void 0?void 0:g.hook;(v=O==null?void 0:O.prepatch)===null||v===void 0||v.call(O,h,d);const T=d.elm=h.elm;if(h===d)return;if(d.data!==void 0||U(d.text)&&d.text!==h.text){(P=d.data)!==null&&P!==void 0||(d.data={}),(C=h.data)!==null&&C!==void 0||(h.data={});for(let ee=0;ee<i.update.length;++ee)i.update[ee](h,d);(A=(S=(E=d.data)===null||E===void 0?void 0:E.hook)===null||S===void 0?void 0:S.update)===null||A===void 0||A.call(S,h,d)}const R=h.children,$=d.children;Ve(d.text)?U(R)&&U($)?R!==$&&_(T,R,$,b):U($)?(U(h.text)&&r.setTextContent(T,""),c(T,null,$,0,$.length-1,b)):U(R)?f(T,R,0,R.length-1):U(h.text)&&r.setTextContent(T,""):h.text!==d.text&&(U(R)&&f(T,R,0,R.length-1),r.setTextContent(T,d.text)),(w=O==null?void 0:O.postpatch)===null||w===void 0||w.call(O,h,d)}return function(d,b){let g,v,P;const C=[];for(g=0;g<i.pre.length;++g)i.pre[g]();for(Hs(r,d)?d=s(d):js(r,d)&&(d=o(d)),De(d,b)?m(d,b,C):(v=d.elm,P=r.parentNode(v),u(b,C),P!==null&&(r.insertBefore(P,b.elm,r.nextSibling(v)),f(P,[d],0,0))),g=0;g<C.length;++g)C[g].data.hook.insert(C[g]);for(g=0;g<i.post.length;++g)i.post[g]();return b}}function Qn(e,t,n){if(e.ns="http://www.w3.org/2000/svg",n!=="foreignObject"&&t!==void 0)for(let i=0;i<t.length;++i){const r=t[i];if(typeof r=="string")continue;const s=r.data;s!==void 0&&Qn(s,r.children,r.sel)}}function M(e,t,n){let i={},r,s,o;if(n!==void 0?(t!==null&&(i=t),He(n)?r=n:je(n)?s=n.toString():n&&n.sel&&(r=[n])):t!=null&&(He(t)?r=t:je(t)?s=t.toString():t&&t.sel?r=[t]:i=t),r!==void 0)for(o=0;o<r.length;++o)je(r[o])&&(r[o]=Be(void 0,void 0,void 0,r[o],void 0));return e.startsWith("svg")&&(e.length===3||e[3]==="."||e[3]==="#")&&Qn(i,r,e),Be(e,i,r,s,void 0)}const Qs="http://www.w3.org/1999/xlink",Xs="http://www.w3.org/2000/xmlns/",Js="http://www.w3.org/XML/1998/namespace",Xn=58,eo=120,to=109;function Jn(e,t){let n;const i=t.elm;let r=e.data.attrs,s=t.data.attrs;if(!(!r&&!s)&&r!==s){r=r||{},s=s||{};for(n in s){const o=s[n];r[n]!==o&&(o===!0?i.setAttribute(n,""):o===!1?i.removeAttribute(n):n.charCodeAt(0)!==eo?i.setAttribute(n,o):n.charCodeAt(3)===Xn?i.setAttributeNS(Js,n,o):n.charCodeAt(5)===Xn?n.charCodeAt(1)===to?i.setAttributeNS(Xs,n,o):i.setAttributeNS(Qs,n,o):i.setAttribute(n,o))}for(n in r)n in s||i.removeAttribute(n)}}const no={create:Jn,update:Jn};function ei(e,t){let n,i;const r=t.elm;let s=e.data.class,o=t.data.class;if(!(!s&&!o)&&s!==o){s=s||{},o=o||{};for(i in s)s[i]&&!Object.prototype.hasOwnProperty.call(o,i)&&r.classList.remove(i);for(i in o)n=o[i],n!==s[i]&&r.classList[n?"add":"remove"](i)}}const io={create:ei,update:ei};function ro(e,t,n){for(const i of["touchstart","mousedown"])e.addEventListener(i,r=>{t(r),r.preventDefault()},{passive:!1})}const Lt=(e,t,n,i=!0)=>Ze(r=>r.addEventListener(e,s=>{const o=t(s);return o===!1&&s.preventDefault(),o},{passive:i}));function Ze(e){return{insert:t=>e(t.elm)}}function so(e){let t=0;return n=>{t+=n.deltaY*(n.deltaMode?40:1),Math.abs(t)>=4?(e(n,!0),t=0):e(n,!1)}}function oo(e,t){const n=()=>{e(),i=Math.max(100,i-i/15),r=setTimeout(n,i)};let i=350,r=setTimeout(n,500);e();const s=t.type=="touchstart"?"touchend":"mouseup";document.addEventListener(s,()=>clearTimeout(r),{once:!0})}const ao=e=>e.altKey||e.ctrlKey||e.shiftKey||e.metaKey||document.activeElement instanceof HTMLInputElement||document.activeElement instanceof HTMLTextAreaElement,co=e=>t=>{ao(t)||(t.key=="ArrowLeft"?e.goTo("prev"):t.key=="ArrowRight"?e.goTo("next"):t.key=="f"&&e.flip())},lo=e=>{var t,n;return M("div.lpv__menu.lpv__pane",[M("button.lpv__menu__entry.lpv__menu__flip.lpv__fbt",{hook:Lt("click",e.flip)},e.translate("flipTheBoard")),!((t=e.opts.menu.analysisBoard)===null||t===void 0)&&t.enabled?M("a.lpv__menu__entry.lpv__menu__analysis.lpv__fbt",{attrs:{href:e.analysisUrl(),target:"_blank"}},e.translate("analysisBoard")):void 0,!((n=e.opts.menu.practiceWithComputer)===null||n===void 0)&&n.enabled?M("a.lpv__menu__entry.lpv__menu__practice.lpv__fbt",{attrs:{href:e.practiceUrl(),target:"_blank"}},e.translate("practiceWithComputer")):void 0,e.opts.menu.getPgn.enabled?M("button.lpv__menu__entry.lpv__menu__pgn.lpv__fbt",{hook:Lt("click",e.togglePgn)},e.translate("getPgn")):void 0,uo(e)])},uo=e=>{const t=e.game.metadata.externalLink;return t&&M("a.lpv__menu__entry.lpv__fbt",{attrs:{href:t,target:"_blank"}},e.translate(e.game.metadata.isLichess?"viewOnLichess":"viewOnSite"))},ho=e=>M("div.lpv__controls",[e.pane=="board"?void 0:Ye(e,"first","step-backward"),Ye(e,"prev","left-open"),M("button.lpv__fbt.lpv__controls__menu.lpv__icon",{class:{active:e.pane!="board","lpv__icon-ellipsis-vert":e.pane=="board"},hook:Lt("click",e.toggleMenu)},e.pane=="board"?void 0:"X"),Ye(e,"next","right-open"),e.pane=="board"?void 0:Ye(e,"last","step-forward")]),Ye=(e,t,n)=>M(`button.lpv__controls__goto.lpv__controls__goto--${t}.lpv__fbt.lpv__icon.lpv__icon-${n}`,{class:{disabled:e.pane=="board"&&!e.canGoTo(t)},hook:Ze(i=>ro(i,r=>oo(()=>e.goTo(t),r)))}),fo=e=>{const t=po[e];return t?M("nag",{attrs:{title:t.name}},t.symbol):void 0},po={1:{symbol:"!",name:"Good move"},2:{symbol:"?",name:"Mistake"},3:{symbol:"!!",name:"Brilliant move"},4:{symbol:"??",name:"Blunder"},5:{symbol:"!?",name:"Interesting move"},6:{symbol:"?!",name:"Dubious move"},7:{symbol:"□",name:"Only move"},22:{symbol:"⨀",name:"Zugzwang"},10:{symbol:"=",name:"Equal position"},13:{symbol:"∞",name:"Unclear position"},14:{symbol:"⩲",name:"White is slightly better"},15:{symbol:"⩱",name:"Black is slightly better"},16:{symbol:"±",name:"White is better"},17:{symbol:"∓",name:"Black is better"},18:{symbol:"+−",name:"White is winning"},19:{symbol:"-+",name:"Black is winning"},146:{symbol:"N",name:"Novelty"},32:{symbol:"↑↑",name:"Development"},36:{symbol:"↑",name:"Initiative"},40:{symbol:"→",name:"Attack"},132:{symbol:"⇆",name:"Counterplay"},138:{symbol:"⊕",name:"Time trouble"},44:{symbol:"=∞",name:"With compensation"},140:{symbol:"∆",name:"With the idea"}},mo=e=>M("div.lpv__side",[M("div.lpv__moves",{hook:{insert:t=>{const n=t.elm;e.path.empty()||ni(e,n),n.addEventListener("mousedown",i=>{const r=i.target.getAttribute("p");r&&e.toPath(new J(r))},{passive:!0})},postpatch:(t,n)=>{e.autoScrollRequested&&(ni(e,n.elm),e.autoScrollRequested=!1)}}},[...e.game.initial.comments.map(Qe),...wo(e),...go(e)])]),go=e=>{const t=e.game.metadata.result;return t&&t!="*"?[M("comment.result",e.game.metadata.result)]:[]},$t=()=>M("move.empty","..."),It=e=>M("index",`${e}.`),Qe=e=>M("comment",e),ko=()=>M("paren.open","("),bo=()=>M("paren.close",")"),Xe=e=>Math.floor((e.ply-1)/2)+1,wo=e=>{const t=vo(e),n=[];let i,r=e.game.moves.children.slice(1);for(e.game.initial.pos.turn=="black"&&e.game.mainline[0]&&n.push(It(e.game.initial.pos.fullmoves),$t());i=(i||e.game.moves).children[0];){const s=i.data,o=s.ply%2==1;o&&n.push(It(Xe(s))),n.push(t(s));const a=o&&(r.length||s.comments.length)&&i.children.length;a&&n.push($t()),s.comments.forEach(u=>n.push(Qe(u))),r.forEach(u=>n.push(yo(t,u))),a&&n.push(It(Xe(s)),$t()),r=i.children.slice(1)}return n},yo=(e,t)=>M("variation",[...t.data.startingComments.map(Qe),...ti(e,t)]),ti=(e,t)=>{let n=[],i=[];t.data.ply%2==0&&n.push(M("index",[Xe(t.data),"..."]));do{const r=t.data;r.ply%2==1&&n.push(M("index",[Xe(r),"."])),n.push(e(r)),r.comments.forEach(s=>n.push(Qe(s))),i.forEach(s=>{n=[...n,ko(),...ti(e,s),bo()]}),i=t.children.slice(1),t=t.children[0]}while(t);return n},vo=e=>t=>M("move",{class:{current:e.path.equals(t.path),ancestor:e.path.contains(t.path),good:t.nags.includes(1),mistake:t.nags.includes(2),brilliant:t.nags.includes(3),blunder:t.nags.includes(4),interesting:t.nags.includes(5),inaccuracy:t.nags.includes(6)},attrs:{p:t.path.path}},[t.san,...t.nags.map(fo)]),ni=(e,t)=>{const n=t.querySelector(".current");if(!n){t.scrollTop=e.path.empty()?0:99999;return}t.scrollTop=n.offsetTop-t.offsetHeight/2+n.offsetHeight};function ii(e,t){const n=t=="bottom"?e.orientation():x(e.orientation()),i=e.game.players[n],r=[i.title?M("span.lpv__player__title",i.title):void 0,M("span.lpv__player__name",i.name),i.rating?M("span.lpv__player__rating",["(",i.rating,")"]):void 0];return M(`div.lpv__player.lpv__player--${t}`,[i.isLichessUser?M("a.lpv__player__person.ulpt.user-link",{attrs:{href:`${e.opts.lichess}/@/${i.name}`}},r):M("span.lpv__player__person",r),e.opts.showClocks?Co(e,n):void 0])}const Co=(e,t)=>{const n=e.curData(),i=n.clocks&&n.clocks[t];return typeof i==null?void 0:M("div.lpv__player__clock",{class:{active:t==n.turn}},_o(i))},_o=e=>{if(!e&&e!==0)return["-"];const t=new Date(e*1e3),n=":",i=ri(t.getUTCMinutes())+n+ri(t.getUTCSeconds());return e>=3600?[Math.floor(e/3600)+n+i]:[i]},ri=e=>(e<10?"0":"")+e;function si(e){const t=e.opts,n=`lpv.lpv--moves-${t.showMoves}.lpv--controls-${t.showControls}${t.classes?"."+t.classes.replace(" ","."):""}`,i=t.showPlayers=="auto"?e.game.hasPlayerName():t.showPlayers;return M(`div.${n}`,{class:{"lpv--menu":e.pane!="board","lpv--players":i},attrs:{tabindex:0},hook:Ze(r=>{e.setGround(xs(r.querySelector(".cg-wrap"),Po(e,r))),t.keyboardToMove&&r.addEventListener("keydown",co(e))})},[i?ii(e,"top"):void 0,Eo(e),i?ii(e,"bottom"):void 0,t.showControls?ho(e):void 0,t.showMoves?mo(e):void 0,e.pane=="menu"?lo(e):e.pane=="pgn"?So(e):void 0])}const Eo=e=>M("div.lpv__board",{hook:Ze(t=>{t.addEventListener("click",e.focus),e.opts.scrollToMove&&!("ontouchstart"in window)&&t.addEventListener("wheel",so((n,i)=>{n.preventDefault(),n.deltaY>0&&i?e.goTo("next",!1):n.deltaY<0&&i&&e.goTo("prev",!1)}))})},M("div.cg-wrap")),So=e=>{const t=new Blob([e.opts.pgn],{type:"text/plain"});return M("div.lpv__pgn.lpv__pane",[M("a.lpv__pgn__download.lpv__fbt",{attrs:{href:window.URL.createObjectURL(t),download:e.opts.menu.getPgn.fileName||`${e.game.title()}.pgn`}},e.translate("download")),M("textarea.lpv__pgn__text",e.opts.pgn)])},Po=(e,t)=>({viewOnly:!e.opts.drawArrows,addDimensionsCssVarsTo:t,drawable:{enabled:e.opts.drawArrows,visible:!0},disableContextMenu:e.opts.drawArrows,...e.opts.chessground||{},movable:{free:!1},draggable:{enabled:!1},selectable:{enabled:!1},...e.cgState()}),xo={pgn:"*",fen:void 0,showPlayers:"auto",showClocks:!0,showMoves:"auto",showControls:!0,scrollToMove:!0,keyboardToMove:!0,orientation:void 0,initialPly:0,chessground:{},drawArrows:!0,menu:{getPgn:{enabled:!0,fileName:void 0},practiceWithComputer:{enabled:!0},analysisBoard:{enabled:!0}},lichess:"https://lichess.org",classes:void 0};function Mo(e,t){const n={...xo};return oi(n,t),n.fen&&(n.pgn=`[FEN "${n.fen}"]
4
- ${n.pgn}`),n.classes||(n.classes=e.className),n}function oi(e,t){for(const n in t)typeof t[n]<"u"&&(ai(e[n])&&ai(t[n])?oi(e[n],t[n]):e[n]=t[n])}function ai(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Ao(e,t){const n=Ys([io,no]),i=Mo(e,t),r=new fr(i,a),s=si(r);e.innerHTML="";let o=n(e,s);r.div=o.elm;function a(){o=n(o,si(r))}return r}class Oo{constructor(t,n){et(this,"viewer");this.viewer=Ao(t,n)}get api(){return this.viewer}}class Ro{constructor(t){et(this,"config");et(this,"viewer");this.config=t}mount(t){this.viewer=new Oo(t,this.config)}get api(){var t;return(t=this.viewer)==null?void 0:t.api}}const To=I.defineComponent({__name:"PgnViewer",props:{config:{}},emits:["ready"],setup(e,{emit:t}){const n=e,i=t,r=I.ref(null),s=new Ro({...n.config}),o=()=>r.value&&s.mount(r.value),a=()=>s.api&&i("ready",s.api);return I.onMounted(()=>o()??a()),(u,c)=>(I.openBlock(),I.createElementBlock("div",{ref_key:"board",ref:r},null,512))}});H.PgnViewer=To,Object.defineProperty(H,Symbol.toStringTag,{value:"Module"})});
3
+ `);this.commentBuf=[],i.node?((t=i.node.data).comments||(t.comments=[]),i.node.data.comments.push(r)):i.root?((n=this.game).comments||(n.comments=[]),this.game.comments.push(r)):(i.startingComments||(i.startingComments=[]),i.startingComments.push(r))}emit(t){if(this.state===4&&this.handleComment(),t)return this.emitGame(this.game,t);this.found&&this.emitGame(this.game,void 0),this.resetGame()}}const ln=(e,t=pt)=>{const n=[];return new Gi(i=>n.push(i),t,NaN).parse(e),n},Ui=e=>{switch((e||"chess").toLowerCase()){case"chess":case"chess960":case"chess 960":case"standard":case"from position":case"classical":case"normal":case"fischerandom":case"fischerrandom":case"fischer random":case"wild/0":case"wild/1":case"wild/2":case"wild/3":case"wild/4":case"wild/5":case"wild/6":case"wild/7":case"wild/8":case"wild/8a":return"chess";case"crazyhouse":case"crazy house":case"house":case"zh":return"crazyhouse";case"king of the hill":case"koth":case"kingofthehill":return"kingofthehill";case"three-check":case"three check":case"threecheck":case"three check chess":case"3-check":case"3 check":case"3check":return"3check";case"antichess":case"anti chess":case"anti":return"antichess";case"atomic":case"atom":case"atomic chess":return"atomic";case"horde":case"horde chess":return"horde";case"racing kings":case"racingkings":case"racing":case"race":return"racingkings";default:return}},Hi=e=>{const t=Ui(e.get("Variant"));if(!t)return k.err(new D(N.Variant));const n=e.get("FEN");return n?Pi(n).chain(i=>$i(t,i)):k.ok(Li(t))};function ji(e){switch(e){case"G":return"green";case"R":return"red";case"Y":return"yellow";case"B":return"blue";default:return}}const Vi=e=>{const t=ji(e.slice(0,1)),n=Ae(e.slice(1,3)),i=Ae(e.slice(3,5));if(!(!t||!y(n))){if(e.length===3)return{color:t,from:n,to:n};if(e.length===5&&y(i))return{color:t,from:n,to:i}}},Zi=e=>{let t,n,i;const r=[];return{text:e.replace(/\s?\[%(emt|clk)\s(\d{1,5}):(\d{1,2}):(\d{1,2}(?:\.\d{0,3})?)\]\s?/g,(o,a,u,c,p)=>{const f=parseInt(u,10)*3600+parseInt(c,10)*60+parseFloat(p);return a==="emt"?t=f:a==="clk"&&(n=f)," "}).replace(/\s?\[%(?:csl|cal)\s([RGYB][a-h][1-8](?:[a-h][1-8])?(?:,[RGYB][a-h][1-8](?:[a-h][1-8])?)*)\]\s?/g,(o,a)=>{for(const u of a.split(","))r.push(Vi(u));return" "}).replace(/\s?\[%eval\s(?:#([+-]?\d{1,5})|([+-]?(?:\d{1,5}|\d{0,5}\.\d{1,2})))(?:,(\d{1,5}))?\]\s?/g,(o,a,u,c)=>{const p=c&&parseInt(c,10);return i=a?{mate:parseInt(a,10),depth:p}:{pawns:parseFloat(u),depth:p}," "}).trim(),shapes:r,emt:t,clock:n,evaluation:i}};function Yi(e){return t=>e&&e(t)||Qi(t)}const Qi=e=>Xi[e],Xi={flipTheBoard:"Flip the board",analysisBoard:"Analysis board",practiceWithComputer:"Practice with computer",getPgn:"Get PGN",download:"Download",viewOnLichess:"View on Lichess",viewOnSite:"View on site"},Ji=["white","black"],ze=["a","b","c","d","e","f","g","h"],qe=["1","2","3","4","5","6","7","8"],er=[...qe].reverse(),kt=Array.prototype.concat(...ze.map(e=>qe.map(t=>e+t))),Z=e=>kt[8*e[0]+e[1]],B=e=>[e.charCodeAt(0)-97,e.charCodeAt(1)-49],tr=e=>{if(e)return e[1]==="@"?[e.slice(2,4)]:[e.slice(0,2),e.slice(2,4)]},un=kt.map(B);function nr(e){let t;const n=()=>(t===void 0&&(t=e()),t);return n.clear=()=>{t=void 0},n}const ir=()=>{let e;return{start(){e=performance.now()},cancel(){e=void 0},stop(){if(!e)return 0;const t=performance.now()-e;return e=void 0,t}}},bt=e=>e==="white"?"black":"white",Oe=(e,t)=>{const n=e[0]-t[0],i=e[1]-t[1];return n*n+i*i},wt=(e,t)=>e.role===t.role&&e.color===t.color,Re=e=>(t,n)=>[(n?t[0]:7-t[0])*e.width/8,(n?7-t[1]:t[1])*e.height/8],te=(e,t)=>{e.style.transform=`translate(${t[0]}px,${t[1]}px)`},hn=(e,t,n=1)=>{e.style.transform=`translate(${t[0]}px,${t[1]}px) scale(${n})`},yt=(e,t)=>{e.style.visibility=t?"visible":"hidden"},be=e=>{var t;if(e.clientX||e.clientX===0)return[e.clientX,e.clientY];if(!((t=e.targetTouches)===null||t===void 0)&&t[0])return[e.targetTouches[0].clientX,e.targetTouches[0].clientY]},dn=e=>e.button===2,re=(e,t)=>{const n=document.createElement(e);return t&&(n.className=t),n};function fn(e,t,n){const i=B(e);return t||(i[0]=7-i[0],i[1]=7-i[1]),[n.left+n.width*i[0]/8+n.width/16,n.top+n.height*(7-i[1])/8+n.height/16]}class J{constructor(t){this.path=t,this.size=()=>this.path.length/2,this.head=()=>this.path.slice(0,2),this.tail=()=>new J(this.path.slice(2)),this.init=()=>new J(this.path.slice(0,-2)),this.last=()=>this.path.slice(-2),this.empty=()=>this.path=="",this.contains=n=>this.path.startsWith(n.path),this.isChildOf=n=>this.init()===n,this.append=n=>new J(this.path+n),this.equals=n=>this.path==n.path}}J.root=new J("");class rr{constructor(t,n,i,r){this.initial=t,this.moves=n,this.players=i,this.metadata=r,this.nodeAt=s=>pn(this.moves,s),this.dataAt=s=>{const o=this.nodeAt(s);return o?or(o)?o.data:this.initial:void 0},this.title=()=>this.players.white.name?[this.players.white.title,this.players.white.name,"vs",this.players.black.title,this.players.black.name].filter(s=>s&&!!s.trim()).join("_").replace(" ","-"):"lichess-pgn-viewer",this.pathAtMainlinePly=s=>{var o;return s==0?J.root:((o=this.mainline[Math.max(0,Math.min(this.mainline.length-1,s=="last"?9999:s-1))])===null||o===void 0?void 0:o.path)||J.root},this.hasPlayerName=()=>{var s,o;return!!(!((s=this.players.white)===null||s===void 0)&&s.name||!((o=this.players.black)===null||o===void 0)&&o.name)},this.mainline=Array.from(this.moves.mainline())}}const sr=(e,t)=>e.children.find(n=>n.data.path.last()==t),pn=(e,t)=>{if(t.empty())return e;const n=sr(e,t.head());return n?pn(n,t.tail()):void 0},or=e=>"data"in e,ar=e=>"uci"in e;class vt{constructor(t,n,i){this.pos=t,this.path=n,this.clocks=i,this.clone=()=>new vt(this.pos.clone(),this.path,{...this.clocks})}}const Ct=e=>{const t=e.map(Zi),n=i=>i.reduce((r,s)=>typeof s==null?r:s,void 0);return{texts:t.map(i=>i.text).filter(i=>!!i),shapes:t.flatMap(i=>i.shapes),clock:n(t.map(i=>i.clock)),emt:n(t.map(i=>i.emt))}},cr=(e,t=!1)=>{var n,i;const r=ln(e)[0]||ln("*")[0],s=Hi(r.headers).unwrap(),o=Xt(s.toSetup()),a=Ct(r.comments||[]),u=new Map(Array.from(r.headers,([m,h])=>[m.toLowerCase(),h])),c=dr(u,t),p={fen:o,turn:s.turn,check:s.isCheck(),pos:s.clone(),comments:a.texts,shapes:a.shapes,clocks:{white:((n=c.timeControl)===null||n===void 0?void 0:n.initial)||a.clock,black:((i=c.timeControl)===null||i===void 0?void 0:i.initial)||a.clock}},f=lr(s,r.moves,c),_=hr(u,c);return new rr(p,f,_,c)},lr=(e,t,n)=>zi(t,new vt(e,J.root,{}),(i,r,s)=>{const o=Bi(i.pos,r.san);if(!o)return;const a=_i(o),u=i.path.append(a),c=Ni(i.pos,o);i.path=u;const p=i.pos.toSetup(),f=Ct(r.comments||[]),_=Ct(r.startingComments||[]),m=[...f.shapes,..._.shapes],h=(p.fullmoves-1)*2+(i.pos.turn==="white"?0:1);let d=i.clocks=ur(i.clocks,i.pos.turn,f.clock);return h<2&&n.timeControl&&(d={white:n.timeControl.initial,black:n.timeControl.initial,...d}),{path:u,ply:h,move:o,san:c,uci:ui(o),fen:Xt(i.pos.toSetup()),turn:i.pos.turn,check:i.pos.isCheck(),comments:f.texts,startingComments:_.texts,nags:r.nags||[],shapes:m,clocks:d,emt:f.emt}}),ur=(e,t,n)=>t=="white"?{...e,black:n}:{...e,white:n};function hr(e,t){const n=(r,s)=>{const o=e.get(`${r}${s}`);return o=="?"||o==""?void 0:o},i=r=>{const s=n(r,"");return{name:s,title:n(r,"title"),rating:parseInt(n(r,"elo")||"")||void 0,isLichessUser:t.isLichess&&!!(s!=null&&s.match(/^[a-z0-9][a-z0-9_-]{0,28}[a-z0-9]$/i))}};return{white:i("white"),black:i("black")}}function dr(e,t){var n;const i=e.get("source")||e.get("site"),r=(n=e.get("timecontrol"))===null||n===void 0?void 0:n.split("+").map(a=>parseInt(a)),s=r&&r[0]?{initial:r[0],increment:r[1]||0}:void 0,o=e.get("orientation");return{externalLink:i&&i.match(/^https?:\/\//)?i:void 0,isLichess:!!(t&&(i!=null&&i.startsWith(t))),timeControl:s,orientation:o==="white"||o==="black"?o:void 0,result:e.get("result")}}class fr{constructor(t,n){this.opts=t,this.redraw=n,this.flipped=!1,this.pane="board",this.autoScrollRequested=!1,this.curNode=()=>this.game.nodeAt(this.path)||this.game.moves,this.curData=()=>this.game.dataAt(this.path)||this.game.initial,this.goTo=(i,r=!0)=>{var s,o;const a=i=="first"?J.root:i=="prev"?this.path.init():i=="next"?(o=(s=this.game.nodeAt(this.path))===null||s===void 0?void 0:s.children[0])===null||o===void 0?void 0:o.data.path:this.game.pathAtMainlinePly("last");this.toPath(a||this.path,r)},this.canGoTo=i=>i=="prev"||i=="first"?!this.path.empty():!!this.curNode().children[0],this.toPath=(i,r=!0)=>{this.path=i,this.pane="board",this.autoScrollRequested=!0,this.redrawGround(),this.redraw(),r&&this.focus()},this.focus=()=>{var i;return(i=this.div)===null||i===void 0?void 0:i.focus()},this.toggleMenu=()=>{this.pane=this.pane=="board"?"menu":"board",this.redraw()},this.togglePgn=()=>{this.pane=this.pane=="pgn"?"board":"pgn",this.redraw()},this.orientation=()=>{const i=this.opts.orientation||"white";return this.flipped?x(i):i},this.flip=()=>{this.flipped=!this.flipped,this.pane="board",this.redrawGround(),this.redraw()},this.cgState=()=>{var i;const r=this.curData(),s=ar(r)?tr(r.uci):(i=this.opts.chessground)===null||i===void 0?void 0:i.lastMove;return{fen:r.fen,orientation:this.orientation(),check:r.check,lastMove:s,turnColor:r.turn}},this.analysisUrl=()=>this.game.metadata.isLichess&&this.game.metadata.externalLink||`https://lichess.org/analysis/${this.curData().fen.replace(" ","_")}?color=${this.orientation()}`,this.practiceUrl=()=>`${this.analysisUrl()}#practice`,this.setGround=i=>{this.ground=i,this.redrawGround()},this.redrawGround=()=>this.withGround(i=>{i.set(this.cgState()),i.setShapes(this.curData().shapes.map(r=>({orig:ae(r.from),dest:ae(r.to),brush:r.color})))}),this.withGround=i=>this.ground&&i(this.ground),this.game=cr(t.pgn,t.lichess),t.orientation=t.orientation||this.game.metadata.orientation,this.translate=Yi(t.translate),this.path=this.game.pathAtMainlinePly(t.initialPly)}}const we=(e,t)=>Math.abs(e-t),pr=e=>(t,n,i,r)=>we(t,i)<2&&(e==="white"?r===n+1||n<=1&&r===n+2&&t===i:r===n-1||n>=6&&r===n-2&&t===i),mn=(e,t,n,i)=>{const r=we(e,n),s=we(t,i);return r===1&&s===2||r===2&&s===1},gn=(e,t,n,i)=>we(e,n)===we(t,i),kn=(e,t,n,i)=>e===n||t===i,bn=(e,t,n,i)=>gn(e,t,n,i)||kn(e,t,n,i),mr=(e,t,n)=>(i,r,s,o)=>we(i,s)<2&&we(r,o)<2||n&&r===o&&r===(e==="white"?0:7)&&(i===4&&(s===2&&t.includes(0)||s===6&&t.includes(7))||t.includes(s));function gr(e,t){const n=t==="white"?"1":"8",i=[];for(const[r,s]of e)r[1]===n&&s.color===t&&s.role==="rook"&&i.push(B(r)[0]);return i}function wn(e,t,n){const i=e.get(t);if(!i)return[];const r=B(t),s=i.role,o=s==="pawn"?pr(i.color):s==="knight"?mn:s==="bishop"?gn:s==="rook"?kn:s==="queen"?bn:mr(i.color,gr(e,i.color),n);return un.filter(a=>(r[0]!==a[0]||r[1]!==a[1])&&o(r[0],r[1],a[0],a[1])).map(Z)}function F(e,...t){e&&setTimeout(()=>e(...t),1)}function kr(e){e.orientation=bt(e.orientation),e.animation.current=e.draggable.current=e.selected=void 0}function br(e,t){for(const[n,i]of t)i?e.pieces.set(n,i):e.pieces.delete(n)}function wr(e,t){if(e.check=void 0,t===!0&&(t=e.turnColor),t)for(const[n,i]of e.pieces)i.role==="king"&&i.color===t&&(e.check=n)}function yr(e,t,n,i){de(e),e.premovable.current=[t,n],F(e.premovable.events.set,t,n,i)}function he(e){e.premovable.current&&(e.premovable.current=void 0,F(e.premovable.events.unset))}function vr(e,t,n){he(e),e.predroppable.current={role:t,key:n},F(e.predroppable.events.set,t,n)}function de(e){const t=e.predroppable;t.current&&(t.current=void 0,F(t.events.unset))}function Cr(e,t,n){if(!e.autoCastle)return!1;const i=e.pieces.get(t);if(!i||i.role!=="king")return!1;const r=B(t),s=B(n);if(r[1]!==0&&r[1]!==7||r[1]!==s[1])return!1;r[0]===4&&!e.pieces.has(n)&&(s[0]===6?n=Z([7,s[1]]):s[0]===2&&(n=Z([0,s[1]])));const o=e.pieces.get(n);return!o||o.color!==i.color||o.role!=="rook"?!1:(e.pieces.delete(t),e.pieces.delete(n),r[0]<s[0]?(e.pieces.set(Z([6,s[1]]),i),e.pieces.set(Z([5,s[1]]),o)):(e.pieces.set(Z([2,s[1]]),i),e.pieces.set(Z([3,s[1]]),o)),!0)}function yn(e,t,n){const i=e.pieces.get(t),r=e.pieces.get(n);if(t===n||!i)return!1;const s=r&&r.color!==i.color?r:void 0;return n===e.selected&&Y(e),F(e.events.move,t,n,s),Cr(e,t,n)||(e.pieces.set(n,i),e.pieces.delete(t)),e.lastMove=[t,n],e.check=void 0,F(e.events.change),s||!0}function _t(e,t,n,i){if(e.pieces.has(n))if(i)e.pieces.delete(n);else return!1;return F(e.events.dropNewPiece,t,n),e.pieces.set(n,t),e.lastMove=[n],e.check=void 0,F(e.events.change),e.movable.dests=void 0,e.turnColor=bt(e.turnColor),!0}function vn(e,t,n){const i=yn(e,t,n);return i&&(e.movable.dests=void 0,e.turnColor=bt(e.turnColor),e.animation.current=void 0),i}function Cn(e,t,n){if(St(e,t,n)){const i=vn(e,t,n);if(i){const r=e.hold.stop();Y(e);const s={premove:!1,ctrlKey:e.stats.ctrlKey,holdTime:r};return i!==!0&&(s.captured=i),F(e.movable.events.after,t,n,s),!0}}else if(Er(e,t,n))return yr(e,t,n,{ctrlKey:e.stats.ctrlKey}),Y(e),!0;return Y(e),!1}function _n(e,t,n,i){const r=e.pieces.get(t);r&&(_r(e,t,n)||i)?(e.pieces.delete(t),_t(e,r,n,i),F(e.movable.events.afterNewPiece,r.role,n,{premove:!1,predrop:!1})):r&&Sr(e,t,n)?vr(e,r.role,n):(he(e),de(e)),e.pieces.delete(t),Y(e)}function Et(e,t,n){if(F(e.events.select,t),e.selected){if(e.selected===t&&!e.draggable.enabled){Y(e),e.hold.cancel();return}else if((e.selectable.enabled||n)&&e.selected!==t&&Cn(e,e.selected,t)){e.stats.dragged=!1;return}}(e.selectable.enabled||e.draggable.enabled)&&(Sn(e,t)||Pt(e,t))&&(En(e,t),e.hold.start())}function En(e,t){e.selected=t,Pt(e,t)?e.premovable.customDests||(e.premovable.dests=wn(e.pieces,t,e.premovable.castle)):e.premovable.dests=void 0}function Y(e){e.selected=void 0,e.premovable.dests=void 0,e.hold.cancel()}function Sn(e,t){const n=e.pieces.get(t);return!!n&&(e.movable.color==="both"||e.movable.color===n.color&&e.turnColor===n.color)}const St=(e,t,n)=>{var i,r;return t!==n&&Sn(e,t)&&(e.movable.free||!!(!((r=(i=e.movable.dests)===null||i===void 0?void 0:i.get(t))===null||r===void 0)&&r.includes(n)))};function _r(e,t,n){const i=e.pieces.get(t);return!!i&&(t===n||!e.pieces.has(n))&&(e.movable.color==="both"||e.movable.color===i.color&&e.turnColor===i.color)}function Pt(e,t){const n=e.pieces.get(t);return!!n&&e.premovable.enabled&&e.movable.color===n.color&&e.turnColor!==n.color}function Er(e,t,n){var i,r;const s=(r=(i=e.premovable.customDests)===null||i===void 0?void 0:i.get(t))!==null&&r!==void 0?r:wn(e.pieces,t,e.premovable.castle);return t!==n&&Pt(e,t)&&s.includes(n)}function Sr(e,t,n){const i=e.pieces.get(t),r=e.pieces.get(n);return!!i&&(!r||r.color!==e.movable.color)&&e.predroppable.enabled&&(i.role!=="pawn"||n[1]!=="1"&&n[1]!=="8")&&e.movable.color===i.color&&e.turnColor!==i.color}function Pr(e,t){const n=e.pieces.get(t);return!!n&&e.draggable.enabled&&(e.movable.color==="both"||e.movable.color===n.color&&(e.turnColor===n.color||e.premovable.enabled))}function xr(e){const t=e.premovable.current;if(!t)return!1;const n=t[0],i=t[1];let r=!1;if(St(e,n,i)){const s=vn(e,n,i);if(s){const o={premove:!0};s!==!0&&(o.captured=s),F(e.movable.events.after,n,i,o),r=!0}}return he(e),r}function Mr(e,t){const n=e.predroppable.current;let i=!1;if(!n)return!1;if(t(n)){const r={role:n.role,color:e.movable.color};_t(e,r,n.key)&&(F(e.movable.events.afterNewPiece,n.role,n.key,{premove:!1,predrop:!0}),i=!0)}return de(e),i}function xt(e){he(e),de(e),Y(e)}function Pn(e){e.movable.color=e.movable.dests=e.animation.current=void 0,xt(e)}function ye(e,t,n){let i=Math.floor(8*(e[0]-n.left)/n.width);t||(i=7-i);let r=7-Math.floor(8*(e[1]-n.top)/n.height);return t||(r=7-r),i>=0&&i<8&&r>=0&&r<8?Z([i,r]):void 0}function Ar(e,t,n,i){const r=B(e),s=un.filter(c=>bn(r[0],r[1],c[0],c[1])||mn(r[0],r[1],c[0],c[1])),a=s.map(c=>fn(Z(c),n,i)).map(c=>Oe(t,c)),[,u]=a.reduce((c,p,f)=>c[0]<p?c:[p,f],[a[0],0]);return Z(s[u])}const G=e=>e.orientation==="white",xn="rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR",Or={p:"pawn",r:"rook",n:"knight",b:"bishop",q:"queen",k:"king"},Rr={pawn:"p",rook:"r",knight:"n",bishop:"b",queen:"q",king:"k"};function Mn(e){e==="start"&&(e=xn);const t=new Map;let n=7,i=0;for(const r of e)switch(r){case" ":case"[":return t;case"/":if(--n,n<0)return t;i=0;break;case"~":{const s=t.get(Z([i-1,n]));s&&(s.promoted=!0);break}default:{const s=r.charCodeAt(0);if(s<57)i+=s-48;else{const o=r.toLowerCase();t.set(Z([i,n]),{role:Or[o],color:r===o?"black":"white"}),++i}}}return t}function Tr(e){return er.map(t=>ze.map(n=>{const i=e.get(n+t);if(i){let r=Rr[i.role];return i.color==="white"&&(r=r.toUpperCase()),i.promoted&&(r+="~"),r}else return"1"}).join("")).join("/").replace(/1{2,}/g,t=>t.length.toString())}function An(e,t){t.animation&&(Mt(e.animation,t.animation),(e.animation.duration||0)<70&&(e.animation.enabled=!1))}function On(e,t){var n,i,r;if(!((n=t.movable)===null||n===void 0)&&n.dests&&(e.movable.dests=void 0),!((i=t.drawable)===null||i===void 0)&&i.autoShapes&&(e.drawable.autoShapes=[]),Mt(e,t),t.fen&&(e.pieces=Mn(t.fen),e.drawable.shapes=((r=t.drawable)===null||r===void 0?void 0:r.shapes)||[]),"check"in t&&wr(e,t.check||!1),"lastMove"in t&&!t.lastMove?e.lastMove=void 0:t.lastMove&&(e.lastMove=t.lastMove),e.selected&&En(e,e.selected),An(e,t),!e.movable.rookCastle&&e.movable.dests){const s=e.movable.color==="white"?"1":"8",o="e"+s,a=e.movable.dests.get(o),u=e.pieces.get(o);if(!a||!u||u.role!=="king")return;e.movable.dests.set(o,a.filter(c=>!(c==="a"+s&&a.includes("c"+s))&&!(c==="h"+s&&a.includes("g"+s))))}}function Mt(e,t){for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(Object.prototype.hasOwnProperty.call(e,n)&&Rn(e[n])&&Rn(t[n])?Mt(e[n],t[n]):e[n]=t[n])}function Rn(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}const ve=(e,t)=>t.animation.enabled?Dr(e,t):fe(e,t);function fe(e,t){const n=e(t);return t.dom.redraw(),n}const At=(e,t)=>({key:e,pos:B(e),piece:t}),Nr=(e,t)=>t.sort((n,i)=>Oe(e.pos,n.pos)-Oe(e.pos,i.pos))[0];function Br(e,t){const n=new Map,i=[],r=new Map,s=[],o=[],a=new Map;let u,c,p;for(const[f,_]of e)a.set(f,At(f,_));for(const f of kt)u=t.pieces.get(f),c=a.get(f),u?c?wt(u,c.piece)||(s.push(c),o.push(At(f,u))):o.push(At(f,u)):c&&s.push(c);for(const f of o)c=Nr(f,s.filter(_=>wt(f.piece,_.piece))),c&&(p=[c.pos[0]-f.pos[0],c.pos[1]-f.pos[1]],n.set(f.key,p.concat(p)),i.push(c.key));for(const f of s)i.includes(f.key)||r.set(f.key,f.piece);return{anims:n,fadings:r}}function Tn(e,t){const n=e.animation.current;if(n===void 0){e.dom.destroyed||e.dom.redrawNow();return}const i=1-(t-n.start)*n.frequency;if(i<=0)e.animation.current=void 0,e.dom.redrawNow();else{const r=Kr(i);for(const s of n.plan.anims.values())s[2]=s[0]*r,s[3]=s[1]*r;e.dom.redrawNow(!0),requestAnimationFrame((s=performance.now())=>Tn(e,s))}}function Dr(e,t){const n=new Map(t.pieces),i=e(t),r=Br(n,t);if(r.anims.size||r.fadings.size){const s=t.animation.current&&t.animation.current.start;t.animation.current={start:performance.now(),frequency:1/t.animation.duration,plan:r},s||Tn(t,performance.now())}else t.dom.redraw();return i}const Kr=e=>e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1,Lr=["green","red","blue","yellow"];function $r(e,t){if(t.touches&&t.touches.length>1)return;t.stopPropagation(),t.preventDefault(),t.ctrlKey?Y(e):xt(e);const n=be(t),i=ye(n,G(e),e.dom.bounds());i&&(e.drawable.current={orig:i,pos:n,brush:Wr(t),snapToValidMove:e.drawable.defaultSnapToValidMove},Nn(e))}function Nn(e){requestAnimationFrame(()=>{const t=e.drawable.current;if(t){const n=ye(t.pos,G(e),e.dom.bounds());n||(t.snapToValidMove=!1);const i=t.snapToValidMove?Ar(t.orig,t.pos,G(e),e.dom.bounds()):n;i!==t.mouseSq&&(t.mouseSq=i,t.dest=i!==t.orig?i:void 0,e.dom.redrawNow()),Nn(e)}})}function Ir(e,t){e.drawable.current&&(e.drawable.current.pos=be(t))}function zr(e){const t=e.drawable.current;t&&(t.mouseSq&&Fr(e.drawable,t),Bn(e))}function Bn(e){e.drawable.current&&(e.drawable.current=void 0,e.dom.redraw())}function qr(e){e.drawable.shapes.length&&(e.drawable.shapes=[],e.dom.redraw(),Dn(e.drawable))}function Wr(e){var t;const n=(e.shiftKey||e.ctrlKey)&&dn(e),i=e.altKey||e.metaKey||((t=e.getModifierState)===null||t===void 0?void 0:t.call(e,"AltGraph"));return Lr[(n?1:0)+(i?2:0)]}function Fr(e,t){const n=r=>r.orig===t.orig&&r.dest===t.dest,i=e.shapes.find(n);i&&(e.shapes=e.shapes.filter(r=>!n(r))),(!i||i.brush!==t.brush)&&e.shapes.push({orig:t.orig,dest:t.dest,brush:t.brush}),Dn(e)}function Dn(e){e.onChange&&e.onChange(e.shapes)}function Gr(e,t){if(!(e.trustAllEvents||t.isTrusted)||t.buttons!==void 0&&t.buttons>1||t.touches&&t.touches.length>1)return;const n=e.dom.bounds(),i=be(t),r=ye(i,G(e),n);if(!r)return;const s=e.pieces.get(r),o=e.selected;if(!o&&e.drawable.enabled&&(e.drawable.eraseOnClick||!s||s.color!==e.turnColor)&&qr(e),t.cancelable!==!1&&(!t.touches||e.blockTouchScroll||s||o||Ur(e,i)))t.preventDefault();else if(t.touches)return;const a=!!e.premovable.current,u=!!e.predroppable.current;e.stats.ctrlKey=t.ctrlKey,e.selected&&St(e,e.selected,r)?ve(f=>Et(f,r),e):Et(e,r);const c=e.selected===r,p=Ln(e,r);if(s&&p&&c&&Pr(e,r)){e.draggable.current={orig:r,piece:s,origPos:i,pos:i,started:e.draggable.autoDistance&&e.stats.dragged,element:p,previouslySelected:o,originTarget:t.target,keyHasChanged:!1},p.cgDragging=!0,p.classList.add("dragging");const f=e.dom.elements.ghost;f&&(f.className=`ghost ${s.color} ${s.role}`,te(f,Re(n)(B(r),G(e))),yt(f,!0)),Ot(e)}else a&&he(e),u&&de(e);e.dom.redraw()}function Ur(e,t){const n=G(e),i=e.dom.bounds(),r=Math.pow(i.width/8,2);for(const s of e.pieces.keys()){const o=fn(s,n,i);if(Oe(o,t)<=r)return!0}return!1}function Hr(e,t,n,i){const r="a0";e.pieces.set(r,t),e.dom.redraw();const s=be(n);e.draggable.current={orig:r,piece:t,origPos:s,pos:s,started:!0,element:()=>Ln(e,r),originTarget:n.target,newPiece:!0,force:!!i,keyHasChanged:!1},Ot(e)}function Ot(e){requestAnimationFrame(()=>{var t;const n=e.draggable.current;if(!n)return;!((t=e.animation.current)===null||t===void 0)&&t.plan.anims.has(n.orig)&&(e.animation.current=void 0);const i=e.pieces.get(n.orig);if(!i||!wt(i,n.piece))We(e);else if(!n.started&&Oe(n.pos,n.origPos)>=Math.pow(e.draggable.distance,2)&&(n.started=!0),n.started){if(typeof n.element=="function"){const s=n.element();if(!s)return;s.cgDragging=!0,s.classList.add("dragging"),n.element=s}const r=e.dom.bounds();te(n.element,[n.pos[0]-r.left-r.width/16,n.pos[1]-r.top-r.height/16]),n.keyHasChanged||(n.keyHasChanged=n.orig!==ye(n.pos,G(e),r))}Ot(e)})}function jr(e,t){e.draggable.current&&(!t.touches||t.touches.length<2)&&(e.draggable.current.pos=be(t))}function Vr(e,t){const n=e.draggable.current;if(!n)return;if(t.type==="touchend"&&t.cancelable!==!1&&t.preventDefault(),t.type==="touchend"&&n.originTarget!==t.target&&!n.newPiece){e.draggable.current=void 0;return}he(e),de(e);const i=be(t)||n.pos,r=ye(i,G(e),e.dom.bounds());r&&n.started&&n.orig!==r?n.newPiece?_n(e,n.orig,r,n.force):(e.stats.ctrlKey=t.ctrlKey,Cn(e,n.orig,r)&&(e.stats.dragged=!0)):n.newPiece?e.pieces.delete(n.orig):e.draggable.deleteOnDropOff&&!r&&(e.pieces.delete(n.orig),F(e.events.change)),(n.orig===n.previouslySelected||n.keyHasChanged)&&(n.orig===r||!r)?Y(e):e.selectable.enabled||Y(e),Kn(e),e.draggable.current=void 0,e.dom.redraw()}function We(e){const t=e.draggable.current;t&&(t.newPiece&&e.pieces.delete(t.orig),e.draggable.current=void 0,Y(e),Kn(e),e.dom.redraw())}function Kn(e){const t=e.dom.elements;t.ghost&&yt(t.ghost,!1)}function Ln(e,t){let n=e.dom.elements.board.firstChild;for(;n;){if(n.cgKey===t&&n.tagName==="PIECE")return n;n=n.nextSibling}}function Zr(e,t){e.exploding={stage:1,keys:t},e.dom.redraw(),setTimeout(()=>{$n(e,2),setTimeout(()=>$n(e,void 0),120)},120)}function $n(e,t){e.exploding&&(t?e.exploding.stage=t:e.exploding=void 0,e.dom.redraw())}function Yr(e,t){function n(){kr(e),t()}return{set(i){i.orientation&&i.orientation!==e.orientation&&n(),An(e,i),(i.fen?ve:fe)(r=>On(r,i),e)},state:e,getFen:()=>Tr(e.pieces),toggleOrientation:n,setPieces(i){ve(r=>br(r,i),e)},selectSquare(i,r){i?ve(s=>Et(s,i,r),e):e.selected&&(Y(e),e.dom.redraw())},move(i,r){ve(s=>yn(s,i,r),e)},newPiece(i,r){ve(s=>_t(s,i,r),e)},playPremove(){if(e.premovable.current){if(ve(xr,e))return!0;e.dom.redraw()}return!1},playPredrop(i){if(e.predroppable.current){const r=Mr(e,i);return e.dom.redraw(),r}return!1},cancelPremove(){fe(he,e)},cancelPredrop(){fe(de,e)},cancelMove(){fe(i=>{xt(i),We(i)},e)},stop(){fe(i=>{Pn(i),We(i)},e)},explode(i){Zr(e,i)},setAutoShapes(i){fe(r=>r.drawable.autoShapes=i,e)},setShapes(i){fe(r=>r.drawable.shapes=i,e)},getKeyAtDomPos(i){return ye(i,G(e),e.dom.bounds())},redrawAll:t,dragNewPiece(i,r,s){Hr(e,i,r,s)},destroy(){Pn(e),e.dom.unbind&&e.dom.unbind(),e.dom.destroyed=!0}}}function Qr(){return{pieces:Mn(xn),orientation:"white",turnColor:"white",coordinates:!0,coordinatesOnSquares:!1,ranksPosition:"right",autoCastle:!0,viewOnly:!1,disableContextMenu:!1,addPieceZIndex:!1,blockTouchScroll:!1,pieceKey:!1,trustAllEvents:!1,highlight:{lastMove:!0,check:!0},animation:{enabled:!0,duration:200},movable:{free:!0,color:"both",showDests:!0,events:{},rookCastle:!0},premovable:{enabled:!0,showDests:!0,castle:!0,events:{}},predroppable:{enabled:!1,events:{}},draggable:{enabled:!0,distance:3,autoDistance:!0,showGhost:!0,deleteOnDropOff:!1},dropmode:{active:!1},selectable:{enabled:!0},stats:{dragged:!("ontouchstart"in window)},events:{},drawable:{enabled:!0,visible:!0,defaultSnapToValidMove:!0,eraseOnClick:!0,shapes:[],autoShapes:[],brushes:{green:{key:"g",color:"#15781B",opacity:1,lineWidth:10},red:{key:"r",color:"#882020",opacity:1,lineWidth:10},blue:{key:"b",color:"#003088",opacity:1,lineWidth:10},yellow:{key:"y",color:"#e68f00",opacity:1,lineWidth:10},paleBlue:{key:"pb",color:"#003088",opacity:.4,lineWidth:15},paleGreen:{key:"pg",color:"#15781B",opacity:.4,lineWidth:15},paleRed:{key:"pr",color:"#882020",opacity:.4,lineWidth:15},paleGrey:{key:"pgr",color:"#4a4a4a",opacity:.35,lineWidth:15},purple:{key:"purple",color:"#68217a",opacity:.65,lineWidth:10},pink:{key:"pink",color:"#ee2080",opacity:.5,lineWidth:10},white:{key:"white",color:"white",opacity:1,lineWidth:10}},prevSvgHash:""},hold:ir()}}const In={hilitePrimary:{key:"hilitePrimary",color:"#3291ff",opacity:1,lineWidth:1},hiliteWhite:{key:"hiliteWhite",color:"#ffffff",opacity:1,lineWidth:1}};function Xr(){const e=L("defs"),t=W(L("filter"),{id:"cg-filter-blur"});return t.appendChild(W(L("feGaussianBlur"),{stdDeviation:"0.019"})),e.appendChild(t),e}function Jr(e,t,n){var i;const r=e.drawable,s=r.current,o=s&&s.mouseSq?s:void 0,a=new Map,u=e.dom.bounds(),c=r.autoShapes.filter(m=>!m.piece);for(const m of r.shapes.concat(c).concat(o?[o]:[])){if(!m.dest)continue;const h=(i=a.get(m.dest))!==null&&i!==void 0?i:new Set,d=Ue(Ge(B(m.orig),e.orientation),u),b=Ue(Ge(B(m.dest),e.orientation),u);h.add(Tt(d,b)),a.set(m.dest,h)}const p=r.shapes.concat(c).map(m=>({shape:m,current:!1,hash:zn(m,Rt(m.dest,a),!1,u)}));o&&p.push({shape:o,current:!0,hash:zn(o,Rt(o.dest,a),!0,u)});const f=p.map(m=>m.hash).join(";");if(f===e.drawable.prevSvgHash)return;e.drawable.prevSvgHash=f;const _=t.querySelector("defs");es(r,p,_),ts(p,t.querySelector("g"),n.querySelector("g"),m=>rs(e,m,r.brushes,a,u))}function es(e,t,n){var i;const r=new Map;let s;for(const u of t.filter(c=>c.shape.dest&&c.shape.brush))s=Wn(e.brushes[u.shape.brush],u.shape.modifiers),!((i=u.shape.modifiers)===null||i===void 0)&&i.hilite&&r.set(Fe(s).key,Fe(s)),r.set(s.key,s);const o=new Set;let a=n.firstElementChild;for(;a;)o.add(a.getAttribute("cgKey")),a=a.nextElementSibling;for(const[u,c]of r.entries())o.has(u)||n.appendChild(as(c))}function ts(e,t,n,i){const r=new Map;for(const s of e)r.set(s.hash,!1);for(const s of[t,n]){const o=[];let a=s.firstElementChild,u;for(;a;)u=a.getAttribute("cgHash"),r.has(u)?r.set(u,!0):o.push(a),a=a.nextElementSibling;for(const c of o)s.removeChild(c)}for(const s of e.filter(o=>!r.get(o.hash)))for(const o of i(s))o.isCustom?n.appendChild(o.el):t.appendChild(o.el)}function zn({orig:e,dest:t,brush:n,piece:i,modifiers:r,customSvg:s,label:o},a,u,c){var p,f;return[c.width,c.height,u,e,t,n,a&&"-",i&&ns(i),r&&is(r),s&&`custom-${qn(s.html)},${(f=(p=s.center)===null||p===void 0?void 0:p[0])!==null&&f!==void 0?f:"o"}`,o&&`label-${qn(o.text)}`].filter(_=>_).join(",")}function ns(e){return[e.color,e.role,e.scale].filter(t=>t).join(",")}function is(e){return[e.lineWidth,e.hilite&&"*"].filter(t=>t).join(",")}function qn(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)>>>0;return t.toString()}function rs(e,{shape:t,current:n,hash:i},r,s,o){var a,u;const c=Ue(Ge(B(t.orig),e.orientation),o),p=t.dest?Ue(Ge(B(t.dest),e.orientation),o):c,f=t.brush&&Wn(r[t.brush],t.modifiers),_=s.get(t.dest),m=[];if(f){const h=W(L("g"),{cgHash:i});m.push({el:h}),c[0]!==p[0]||c[1]!==p[1]?h.appendChild(os(t,f,c,p,n,Rt(t.dest,s))):h.appendChild(ss(r[t.brush],c,n,o))}if(t.label){const h=t.label;(a=h.fill)!==null&&a!==void 0||(h.fill=t.brush&&r[t.brush].color);const d=t.brush?void 0:"tr";m.push({el:cs(h,i,c,p,_,d),isCustom:!0})}if(t.customSvg){const h=(u=t.customSvg.center)!==null&&u!==void 0?u:"orig",[d,b]=h==="label"?Gn(c,p,_).map(v=>v-.5):h==="dest"?p:c,g=W(L("g"),{transform:`translate(${d},${b})`,cgHash:i});g.innerHTML=`<svg width="1" height="1" viewBox="0 0 100 100">${t.customSvg.html}</svg>`,m.push({el:g,isCustom:!0})}return m}function ss(e,t,n,i){const r=ls(),s=(i.width+i.height)/(4*Math.max(i.width,i.height));return W(L("circle"),{stroke:e.color,"stroke-width":r[n?0:1],fill:"none",opacity:Fn(e,n),cx:t[0],cy:t[1],r:s-r[1]/2})}function Fe(e){return["#ffffff","#fff","white"].includes(e.color)?In.hilitePrimary:In.hiliteWhite}function os(e,t,n,i,r,s){var o;function a(p){var f;const _=hs(s&&!r),m=i[0]-n[0],h=i[1]-n[1],d=Math.atan2(h,m),b=Math.cos(d)*_,g=Math.sin(d)*_;return W(L("line"),{stroke:p?Fe(t).color:t.color,"stroke-width":us(t,r)+(p?.04:0),"stroke-linecap":"round","marker-end":`url(#arrowhead-${p?Fe(t).key:t.key})`,opacity:!((f=e.modifiers)===null||f===void 0)&&f.hilite?1:Fn(t,r),x1:n[0],y1:n[1],x2:i[0]-b,y2:i[1]-g})}if(!(!((o=e.modifiers)===null||o===void 0)&&o.hilite))return a(!1);const u=L("g"),c=W(L("g"),{filter:"url(#cg-filter-blur)"});return c.appendChild(ds(n,i)),c.appendChild(a(!0)),u.appendChild(c),u.appendChild(a(!1)),u}function as(e){const t=W(L("marker"),{id:"arrowhead-"+e.key,orient:"auto",overflow:"visible",markerWidth:4,markerHeight:4,refX:e.key.startsWith("hilite")?1.86:2.05,refY:2});return t.appendChild(W(L("path"),{d:"M0,0 V4 L3,2 Z",fill:e.color})),t.setAttribute("cgKey",e.key),t}function cs(e,t,n,i,r,s){var o;const u=.4*.75**e.text.length,c=Gn(n,i,r),p=s==="tr"?.4:0,f=W(L("g"),{transform:`translate(${c[0]+p},${c[1]-p})`,cgHash:t});f.appendChild(W(L("circle"),{r:.4/2,"fill-opacity":s?1:.8,"stroke-opacity":s?1:.7,"stroke-width":.03,fill:(o=e.fill)!==null&&o!==void 0?o:"#666",stroke:"white"}));const _=W(L("text"),{"font-size":u,"font-family":"Noto Sans","text-anchor":"middle",fill:"white",y:.13*.75**e.text.length});return _.innerHTML=e.text,f.appendChild(_),f}function Ge(e,t){return t==="white"?e:[7-e[0],7-e[1]]}function Rt(e,t){return(e&&t.has(e)&&t.get(e).size>1)===!0}function L(e){return document.createElementNS("http://www.w3.org/2000/svg",e)}function W(e,t){for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.setAttribute(n,t[n]);return e}function Wn(e,t){return t?{color:e.color,opacity:Math.round(e.opacity*10)/10,lineWidth:Math.round(t.lineWidth||e.lineWidth),key:[e.key,t.lineWidth].filter(n=>n).join("")}:e}function ls(){return[3/64,4/64]}function us(e,t){return(e.lineWidth||10)*(t?.85:1)/64}function Fn(e,t){return(e.opacity||1)*(t?.9:1)}function hs(e){return(e?20:10)/64}function Ue(e,t){const n=Math.min(1,t.width/t.height),i=Math.min(1,t.height/t.width);return[(e[0]-3.5)*n,(3.5-e[1])*i]}function ds(e,t){const n={from:[Math.floor(Math.min(e[0],t[0])),Math.floor(Math.min(e[1],t[1]))],to:[Math.ceil(Math.max(e[0],t[0])),Math.ceil(Math.max(e[1],t[1]))]};return W(L("rect"),{x:n.from[0],y:n.from[1],width:n.to[0]-n.from[0],height:n.to[1]-n.from[1],fill:"none",stroke:"none"})}function Tt(e,t,n=!0){const i=Math.atan2(t[1]-e[1],t[0]-e[0])+Math.PI;return n?(Math.round(i*8/Math.PI)+16)%16:i}function fs(e,t){return Math.sqrt([e[0]-t[0],e[1]-t[1]].reduce((n,i)=>n+i*i,0))}function Gn(e,t,n){let i=fs(e,t);const r=Tt(e,t,!1);if(n&&(i-=33/64,n.size>1)){i-=10/64;const s=Tt(e,t);(n.has((s+1)%16)||n.has((s+15)%16))&&s&1&&(i-=.4)}return[e[0]-Math.cos(r)*i,e[1]-Math.sin(r)*i].map(s=>s+.5)}function ps(e,t){e.innerHTML="",e.classList.add("cg-wrap");for(const u of Ji)e.classList.toggle("orientation-"+u,t.orientation===u);e.classList.toggle("manipulable",!t.viewOnly);const n=re("cg-container");e.appendChild(n);const i=re("cg-board");n.appendChild(i);let r,s,o;if(t.drawable.visible&&(r=W(L("svg"),{class:"cg-shapes",viewBox:"-4 -4 8 8",preserveAspectRatio:"xMidYMid slice"}),r.appendChild(Xr()),r.appendChild(L("g")),s=W(L("svg"),{class:"cg-custom-svgs",viewBox:"-3.5 -3.5 8 8",preserveAspectRatio:"xMidYMid slice"}),s.appendChild(L("g")),o=re("cg-auto-pieces"),n.appendChild(r),n.appendChild(s),n.appendChild(o)),t.coordinates){const u=t.orientation==="black"?" black":"",c=t.ranksPosition==="left"?" left":"";if(t.coordinatesOnSquares){const p=t.orientation==="white"?f=>f+1:f=>8-f;ze.forEach((f,_)=>n.appendChild(Nt(qe.map(m=>f+m),"squares rank"+p(_)+u+c)))}else n.appendChild(Nt(qe,"ranks"+u+c)),n.appendChild(Nt(ze,"files"+u))}let a;return t.draggable.enabled&&t.draggable.showGhost&&(a=re("piece","ghost"),yt(a,!1),n.appendChild(a)),{board:i,container:n,wrap:e,ghost:a,svg:r,customSvg:s,autoPieces:o}}function Nt(e,t){const n=re("coords",t);let i;for(const r of e)i=re("coord"),i.textContent=r,n.appendChild(i);return n}function ms(e,t){if(!e.dropmode.active)return;he(e),de(e);const n=e.dropmode.piece;if(n){e.pieces.set("a0",n);const i=be(t),r=i&&ye(i,G(e),e.dom.bounds());r&&_n(e,"a0",r)}e.dom.redraw()}function gs(e,t){const n=e.dom.elements.board;if("ResizeObserver"in window&&new ResizeObserver(t).observe(e.dom.elements.wrap),(e.disableContextMenu||e.drawable.enabled)&&n.addEventListener("contextmenu",r=>r.preventDefault()),e.viewOnly)return;const i=bs(e);n.addEventListener("touchstart",i,{passive:!1}),n.addEventListener("mousedown",i,{passive:!1})}function ks(e,t){const n=[];if("ResizeObserver"in window||n.push(Te(document.body,"chessground.resize",t)),!e.viewOnly){const i=Un(e,jr,Ir),r=Un(e,Vr,zr);for(const o of["touchmove","mousemove"])n.push(Te(document,o,i));for(const o of["touchend","mouseup"])n.push(Te(document,o,r));const s=()=>e.dom.bounds.clear();n.push(Te(document,"scroll",s,{capture:!0,passive:!0})),n.push(Te(window,"resize",s,{passive:!0}))}return()=>n.forEach(i=>i())}function Te(e,t,n,i){return e.addEventListener(t,n,i),()=>e.removeEventListener(t,n,i)}const bs=e=>t=>{e.draggable.current?We(e):e.drawable.current?Bn(e):t.shiftKey||dn(t)?e.drawable.enabled&&$r(e,t):e.viewOnly||(e.dropmode.active?ms(e,t):Gr(e,t))},Un=(e,t,n)=>i=>{e.drawable.current?e.drawable.enabled&&n(e,i):e.viewOnly||t(e,i)};function ws(e){const t=G(e),n=Re(e.dom.bounds()),i=e.dom.elements.board,r=e.pieces,s=e.animation.current,o=s?s.plan.anims:new Map,a=s?s.plan.fadings:new Map,u=e.draggable.current,c=vs(e),p=new Set,f=new Set,_=new Map,m=new Map;let h,d,b,g,v,P,C,E,S,A;for(d=i.firstChild;d;){if(h=d.cgKey,jn(d))if(b=r.get(h),v=o.get(h),P=a.get(h),g=d.cgPiece,d.cgDragging&&(!u||u.orig!==h)&&(d.classList.remove("dragging"),te(d,n(B(h),t)),d.cgDragging=!1),!P&&d.cgFading&&(d.cgFading=!1,d.classList.remove("fading")),b){if(v&&d.cgAnimating&&g===Ne(b)){const w=B(h);w[0]+=v[2],w[1]+=v[3],d.classList.add("anim"),te(d,n(w,t))}else d.cgAnimating&&(d.cgAnimating=!1,d.classList.remove("anim"),te(d,n(B(h),t)),e.addPieceZIndex&&(d.style.zIndex=Bt(B(h),t)));g===Ne(b)&&(!P||!d.cgFading)?p.add(h):P&&g===Ne(P)?(d.classList.add("fading"),d.cgFading=!0):Dt(_,g,d)}else Dt(_,g,d);else if(Vn(d)){const w=d.className;c.get(h)===w?f.add(h):Dt(m,w,d)}d=d.nextSibling}for(const[w,O]of c)if(!f.has(w)){S=m.get(O),A=S&&S.pop();const T=n(B(w),t);if(A)A.cgKey=w,te(A,T);else{const R=re("square",O);R.cgKey=w,te(R,T),i.insertBefore(R,i.firstChild)}}for(const[w,O]of r)if(v=o.get(w),!p.has(w))if(C=_.get(Ne(O)),E=C&&C.pop(),E){E.cgKey=w,E.cgFading&&(E.classList.remove("fading"),E.cgFading=!1);const T=B(w);e.addPieceZIndex&&(E.style.zIndex=Bt(T,t)),v&&(E.cgAnimating=!0,E.classList.add("anim"),T[0]+=v[2],T[1]+=v[3]),te(E,n(T,t))}else{const T=Ne(O),R=re("piece",T),$=B(w);R.cgPiece=T,R.cgKey=w,v&&(R.cgAnimating=!0,$[0]+=v[2],$[1]+=v[3]),te(R,n($,t)),e.addPieceZIndex&&(R.style.zIndex=Bt($,t)),i.appendChild(R)}for(const w of _.values())Zn(e,w);for(const w of m.values())Zn(e,w)}function ys(e){const t=G(e),n=Re(e.dom.bounds());let i=e.dom.elements.board.firstChild;for(;i;)(jn(i)&&!i.cgAnimating||Vn(i))&&te(i,n(B(i.cgKey),t)),i=i.nextSibling}function Hn(e){var t,n;const i=e.dom.elements.wrap.getBoundingClientRect(),r=e.dom.elements.container,s=i.height/i.width,o=Math.floor(i.width*window.devicePixelRatio/8)*8/window.devicePixelRatio,a=o*s;r.style.width=o+"px",r.style.height=a+"px",e.dom.bounds.clear(),(t=e.addDimensionsCssVarsTo)===null||t===void 0||t.style.setProperty("---cg-width",o+"px"),(n=e.addDimensionsCssVarsTo)===null||n===void 0||n.style.setProperty("---cg-height",a+"px")}const jn=e=>e.tagName==="PIECE",Vn=e=>e.tagName==="SQUARE";function Zn(e,t){for(const n of t)e.dom.elements.board.removeChild(n)}function Bt(e,t){const i=e[1];return`${t?10-i:3+i}`}const Ne=e=>`${e.color} ${e.role}`;function vs(e){var t,n,i;const r=new Map;if(e.lastMove&&e.highlight.lastMove)for(const a of e.lastMove)se(r,a,"last-move");if(e.check&&e.highlight.check&&se(r,e.check,"check"),e.selected&&(se(r,e.selected,"selected"),e.movable.showDests)){const a=(t=e.movable.dests)===null||t===void 0?void 0:t.get(e.selected);if(a)for(const c of a)se(r,c,"move-dest"+(e.pieces.has(c)?" oc":""));const u=(i=(n=e.premovable.customDests)===null||n===void 0?void 0:n.get(e.selected))!==null&&i!==void 0?i:e.premovable.dests;if(u)for(const c of u)se(r,c,"premove-dest"+(e.pieces.has(c)?" oc":""))}const s=e.premovable.current;if(s)for(const a of s)se(r,a,"current-premove");else e.predroppable.current&&se(r,e.predroppable.current.key,"current-premove");const o=e.exploding;if(o)for(const a of o.keys)se(r,a,"exploding"+o.stage);return e.highlight.custom&&e.highlight.custom.forEach((a,u)=>{se(r,u,a)}),r}function se(e,t,n){const i=e.get(t);i?e.set(t,`${i} ${n}`):e.set(t,n)}function Dt(e,t,n){const i=e.get(t);i?i.push(n):e.set(t,[n])}function Cs(e,t,n){const i=new Map,r=[];for(const a of e)i.set(a.hash,!1);let s=t.firstElementChild,o;for(;s;)o=s.getAttribute("cgHash"),i.has(o)?i.set(o,!0):r.push(s),s=s.nextElementSibling;for(const a of r)t.removeChild(a);for(const a of e)i.get(a.hash)||t.appendChild(n(a))}function _s(e,t){const i=e.drawable.autoShapes.filter(r=>r.piece).map(r=>({shape:r,hash:Ps(r),current:!1}));Cs(i,t,r=>Ss(e,r,e.dom.bounds()))}function Es(e){var t;const n=G(e),i=Re(e.dom.bounds());let r=(t=e.dom.elements.autoPieces)===null||t===void 0?void 0:t.firstChild;for(;r;)hn(r,i(B(r.cgKey),n),r.cgScale),r=r.nextSibling}function Ss(e,{shape:t,hash:n},i){var r,s,o;const a=t.orig,u=(r=t.piece)===null||r===void 0?void 0:r.role,c=(s=t.piece)===null||s===void 0?void 0:s.color,p=(o=t.piece)===null||o===void 0?void 0:o.scale,f=re("piece",`${u} ${c}`);return f.setAttribute("cgHash",n),f.cgKey=a,f.cgScale=p,hn(f,Re(i)(B(a),G(e)),p),f}const Ps=e=>{var t,n,i;return[e.orig,(t=e.piece)===null||t===void 0?void 0:t.role,(n=e.piece)===null||n===void 0?void 0:n.color,(i=e.piece)===null||i===void 0?void 0:i.scale].join(",")};function xs(e,t){const n=Qr();On(n,t||{});function i(){const r="dom"in n?n.dom.unbind:void 0,s=ps(e,n),o=nr(()=>s.board.getBoundingClientRect()),a=p=>{ws(c),s.autoPieces&&_s(c,s.autoPieces),!p&&s.svg&&Jr(c,s.svg,s.customSvg)},u=()=>{Hn(c),ys(c),s.autoPieces&&Es(c)},c=n;return c.dom={elements:s,bounds:o,redraw:Ms(a),redrawNow:a,unbind:r},c.drawable.prevSvgHash="",Hn(c),a(!1),gs(c,u),r||(c.dom.unbind=ks(c,u)),c.events.insert&&c.events.insert(s),c}return Yr(i(),i)}function Ms(e){let t=!1;return()=>{t||(t=!0,requestAnimationFrame(()=>{e(),t=!1}))}}function As(e,t){return document.createElement(e,t)}function Os(e,t,n){return document.createElementNS(e,t,n)}function Rs(){return Ce(document.createDocumentFragment())}function Ts(e){return document.createTextNode(e)}function Ns(e){return document.createComment(e)}function Bs(e,t,n){if(oe(e)){let i=e;for(;i&&oe(i);)i=Ce(i).parent;e=i??e}oe(t)&&(t=Ce(t,e)),n&&oe(n)&&(n=Ce(n).firstChildNode),e.insertBefore(t,n)}function Ds(e,t){e.removeChild(t)}function Ks(e,t){oe(t)&&(t=Ce(t,e)),e.appendChild(t)}function Yn(e){if(oe(e)){for(;e&&oe(e);)e=Ce(e).parent;return e??null}return e.parentNode}function Ls(e){var t;if(oe(e)){const n=Ce(e),i=Yn(n);if(i&&n.lastChildNode){const r=Array.from(i.childNodes),s=r.indexOf(n.lastChildNode);return(t=r[s+1])!==null&&t!==void 0?t:null}return null}return e.nextSibling}function $s(e){return e.tagName}function Is(e,t){e.textContent=t}function zs(e){return e.textContent}function qs(e){return e.nodeType===1}function Ws(e){return e.nodeType===3}function Fs(e){return e.nodeType===8}function oe(e){return e.nodeType===11}function Ce(e,t){var n,i,r;const s=e;return(n=s.parent)!==null&&n!==void 0||(s.parent=t??null),(i=s.firstChildNode)!==null&&i!==void 0||(s.firstChildNode=e.firstChild),(r=s.lastChildNode)!==null&&r!==void 0||(s.lastChildNode=e.lastChild),s}const Gs={createElement:As,createElementNS:Os,createTextNode:Ts,createDocumentFragment:Rs,createComment:Ns,insertBefore:Bs,removeChild:Ds,appendChild:Ks,parentNode:Yn,nextSibling:Ls,tagName:$s,setTextContent:Is,getTextContent:zs,isElement:qs,isText:Ws,isComment:Fs,isDocumentFragment:oe};function Be(e,t,n,i,r){const s=t===void 0?void 0:t.key;return{sel:e,data:t,children:n,text:i,elm:r,key:s}}const He=Array.isArray;function je(e){return typeof e=="string"||typeof e=="number"||e instanceof String||e instanceof Number}function Ve(e){return e===void 0}function U(e){return e!==void 0}const Kt=Be("",{},[],void 0,void 0);function De(e,t){var n,i;const r=e.key===t.key,s=((n=e.data)===null||n===void 0?void 0:n.is)===((i=t.data)===null||i===void 0?void 0:i.is),o=e.sel===t.sel,a=!e.sel&&e.sel===t.sel?typeof e.text==typeof t.text:!0;return o&&r&&s&&a}function Us(){throw new Error("The document fragment is not supported on this platform.")}function Hs(e,t){return e.isElement(t)}function js(e,t){return e.isDocumentFragment(t)}function Vs(e,t,n){var i;const r={};for(let s=t;s<=n;++s){const o=(i=e[s])===null||i===void 0?void 0:i.key;o!==void 0&&(r[o]=s)}return r}const Zs=["create","update","remove","destroy","pre","post"];function Ys(e,t,n){const i={create:[],update:[],remove:[],destroy:[],pre:[],post:[]},r=Gs;for(const h of Zs)for(const d of e){const b=d[h];b!==void 0&&i[h].push(b)}function s(h){const d=h.id?"#"+h.id:"",b=h.getAttribute("class"),g=b?"."+b.split(" ").join("."):"";return Be(r.tagName(h).toLowerCase()+d+g,{},[],void 0,h)}function o(h){return Be(void 0,{},[],void 0,h)}function a(h,d){return function(){if(--d===0){const g=r.parentNode(h);g!==null&&r.removeChild(g,h)}}}function u(h,d){var b,g,v,P;let C,E=h.data;if(E!==void 0){const w=(b=E.hook)===null||b===void 0?void 0:b.init;U(w)&&(w(h),E=h.data)}const S=h.children,A=h.sel;if(A==="!")Ve(h.text)&&(h.text=""),h.elm=r.createComment(h.text);else if(A==="")h.elm=r.createTextNode(h.text);else if(A!==void 0){const w=A.indexOf("#"),O=A.indexOf(".",w),T=w>0?w:A.length,R=O>0?O:A.length,$=w!==-1||O!==-1?A.slice(0,Math.min(T,R)):A,ee=h.elm=U(E)&&U(C=E.ns)?r.createElementNS(C,$,E):r.createElement($,E);for(T<R&&ee.setAttribute("id",A.slice(T+1,R)),O>0&&ee.setAttribute("class",A.slice(R+1).replace(/\./g," ")),C=0;C<i.create.length;++C)i.create[C](Kt,h);if(je(h.text)&&(!He(S)||S.length===0)&&r.appendChild(ee,r.createTextNode(h.text)),He(S))for(C=0;C<S.length;++C){const ci=S[C];ci!=null&&r.appendChild(ee,u(ci,d))}const Je=h.data.hook;U(Je)&&((g=Je.create)===null||g===void 0||g.call(Je,Kt,h),Je.insert&&d.push(h))}else if(!((v=void 0)===null||v===void 0)&&v.fragments&&h.children){for(h.elm=((P=r.createDocumentFragment)!==null&&P!==void 0?P:Us)(),C=0;C<i.create.length;++C)i.create[C](Kt,h);for(C=0;C<h.children.length;++C){const w=h.children[C];w!=null&&r.appendChild(h.elm,u(w,d))}}else h.elm=r.createTextNode(h.text);return h.elm}function c(h,d,b,g,v,P){for(;g<=v;++g){const C=b[g];C!=null&&r.insertBefore(h,u(C,P),d)}}function p(h){var d,b;const g=h.data;if(g!==void 0){(b=(d=g==null?void 0:g.hook)===null||d===void 0?void 0:d.destroy)===null||b===void 0||b.call(d,h);for(let v=0;v<i.destroy.length;++v)i.destroy[v](h);if(h.children!==void 0)for(let v=0;v<h.children.length;++v){const P=h.children[v];P!=null&&typeof P!="string"&&p(P)}}}function f(h,d,b,g){for(var v,P;b<=g;++b){let C,E;const S=d[b];if(S!=null)if(U(S.sel)){p(S),C=i.remove.length+1,E=a(S.elm,C);for(let w=0;w<i.remove.length;++w)i.remove[w](S,E);const A=(P=(v=S==null?void 0:S.data)===null||v===void 0?void 0:v.hook)===null||P===void 0?void 0:P.remove;U(A)?A(S,E):E()}else S.children?(p(S),f(h,S.children,0,S.children.length-1)):r.removeChild(h,S.elm)}}function _(h,d,b,g){let v=0,P=0,C=d.length-1,E=d[0],S=d[C],A=b.length-1,w=b[0],O=b[A],T,R,$,ee;for(;v<=C&&P<=A;)E==null?E=d[++v]:S==null?S=d[--C]:w==null?w=b[++P]:O==null?O=b[--A]:De(E,w)?(m(E,w,g),E=d[++v],w=b[++P]):De(S,O)?(m(S,O,g),S=d[--C],O=b[--A]):De(E,O)?(m(E,O,g),r.insertBefore(h,E.elm,r.nextSibling(S.elm)),E=d[++v],O=b[--A]):De(S,w)?(m(S,w,g),r.insertBefore(h,S.elm,E.elm),S=d[--C],w=b[++P]):(T===void 0&&(T=Vs(d,v,C)),R=T[w.key],Ve(R)?(r.insertBefore(h,u(w,g),E.elm),w=b[++P]):Ve(T[O.key])?(r.insertBefore(h,u(O,g),r.nextSibling(S.elm)),O=b[--A]):($=d[R],$.sel!==w.sel?r.insertBefore(h,u(w,g),E.elm):(m($,w,g),d[R]=void 0,r.insertBefore(h,$.elm,E.elm)),w=b[++P]));P<=A&&(ee=b[A+1]==null?null:b[A+1].elm,c(h,ee,b,P,A,g)),v<=C&&f(h,d,v,C)}function m(h,d,b){var g,v,P,C,E,S,A,w;const O=(g=d.data)===null||g===void 0?void 0:g.hook;(v=O==null?void 0:O.prepatch)===null||v===void 0||v.call(O,h,d);const T=d.elm=h.elm;if(h===d)return;if(d.data!==void 0||U(d.text)&&d.text!==h.text){(P=d.data)!==null&&P!==void 0||(d.data={}),(C=h.data)!==null&&C!==void 0||(h.data={});for(let ee=0;ee<i.update.length;++ee)i.update[ee](h,d);(A=(S=(E=d.data)===null||E===void 0?void 0:E.hook)===null||S===void 0?void 0:S.update)===null||A===void 0||A.call(S,h,d)}const R=h.children,$=d.children;Ve(d.text)?U(R)&&U($)?R!==$&&_(T,R,$,b):U($)?(U(h.text)&&r.setTextContent(T,""),c(T,null,$,0,$.length-1,b)):U(R)?f(T,R,0,R.length-1):U(h.text)&&r.setTextContent(T,""):h.text!==d.text&&(U(R)&&f(T,R,0,R.length-1),r.setTextContent(T,d.text)),(w=O==null?void 0:O.postpatch)===null||w===void 0||w.call(O,h,d)}return function(d,b){let g,v,P;const C=[];for(g=0;g<i.pre.length;++g)i.pre[g]();for(Hs(r,d)?d=s(d):js(r,d)&&(d=o(d)),De(d,b)?m(d,b,C):(v=d.elm,P=r.parentNode(v),u(b,C),P!==null&&(r.insertBefore(P,b.elm,r.nextSibling(v)),f(P,[d],0,0))),g=0;g<C.length;++g)C[g].data.hook.insert(C[g]);for(g=0;g<i.post.length;++g)i.post[g]();return b}}function Qn(e,t,n){if(e.ns="http://www.w3.org/2000/svg",n!=="foreignObject"&&t!==void 0)for(let i=0;i<t.length;++i){const r=t[i];if(typeof r=="string")continue;const s=r.data;s!==void 0&&Qn(s,r.children,r.sel)}}function M(e,t,n){let i={},r,s,o;if(n!==void 0?(t!==null&&(i=t),He(n)?r=n:je(n)?s=n.toString():n&&n.sel&&(r=[n])):t!=null&&(He(t)?r=t:je(t)?s=t.toString():t&&t.sel?r=[t]:i=t),r!==void 0)for(o=0;o<r.length;++o)je(r[o])&&(r[o]=Be(void 0,void 0,void 0,r[o],void 0));return e.startsWith("svg")&&(e.length===3||e[3]==="."||e[3]==="#")&&Qn(i,r,e),Be(e,i,r,s,void 0)}const Qs="http://www.w3.org/1999/xlink",Xs="http://www.w3.org/2000/xmlns/",Js="http://www.w3.org/XML/1998/namespace",Xn=58,eo=120,to=109;function Jn(e,t){let n;const i=t.elm;let r=e.data.attrs,s=t.data.attrs;if(!(!r&&!s)&&r!==s){r=r||{},s=s||{};for(n in s){const o=s[n];r[n]!==o&&(o===!0?i.setAttribute(n,""):o===!1?i.removeAttribute(n):n.charCodeAt(0)!==eo?i.setAttribute(n,o):n.charCodeAt(3)===Xn?i.setAttributeNS(Js,n,o):n.charCodeAt(5)===Xn?n.charCodeAt(1)===to?i.setAttributeNS(Xs,n,o):i.setAttributeNS(Qs,n,o):i.setAttribute(n,o))}for(n in r)n in s||i.removeAttribute(n)}}const no={create:Jn,update:Jn};function ei(e,t){let n,i;const r=t.elm;let s=e.data.class,o=t.data.class;if(!(!s&&!o)&&s!==o){s=s||{},o=o||{};for(i in s)s[i]&&!Object.prototype.hasOwnProperty.call(o,i)&&r.classList.remove(i);for(i in o)n=o[i],n!==s[i]&&r.classList[n?"add":"remove"](i)}}const io={create:ei,update:ei};function ro(e,t,n){for(const i of["touchstart","mousedown"])e.addEventListener(i,r=>{t(r),r.preventDefault()},{passive:!1})}const Lt=(e,t,n,i=!0)=>Ze(r=>r.addEventListener(e,s=>{const o=t(s);return o===!1&&s.preventDefault(),o},{passive:i}));function Ze(e){return{insert:t=>e(t.elm)}}function so(e){let t=0;return n=>{t+=n.deltaY*(n.deltaMode?40:1),Math.abs(t)>=4?(e(n,!0),t=0):e(n,!1)}}function oo(e,t){const n=()=>{e(),i=Math.max(100,i-i/15),r=setTimeout(n,i)};let i=350,r=setTimeout(n,500);e();const s=t.type=="touchstart"?"touchend":"mouseup";document.addEventListener(s,()=>clearTimeout(r),{once:!0})}const ao=e=>e.altKey||e.ctrlKey||e.shiftKey||e.metaKey||document.activeElement instanceof HTMLInputElement||document.activeElement instanceof HTMLTextAreaElement,co=e=>t=>{ao(t)||(t.key=="ArrowLeft"?e.goTo("prev"):t.key=="ArrowRight"?e.goTo("next"):t.key=="f"&&e.flip())},lo=e=>{var t,n;return M("div.lpv__menu.lpv__pane",[M("button.lpv__menu__entry.lpv__menu__flip.lpv__fbt",{hook:Lt("click",e.flip)},e.translate("flipTheBoard")),!((t=e.opts.menu.analysisBoard)===null||t===void 0)&&t.enabled?M("a.lpv__menu__entry.lpv__menu__analysis.lpv__fbt",{attrs:{href:e.analysisUrl(),target:"_blank"}},e.translate("analysisBoard")):void 0,!((n=e.opts.menu.practiceWithComputer)===null||n===void 0)&&n.enabled?M("a.lpv__menu__entry.lpv__menu__practice.lpv__fbt",{attrs:{href:e.practiceUrl(),target:"_blank"}},e.translate("practiceWithComputer")):void 0,e.opts.menu.getPgn.enabled?M("button.lpv__menu__entry.lpv__menu__pgn.lpv__fbt",{hook:Lt("click",e.togglePgn)},e.translate("getPgn")):void 0,uo(e)])},uo=e=>{const t=e.game.metadata.externalLink;return t&&M("a.lpv__menu__entry.lpv__fbt",{attrs:{href:t,target:"_blank"}},e.translate(e.game.metadata.isLichess?"viewOnLichess":"viewOnSite"))},ho=e=>M("div.lpv__controls",[e.pane=="board"?void 0:Ye(e,"first","step-backward"),Ye(e,"prev","left-open"),M("button.lpv__fbt.lpv__controls__menu.lpv__icon",{class:{active:e.pane!="board","lpv__icon-ellipsis-vert":e.pane=="board"},hook:Lt("click",e.toggleMenu)},e.pane=="board"?void 0:"X"),Ye(e,"next","right-open"),e.pane=="board"?void 0:Ye(e,"last","step-forward")]),Ye=(e,t,n)=>M(`button.lpv__controls__goto.lpv__controls__goto--${t}.lpv__fbt.lpv__icon.lpv__icon-${n}`,{class:{disabled:e.pane=="board"&&!e.canGoTo(t)},hook:Ze(i=>ro(i,r=>oo(()=>e.goTo(t),r)))}),fo=e=>{const t=po[e];return t?M("nag",{attrs:{title:t.name}},t.symbol):void 0},po={1:{symbol:"!",name:"Good move"},2:{symbol:"?",name:"Mistake"},3:{symbol:"!!",name:"Brilliant move"},4:{symbol:"??",name:"Blunder"},5:{symbol:"!?",name:"Interesting move"},6:{symbol:"?!",name:"Dubious move"},7:{symbol:"□",name:"Only move"},22:{symbol:"⨀",name:"Zugzwang"},10:{symbol:"=",name:"Equal position"},13:{symbol:"∞",name:"Unclear position"},14:{symbol:"⩲",name:"White is slightly better"},15:{symbol:"⩱",name:"Black is slightly better"},16:{symbol:"±",name:"White is better"},17:{symbol:"∓",name:"Black is better"},18:{symbol:"+−",name:"White is winning"},19:{symbol:"-+",name:"Black is winning"},146:{symbol:"N",name:"Novelty"},32:{symbol:"↑↑",name:"Development"},36:{symbol:"↑",name:"Initiative"},40:{symbol:"→",name:"Attack"},132:{symbol:"⇆",name:"Counterplay"},138:{symbol:"⊕",name:"Time trouble"},44:{symbol:"=∞",name:"With compensation"},140:{symbol:"∆",name:"With the idea"}},mo=e=>M("div.lpv__side",[M("div.lpv__moves",{hook:{insert:t=>{const n=t.elm;e.path.empty()||ni(e,n),n.addEventListener("mousedown",i=>{const r=i.target.getAttribute("p");r&&e.toPath(new J(r))},{passive:!0})},postpatch:(t,n)=>{e.autoScrollRequested&&(ni(e,n.elm),e.autoScrollRequested=!1)}}},[...e.game.initial.comments.map(Qe),...wo(e),...go(e)])]),go=e=>{const t=e.game.metadata.result;return t&&t!="*"?[M("comment.result",e.game.metadata.result)]:[]},$t=()=>M("move.empty","..."),It=e=>M("index",`${e}.`),Qe=e=>M("comment",e),ko=()=>M("paren.open","("),bo=()=>M("paren.close",")"),Xe=e=>Math.floor((e.ply-1)/2)+1,wo=e=>{const t=vo(e),n=[];let i,r=e.game.moves.children.slice(1);for(e.game.initial.pos.turn=="black"&&e.game.mainline[0]&&n.push(It(e.game.initial.pos.fullmoves),$t());i=(i||e.game.moves).children[0];){const s=i.data,o=s.ply%2==1;o&&n.push(It(Xe(s))),n.push(t(s));const a=o&&(r.length||s.comments.length)&&i.children.length;a&&n.push($t()),s.comments.forEach(u=>n.push(Qe(u))),r.forEach(u=>n.push(yo(t,u))),a&&n.push(It(Xe(s)),$t()),r=i.children.slice(1)}return n},yo=(e,t)=>M("variation",[...t.data.startingComments.map(Qe),...ti(e,t)]),ti=(e,t)=>{let n=[],i=[];t.data.ply%2==0&&n.push(M("index",[Xe(t.data),"..."]));do{const r=t.data;r.ply%2==1&&n.push(M("index",[Xe(r),"."])),n.push(e(r)),r.comments.forEach(s=>n.push(Qe(s))),i.forEach(s=>{n=[...n,ko(),...ti(e,s),bo()]}),i=t.children.slice(1),t=t.children[0]}while(t);return n},vo=e=>t=>M("move",{class:{current:e.path.equals(t.path),ancestor:e.path.contains(t.path),good:t.nags.includes(1),mistake:t.nags.includes(2),brilliant:t.nags.includes(3),blunder:t.nags.includes(4),interesting:t.nags.includes(5),inaccuracy:t.nags.includes(6)},attrs:{p:t.path.path}},[t.san,...t.nags.map(fo)]),ni=(e,t)=>{const n=t.querySelector(".current");if(!n){t.scrollTop=e.path.empty()?0:99999;return}t.scrollTop=n.offsetTop-t.offsetHeight/2+n.offsetHeight};function ii(e,t){const n=t=="bottom"?e.orientation():x(e.orientation()),i=e.game.players[n],r=[i.title?M("span.lpv__player__title",i.title):void 0,M("span.lpv__player__name",i.name),i.rating?M("span.lpv__player__rating",["(",i.rating,")"]):void 0];return M(`div.lpv__player.lpv__player--${t}`,[i.isLichessUser?M("a.lpv__player__person.ulpt.user-link",{attrs:{href:`${e.opts.lichess}/@/${i.name}`}},r):M("span.lpv__player__person",r),e.opts.showClocks?Co(e,n):void 0])}const Co=(e,t)=>{const n=e.curData(),i=n.clocks&&n.clocks[t];return typeof i==null?void 0:M("div.lpv__player__clock",{class:{active:t==n.turn}},_o(i))},_o=e=>{if(!e&&e!==0)return["-"];const t=new Date(e*1e3),n=":",i=ri(t.getUTCMinutes())+n+ri(t.getUTCSeconds());return e>=3600?[Math.floor(e/3600)+n+i]:[i]},ri=e=>(e<10?"0":"")+e;function si(e){const t=e.opts,n=`lpv.lpv--moves-${t.showMoves}.lpv--controls-${t.showControls}${t.classes?"."+t.classes.replace(" ","."):""}`,i=t.showPlayers=="auto"?e.game.hasPlayerName():t.showPlayers;return M(`div.${n}`,{class:{"lpv--menu":e.pane!="board","lpv--players":i},attrs:{tabindex:0},hook:Ze(r=>{e.setGround(xs(r.querySelector(".cg-wrap"),Po(e,r))),t.keyboardToMove&&r.addEventListener("keydown",co(e))})},[i?ii(e,"top"):void 0,Eo(e),i?ii(e,"bottom"):void 0,t.showControls?ho(e):void 0,t.showMoves?mo(e):void 0,e.pane=="menu"?lo(e):e.pane=="pgn"?So(e):void 0])}const Eo=e=>M("div.lpv__board",{hook:Ze(t=>{t.addEventListener("click",e.focus),e.opts.scrollToMove&&!("ontouchstart"in window)&&t.addEventListener("wheel",so((n,i)=>{n.preventDefault(),n.deltaY>0&&i?e.goTo("next",!1):n.deltaY<0&&i&&e.goTo("prev",!1)}))})},M("div.cg-wrap")),So=e=>{const t=new Blob([e.opts.pgn],{type:"text/plain"});return M("div.lpv__pgn.lpv__pane",[M("a.lpv__pgn__download.lpv__fbt",{attrs:{href:window.URL.createObjectURL(t),download:e.opts.menu.getPgn.fileName||`${e.game.title()}.pgn`}},e.translate("download")),M("textarea.lpv__pgn__text",e.opts.pgn)])},Po=(e,t)=>({viewOnly:!e.opts.drawArrows,addDimensionsCssVarsTo:t,drawable:{enabled:e.opts.drawArrows,visible:!0},disableContextMenu:e.opts.drawArrows,...e.opts.chessground||{},movable:{free:!1},draggable:{enabled:!1},selectable:{enabled:!1},...e.cgState()}),xo={pgn:"*",fen:void 0,showPlayers:"auto",showClocks:!0,showMoves:"auto",showControls:!0,scrollToMove:!0,keyboardToMove:!0,orientation:void 0,initialPly:0,chessground:{},drawArrows:!0,menu:{getPgn:{enabled:!0,fileName:void 0},practiceWithComputer:{enabled:!0},analysisBoard:{enabled:!0}},lichess:"https://lichess.org",classes:void 0};function Mo(e,t){const n={...xo};return oi(n,t),n.fen&&(n.pgn=`[FEN "${n.fen}"]
4
+ ${n.pgn}`),n.classes||(n.classes=e.className),n}function oi(e,t){for(const n in t)typeof t[n]<"u"&&(ai(e[n])&&ai(t[n])?oi(e[n],t[n]):e[n]=t[n])}function ai(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Ao(e,t){const n=Ys([io,no]),i=Mo(e,t),r=new fr(i,a),s=si(r);e.innerHTML="";let o=n(e,s);r.div=o.elm;function a(){o=n(o,si(r))}return r}class Oo{constructor(t,n){et(this,"viewer");this.viewer=Ao(t,{...n})}get api(){return this.viewer}}class Ro{constructor(t){et(this,"config");et(this,"viewer");this.config=t}mount(t){this.viewer=new Oo(t,this.config)}get api(){return this.viewer.api}}const To=I.defineComponent({__name:"PgnViewer",props:{config:{}},emits:["ready"],setup(e,{emit:t}){const n=e,i=t,r=I.ref(null),s=new Ro({...n.config}),o=()=>s.mount(r.value),a=()=>i("ready",s.api);return I.onMounted(()=>{o(),a()}),(u,c)=>(I.openBlock(),I.createElementBlock("div",{ref_key:"div",ref:r},null,512))}});H.PgnViewer=To,Object.defineProperty(H,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,16 +1,30 @@
1
1
  {
2
2
  "name": "vue-pgn-viewer",
3
+ "version": "0.3.0",
3
4
  "description": "Vue 3 wrapper around official Lichess PGN viewer",
5
+ "keywords": [
6
+ "vue",
7
+ "pgn-viewer",
8
+ "chess",
9
+ "lichess",
10
+ "component",
11
+ "widget"
12
+ ],
13
+ "homepage": "https://github.com/dragunovartem99/vue-pgn-viewer",
14
+ "bugs": {
15
+ "url": "https://github.com/dragunovartem99/vue-pgn-viewer/issues",
16
+ "email": "dragunovartem99@gmail.com"
17
+ },
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/dragunovartem99/vue-pgn-viewer.git"
21
+ },
4
22
  "license": "GPL-3.0-or-later",
5
- "version": "0.2.1",
6
- "author": "Artem Dragunov <dragunovartem99@gmail.com>",
23
+ "author": {
24
+ "name": "Artem Dragunov",
25
+ "email": "dragunovartem99@gmail.com"
26
+ },
7
27
  "type": "module",
8
- "files": [
9
- "dist"
10
- ],
11
- "main": "./dist/vue-pgn-viewer.umd.cjs",
12
- "module": "./dist/vue-pgn-viewer.js",
13
- "types": "./dist/vue-pgn-viewer.d.ts",
14
28
  "exports": {
15
29
  ".": {
16
30
  "import": "./dist/vue-pgn-viewer.js",
@@ -18,13 +32,21 @@
18
32
  },
19
33
  "./style.css": "./dist/vue-pgn-viewer.css"
20
34
  },
35
+ "main": "./dist/vue-pgn-viewer.umd.cjs",
36
+ "module": "./dist/vue-pgn-viewer.js",
37
+ "types": "./dist/vue-pgn-viewer.d.ts",
38
+ "files": [
39
+ "dist"
40
+ ],
21
41
  "scripts": {
22
- "dev": "vite",
23
42
  "build": "vue-tsc -b && vite build",
43
+ "dev": "vite",
44
+ "format": "prettier . --write",
24
45
  "preview": "vite preview -c web.config.ts",
25
- "web": "vue-tsc -b && vite build -c web.config.ts",
26
- "format": "prettier . --write"
46
+ "test": "vitest",
47
+ "web": "vue-tsc -b && vite build -c web.config.ts"
27
48
  },
49
+ "prettier": "@dragunovartem99/prettier-config",
28
50
  "dependencies": {
29
51
  "lichess-pgn-viewer": "^2.3.0",
30
52
  "vue": "^3.5.13"
@@ -34,11 +56,12 @@
34
56
  "@types/node": "^22.12.0",
35
57
  "@vitejs/plugin-vue": "^5.2.1",
36
58
  "@vue/tsconfig": "^0.7.0",
59
+ "jsdom": "^26.0.0",
37
60
  "prettier": "^3.4.2",
38
61
  "typescript": "~5.6.2",
39
62
  "vite": "^6.0.5",
40
63
  "vite-plugin-dts": "^4.5.0",
64
+ "vitest": "^3.0.5",
41
65
  "vue-tsc": "^2.2.0"
42
- },
43
- "prettier": "@dragunovartem99/prettier-config"
66
+ }
44
67
  }