-
Notifications
You must be signed in to change notification settings - Fork 0
/
svg.ts
98 lines (86 loc) · 2.27 KB
/
svg.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// NOTE: This skips a bunch of stuff for now.
// This only implements enough for `pgn.ts` to work.
import { parseSquare, Square, SQUARE_NAMES } from './index'
/**
* Details of an arrow to be drawn.
*/
export class Arrow {
/** Start square of the arrow. */
tail: Square
/** End square of the arrow. */
head: Square
/** Arrow color. */
color: string
constructor(
tail: Square,
head: Square,
{ color = 'green' }: { color?: string } = {},
) {
this.tail = tail
this.head = head
this.color = color
}
/**
* Returns the arrow in the format used by ``[%csl ...]`` and
* ``[%cal ...]`` PGN annotations, e.g., ``Ga1`` or ``Ya2h2``.
*
* Colors other than ``red``, ``yellow``, and ``blue`` default to green.
*/
pgn(): string {
let color: string
if (this.color === 'red') {
color = 'R'
} else if (this.color === 'yellow') {
color = 'Y'
} else if (this.color === 'blue') {
color = 'B'
} else {
color = 'G'
}
if (this.tail === this.head) {
return `${color}${SQUARE_NAMES[this.tail]}`
} else {
return `${color}${SQUARE_NAMES[this.tail]}${SQUARE_NAMES[this.head]}`
}
}
// __str__()
toString(): string {
return this.pgn()
}
// __repr__()
toRepr(): string {
return `Arrow(${SQUARE_NAMES[this.tail].toUpperCase()}, ${SQUARE_NAMES[this.head].toUpperCase()}, color=${this.color})`
}
/**
* Parses an arrow from the format used by ``[%csl ...]`` and
* ``[%cal ...]`` PGN annotations, e.g., ``Ga1`` or ``Ya2h2``.
*
* Also allows skipping the color prefix, defaulting to green.
*
* :raises: :exc:`ValueError` if the format is invalid.
*/
static fromPgn(pgn: string): Arrow {
let color: string
if (pgn.startsWith('G')) {
color = 'green'
pgn = pgn.slice(1)
} else if (pgn.startsWith('R')) {
color = 'red'
pgn = pgn.slice(1)
} else if (pgn.startsWith('Y')) {
color = 'yellow'
pgn = pgn.slice(1)
} else if (pgn.startsWith('B')) {
color = 'blue'
pgn = pgn.slice(1)
} else {
color = 'green'
}
const tail = parseSquare(pgn.slice(0, 2))
const head = pgn.length > 2 ? parseSquare(pgn.slice(2)) : tail
return new this(tail, head, { color })
}
}
export default {
Arrow,
}