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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
|
# ==============================================================================
# Copyright (C) 2019 - Philip Paquette, Steven Bocco
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
# details.
#
# You should have received a copy of the GNU Affero General Public License along
# with this program. If not, see <https://www.gnu.org/licenses/>.
# ==============================================================================
""" Helper script to convert a SVG file into a React JS component file.
Type ``python <script name> --help`` for help.
"""
import argparse
import os
import re
from xml.dom import minidom, Node
import ujson as json
LICENSE_TEXT = """/**
==============================================================================
Copyright (C) 2019 - Philip Paquette, Steven Bocco
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <https:www.gnu.org/licenses/>.
==============================================================================
**/"""
TAG_ORDERDRAWING = 'jdipNS:ORDERDRAWING'
TAG_POWERCOLORS = 'jdipNS:POWERCOLORS'
TAG_POWERCOLOR = 'jdipNS:POWERCOLOR'
TAG_SYMBOLSIZE = 'jdipNS:SYMBOLSIZE'
TAG_PROVINCE_DATA = 'jdipNS:PROVINCE_DATA'
TAG_PROVINCE = 'jdipNS:PROVINCE'
TAG_UNIT = 'jdipNS:UNIT'
TAG_DISLODGED_UNIT = 'jdipNS:DISLODGED_UNIT'
TAG_SUPPLY_CENTER = 'jdipNS:SUPPLY_CENTER'
SELECTOR_REGEX = re.compile(r'([\r\n][ \t]*)([^{\r\n]+){')
LINES_REGEX = re.compile(r'[\r\n]+')
SPACES_REGEX = re.compile(r'[\t ]+')
STRING_REGEX = re.compile(r'[`\'"] {0,1}\+ {0,1}[`\'"]')
def prepend_css_selectors(prefix, css_text):
""" Prepend all CSS selector with given prefix (e.g. ID selector) followed by a space.
:param prefix: prefix to prepend
:param css_text: CSS text to parse
:rtype: str
"""
def repl(match):
return '%s%s %s{' % (match.group(1), prefix, match.group(2))
return SELECTOR_REGEX.sub(repl, css_text)
class ExtractedData:
""" Helper class to store extra data collected while parsing SVG file. Properties:
- name: class name of parsed SVG component
- extra: data parsed from invalid tags found in SVG content
- style_lines: string lines parsed from <style> tag if found in SVG content
- id_to_class: dictionary mapping and ID to corresponding class name
for each tag found with both ID and class name in SVG content.
"""
__slots__ = ('name', 'extra', 'style_lines', 'id_to_class')
def __init__(self, name):
""" Initialize extracted data object.
:param name: class name of parsed SVG content
"""
self.name = name
self.extra = {}
self.style_lines = []
self.id_to_class = {}
def get_coordinates(self):
""" Parse and return unit coordinates from extra field.
:return: a dictionary mapping a province name to coordinates [x, y] (as string values)
for unit ('unit'), dislodged unit ('disl'), and supply center ('sc', if available).
:rtype: dict
"""
coordinates = {}
for province_definition in self.extra[TAG_PROVINCE_DATA][TAG_PROVINCE]:
name = province_definition['name'].upper().replace('-', '/')
coordinates[name] = {}
if TAG_UNIT in province_definition:
coordinates[name]['unit'] = [
province_definition[TAG_UNIT]['x'], province_definition[TAG_UNIT]['y']]
if TAG_DISLODGED_UNIT in province_definition:
coordinates[name]['disl'] = [province_definition[TAG_DISLODGED_UNIT]['x'],
province_definition[TAG_DISLODGED_UNIT]['y']]
if TAG_SUPPLY_CENTER in province_definition:
coordinates[name]['sc'] = [province_definition[TAG_SUPPLY_CENTER]['x'],
province_definition[TAG_SUPPLY_CENTER]['y']]
return coordinates
def get_symbol_sizes(self):
""" Parse and return symbol sizes from extra field.
:return: a dictionary mapping a symbol name to sizes
('width' and 'height' as floating values).
:rtype: dict
"""
sizes = {}
for definition in self.extra[TAG_ORDERDRAWING][TAG_SYMBOLSIZE]:
sizes[definition['name']] = {
'width': float(definition['width']),
'height': float(definition['height'])
}
return sizes
def get_colors(self):
""" Parse and return power colors from extra field.
:return: a dictionary mapping a power name to a HTML color.
:rtype: dict
"""
colors = {}
for definition in self.extra[TAG_ORDERDRAWING][TAG_POWERCOLORS][TAG_POWERCOLOR]:
colors[definition['power'].upper()] = definition['color']
return colors
def safe_react_attribute_name(name):
""" Convert given raw attribute name into a valid React HTML tag attribute name.
:param name: attribute to convert
:return: valid attribute
:type name: str
:rtype: str
"""
# Replace 'class' with 'className'
if name == 'class':
return 'className'
# Replace aa-bb-cc with aaBbCc.
if '-' in name:
input_pieces = name.split('-')
output_pieces = [input_pieces[0]]
for piece in input_pieces[1:]:
output_pieces.append('%s%s' % (piece[0].upper(), piece[1:]))
return ''.join(output_pieces)
if name == 'xlink:href':
return 'href'
# Otherwise, return name as-is.
return name
def compact_extra(extra):
""" Compact extra dictionary so that it takes less place into final output string.
:param extra: dictionary of extra data
:type extra: dict
"""
# pylint:disable=too-many-branches
if 'children' in extra:
names = set()
text_found = False
for child in extra['children']:
if isinstance(child, str):
text_found = True
else:
names.add(child['name'])
if len(names) == len(extra['children']):
# Each child has a different name, so they cannot be confused,
# and extra dictionary can be merged with them.
children_dict = {}
for child in extra['children']:
child_name = child.pop('name')
compact_extra(child)
children_dict[child_name] = child
extra.pop('children')
extra.update(children_dict)
elif not text_found:
# Classify children by name.
classed = {}
for child in extra['children']:
classed.setdefault(child['name'], []).append(child)
# Remove extra['children']
extra.pop('children')
for name, children in classed.items():
if len(children) == 1:
# This child is the only one with that name. Merge it with extra dictionary.
child = children[0]
child.pop('name')
compact_extra(child)
extra[name] = child
else:
# We found many children with same name.
# Merge them as a list into extra dictionary.
values = []
for child in children:
child.pop('name')
compact_extra(child)
values.append(child)
extra[name] = values
else:
for child in extra['children']:
compact_extra(child)
if 'attributes' in extra:
if not extra['attributes']:
extra.pop('attributes')
elif 'name' not in extra or 'name' not in extra['attributes']:
# Dictionary can be merged with its 'attributes' field.
extra.update(extra.pop('attributes'))
def extract_extra(node, extra):
""" Collect extra information from given node into output extra.
:type extra: dict
"""
extra_dictionary = {'name': node.tagName, 'attributes': {}, 'children': []}
# Collect attributes.
for attribute_index in range(node.attributes.length):
attribute = node.attributes.item(attribute_index)
extra_dictionary['attributes'][attribute.name] = attribute.value
# Collect children lines.
for child in node.childNodes:
if child.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
# Child is a text.
text = child.data.strip()
if text:
extra_dictionary['children'].append(text)
elif child.nodeType != Node.COMMENT_NODE:
# Child is a normal node. We still consider it as an extra node.
extract_extra(child, extra_dictionary)
# Save extra node data into list field extra['children'].
extra.setdefault('children', []).append(extra_dictionary)
def attributes_to_string(attributes):
""" Convert given HTML attributes ton an inline string.
:param attributes: attributes to write
:return: a string representing attributes
:type attributes: dict
:rtype: str
"""
pieces = []
for name in sorted(attributes):
value = attributes[name]
if value.startswith('{'):
pieces.append('%s=%s' % (name, value))
else:
pieces.append('%s="%s"' % (name, value))
return ' '.join(pieces)
def extract_dom(node, nb_indentation, lines, data):
""" Parse given node.
:param node: (input) node to parse
:param nb_indentation: (input) number of indentation to use for current node content
into output lines. 1 indentation is converted to 4 spaces.
:param lines: (output) collector for output lines of text corresponding to parsed content
:param data: ExtractedData object to collect extracted data
(extra, style lines, ID-to-class mapping).
:type nb_indentation: int
:type lines: List[str]
:type data: ExtractedData
"""
# pylint: disable=too-many-branches, too-many-statements
if node.nodeType != Node.ELEMENT_NODE:
return
if ':' in node.tagName:
# Found unhandled tag (example: `<jdipNS:DISPLAY>`).
# Collect it (and all its descendants) into extra.
extract_extra(node, data.extra)
else:
# Found valid tag.
attributes = {}
child_lines = []
node_id = None
node_class = None
# Collect attributes.
for attribute_index in range(node.attributes.length):
attribute = node.attributes.item(attribute_index)
attribute_name = safe_react_attribute_name(attribute.name)
# Attributes "xmlns:*" are not handled by React. Skip them.
if not attribute_name.startswith('xmlns:') and attribute_name != 'version':
attributes[attribute_name] = attribute.value
if attribute_name == 'id':
node_id = attribute.value
elif attribute_name == 'className':
node_class = attribute.value
if node_id:
if node_class:
# We parameterize class name for this node.
attributes['className'] = "{classes['%s']}" % node_id
data.id_to_class[node_id] = node_class
if node.parentNode.getAttribute('id') == 'MouseLayer':
# This node must react to onClick and onMouseOver.
attributes['onClick'] = '{this.onClick}'
attributes['onMouseOver'] = '{this.onHover}'
# Collect children lines.
for child in node.childNodes:
if child.nodeType in (Node.TEXT_NODE, Node.CDATA_SECTION_NODE):
# Found a text node.
text = child.data.strip()
if text:
child_lines.append(text)
else:
# Found an element node.
extract_dom(child, nb_indentation + 1, child_lines, data)
if node.tagName == 'style':
# Found 'style' tag. Save its children lines into style lines and return immediately,
data.style_lines.extend(child_lines)
return
if node.tagName == 'svg':
if node_class:
attributes['className'] += ' %s' % data.name
else:
attributes['className'] = data.name
if node_id:
if not child_lines:
if node_id == 'Layer2':
child_lines.append('{renderedOrders2}')
elif node_id == 'Layer1':
child_lines.append('{renderedOrders}')
elif node_id == 'UnitLayer':
child_lines.append('{renderedUnits}')
elif node_id == 'DislodgedUnitLayer':
child_lines.append('{renderedDislodgedUnits}')
elif node_id == 'HighestOrderLayer':
child_lines.append('{renderedHighestOrders}')
elif node_id == 'CurrentNote':
child_lines.append("{nb_centers_per_power ? nb_centers_per_power : ''}")
elif node_id == 'CurrentNote2':
child_lines.append("{note ? note : ''}")
if (node_id == 'CurrentPhase'
and len(child_lines) == 1
and isinstance(child_lines[0], str)):
child_lines = ['{current_phase}']
# We have a normal element node (not style node). Convert it to output lines.
indentation = ' ' * (4 * nb_indentation)
attr_string = attributes_to_string(attributes)
if child_lines:
# Node must be written as an open tag.
if len(child_lines) == 1:
# If we just have 1 child line, write a compact line.
lines.append(
'%s<%s%s>%s</%s>' % (
indentation, node.tagName,
(' %s' % attr_string) if attr_string else '',
child_lines[0].lstrip(),
node.tagName))
else:
# Otherwise, write node normally.
lines.append(
'%s<%s%s>' % (indentation, node.tagName,
(' %s' % attr_string) if attr_string else ''))
lines.extend(child_lines)
lines.append('%s</%s>' % (indentation, node.tagName))
else:
# Node can be written as a close tag.
lines.append(
'%s<%s%s/>' % (
indentation, node.tagName, (' %s' % attr_string) if attr_string else ''))
def to_json_string(dictionary):
""" Converts to a JSON string, without escaping the '/' characters """
return json.dumps(dictionary).replace(r'\/', r'/')
def minify(code):
""" Minifyies a Javascript / CSS file """
code = LINES_REGEX.sub(' ', code)
code = SPACES_REGEX.sub(' ', code)
code = STRING_REGEX.sub(' ', code)
return code
def main():
""" Main script function. """
parser = argparse.ArgumentParser(
prog='Convert a SVG file to a React Component.'
)
parser.add_argument('--input', '-i', type=str, required=True, help='SVG file to convert.')
parser.add_argument('--name', '-n', type=str, required=True, help="Component name.")
parser.add_argument('--output', '-o', type=str, default=os.getcwd(),
help='Output folder (default to working folder).')
args = parser.parse_args()
root = minidom.parse(args.input).documentElement
class_name = args.name
output_folder = args.output
if not os.path.exists(output_folder):
os.makedirs(output_folder)
assert os.path.isdir(output_folder), 'Not a directory: %s' % output_folder
extra_class_name = '%sMetadata' % class_name
lines = []
data = ExtractedData(class_name)
extract_dom(root, 3, lines, data)
compact_extra(data.extra)
output_file_name = os.path.join(output_folder, '%s.js' % class_name)
style_file_name = os.path.join(output_folder, '%s.css' % class_name)
extra_parsed_file_name = os.path.join(output_folder, '%s.js' % extra_class_name)
# CSS
if data.style_lines:
with open(style_file_name, 'w') as style_file:
style_file.write(LICENSE_TEXT)
style_file.write('\n')
style_file.writelines(
minify(prepend_css_selectors('.%s' % class_name, '\n'.join(data.style_lines))))
# Metadata
if data.extra:
with open(extra_parsed_file_name, 'w') as extra_parsed_file:
extra_parsed_file.write("""%(license_text)s
export const Coordinates = %(coordinates)s;
export const SymbolSizes = %(symbol_sizes)s;
export const Colors = %(colors)s;
""" % {'license_text': LICENSE_TEXT,
'coordinates': to_json_string(data.get_coordinates()),
'symbol_sizes': to_json_string(data.get_symbol_sizes()),
'colors': to_json_string(data.get_colors())})
# Map javacript
map_js_code = ("""
import React from 'react';
import PropTypes from 'prop-types';
%(style_content)s
%(extra_content)s
import {getClickedID, parseLocation, setInfluence} from "../common/common";
import {Game} from "../../../diplomacy/engine/game";
import {MapData} from "../../utils/map_data";
import {UTILS} from "../../../diplomacy/utils/utils";
import {Diplog} from "../../../diplomacy/utils/diplog";
import {extendOrderBuilding} from "../../utils/order_building";
import {Unit} from "../common/unit";
import {Hold} from "../common/hold";
import {Move} from "../common/move";
import {SupportMove} from "../common/supportMove";
import {SupportHold} from "../common/supportHold";
import {Convoy} from "../common/convoy";
import {Build} from "../common/build";
import {Disband} from "../common/disband";
export class %(classname)s extends React.Component {
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this);
this.onHover = this.onHover.bind(this);
}
onClick(event) {
if (this.props.orderBuilding)
return this.handleClickedID(getClickedID(event));
}
onHover(event) {
return this.handleHoverID(getClickedID(event));
}
handleClickedID(id) {
const orderBuilding = this.props.orderBuilding;
if (!orderBuilding.builder)
return this.props.onError('No orderable locations.');
const province = this.props.mapData.getProvince(id);
if (!province)
throw new Error(`Cannot find a province named ${id}`);
const stepLength = orderBuilding.builder.steps.length;
if (orderBuilding.path.length >= stepLength)
throw new Error(`Order building: current steps count (${orderBuilding.path.length}) should be less than` +
` expected steps count (${stepLength}) (${orderBuilding.path.join(', ')}).`);
const lengthAfterClick = orderBuilding.path.length + 1;
let validLocations = [];
const testedPath = [orderBuilding.type].concat(orderBuilding.path);
const value = UTILS.javascript.getTreeValue(this.props.game.ordersTree, testedPath);
if (value !== null) {
const checker = orderBuilding.builder.steps[lengthAfterClick - 1];
try {
const possibleLocations = checker(province, orderBuilding.power);
for (let possibleLocation of possibleLocations) {
possibleLocation = possibleLocation.toUpperCase();
if (value.includes(possibleLocation))
validLocations.push(possibleLocation);
}
} catch (error) {
return this.props.onError(error);
}
}
if (!validLocations.length)
return this.props.onError('Disallowed.');
if (validLocations.length > 1 && orderBuilding.type === 'S' && orderBuilding.path.length >= 2) {
/* We are building a support order and we have a multiple choice for a location. */
/* Let's check if next location to choose is a coast. To have a coast: */
/* - all possible locations must start with same 3 characters. */
/* - we expect at least province name in possible locations (e.g. 'SPA' for 'SPA/NC'). */
/* If we have a coast, we will remove province name from possible locations. */
let isACoast = true;
let validLocationsNoProvinceName = [];
for (let i = 0; i < validLocations.length; ++i) {
let location = validLocations[i];
if (i > 0) {
/* Compare 3 first letters with previous location. */
if (validLocations[i - 1].substring(0, 3).toUpperCase() !== validLocations[i].substring(0, 3).toUpperCase()) {
/* No same prefix with previous location. We does not have a coast. */
isACoast = false;
break;
}
}
if (location.length !== 3)
validLocationsNoProvinceName.push(location);
}
if (validLocations.length === validLocationsNoProvinceName.length) {
/* We have not found province name. */
isACoast = false;
}
if (isACoast) {
/* We want to choose location in a coastal province. Let's remove province name. */
validLocations = validLocationsNoProvinceName;
}
}
if (validLocations.length > 1) {
if (this.props.onSelectLocation) {
return this.props.onSelectLocation(validLocations, orderBuilding.power, orderBuilding.type, orderBuilding.path);
} else {
Diplog.warn(`Forced to select first valid location.`);
validLocations = [validLocations[0]];
}
}
let orderBuildingType = orderBuilding.type;
if (lengthAfterClick === stepLength && orderBuildingType === 'M') {
const moveOrderPath = ['M'].concat(orderBuilding.path, validLocations[0]);
const moveTypes = UTILS.javascript.getTreeValue(this.props.game.ordersTree, moveOrderPath);
if (moveTypes !== null) {
if (moveTypes.length === 2 && this.props.onSelectVia) {
/* This move can be done either regularly or VIA a fleet. Let user choose. */
return this.props.onSelectVia(validLocations[0], orderBuilding.power, orderBuilding.path);
} else {
orderBuildingType = moveTypes[0];
}
}
}
extendOrderBuilding(
orderBuilding.power, orderBuildingType, orderBuilding.path, validLocations[0],
this.props.onOrderBuilding, this.props.onOrderBuilt, this.props.onError
);
}
handleHoverID(id) {
if (this.props.onHover) {
const province = this.props.mapData.getProvince(id);
if (province) {
this.props.onHover(province.name, this.getRelatedOrders(province.name));
}
}
}
getRelatedOrders(name) {
const orders = [];
if (this.props.orders) {
for (let powerOrders of Object.values(this.props.orders)) {
if (powerOrders) {
for (let order of powerOrders) {
const pieces = order.split(/ +/);
if (pieces[1].slice(0, 3) === name.toUpperCase().slice(0, 3))
orders.push(order);
}
}
}
}
return orders;
}
getNeighbors(extraLocation) {
const selectedPath = [this.props.orderBuilding.type].concat(this.props.orderBuilding.path);
if (extraLocation)
selectedPath.push(extraLocation);
const possibleNeighbors = UTILS.javascript.getTreeValue(this.props.game.ordersTree, selectedPath);
const neighbors = possibleNeighbors ? possibleNeighbors.map(neighbor => parseLocation(neighbor)) : [];
return neighbors.length ? neighbors: null;
}
render() {
const classes = %(classes)s;
const game = this.props.game;
const mapData = this.props.mapData;
const orders = this.props.orders;
/* Current phase. */
const current_phase = (game.phase[0] === '?' || game.phase === 'COMPLETED') ? 'FINAL' : game.phase;
/* Notes. */
const nb_centers = [];
for (let power of Object.values(game.powers)) {
if (!power.isEliminated())
nb_centers.push([power.name.substr(0, 3), power.centers.length]);
}
/* Sort nb_centers by descending number of centers. */
nb_centers.sort((a, b) => {
return -(a[1] - b[1]) || a[0].localeCompare(b[0]);
});
const nb_centers_per_power = nb_centers.map((couple) => (couple[0] + ': ' + couple[1])).join(' ');
const note = game.note;
/* Adding units, influence and orders. */
const renderedUnits = [];
const renderedDislodgedUnits = [];
const renderedOrders = [];
const renderedOrders2 = [];
const renderedHighestOrders = [];
for (let power of Object.values(game.powers)) if (!power.isEliminated()) {
for (let unit of power.units) {
renderedUnits.push(
<Unit key={unit}
unit={unit}
powerName={power.name}
isDislodged={false}
coordinates={Coordinates}
symbolSizes={SymbolSizes}/>
);
}
for (let unit of Object.keys(power.retreats)) {
renderedDislodgedUnits.push(
<Unit key={unit}
unit={unit}
powerName={power.name}
isDislodged={true}
coordinates={Coordinates}
symbolSizes={SymbolSizes}/>
);
}
for (let center of power.centers) {
setInfluence(classes, mapData, center, power.name);
}
for (let loc of power.influence) {
if (!mapData.supplyCenters.has(loc))
setInfluence(classes, mapData, loc, power.name);
}
if (orders) {
const powerOrders = (orders && orders.hasOwnProperty(power.name) && orders[power.name]) || [];
for (let order of powerOrders) {
const tokens = order.split(/ +/);
if (!tokens || tokens.length < 3)
continue;
const unit_loc = tokens[1];
if (tokens[2] === 'H') {
renderedOrders.push(
<Hold key={order}
loc={unit_loc}
powerName={power.name}
coordinates={Coordinates}
symbolSizes={SymbolSizes}
colors={Colors}/>
);
} else if (tokens[2] === '-') {
const destLoc = tokens[tokens.length - (tokens[tokens.length - 1] === 'VIA' ? 2 : 1)];
renderedOrders.push(
<Move key={order}
srcLoc={unit_loc}
dstLoc={destLoc}
powerName={power.name}
phaseType={game.getPhaseType()}
coordinates={Coordinates}
symbolSizes={SymbolSizes}
colors={Colors}/>
);
} else if (tokens[2] === 'S') {
const destLoc = tokens[tokens.length - 1];
if (tokens.includes('-')) {
const srcLoc = tokens[4];
renderedOrders2.push(
<SupportMove key={order}
loc={unit_loc}
srcLoc={srcLoc}
dstLoc={destLoc}
powerName={power.name}
coordinates={Coordinates}
symbolSizes={SymbolSizes}
colors={Colors}/>
);
} else {
renderedOrders2.push(
<SupportHold key={order}
loc={unit_loc}
dstLoc={destLoc}
powerName={power.name}
coordinates={Coordinates}
symbolSizes={SymbolSizes}
colors={Colors}/>
);
}
} else if (tokens[2] === 'C') {
const srcLoc = tokens[4];
const destLoc = tokens[tokens.length - 1];
if ((srcLoc !== destLoc) && (tokens.includes('-'))) {
renderedOrders2.push(
<Convoy key={order}
loc={unit_loc}
srcLoc={srcLoc}
dstLoc={destLoc}
powerName={power.name}
coordinates={Coordinates} colors={Colors}
symbolSizes={SymbolSizes}/>
);
}
} else if (tokens[2] === 'B') {
renderedHighestOrders.push(
<Build key={order}
unitType={tokens[0]}
loc={unit_loc}
powerName={power.name}
coordinates={Coordinates}
symbolSizes={SymbolSizes}/>
);
} else if (tokens[2] === 'D') {
renderedHighestOrders.push(
<Disband key={order}
loc={unit_loc}
phaseType={game.getPhaseType()}
coordinates={Coordinates}
symbolSizes={SymbolSizes}/>
);
} else if (tokens[2] === 'R') {
const destLoc = tokens[3];
renderedOrders.push(
<Move key={order}
srcLoc={unit_loc}
dstLoc={destLoc}
powerName={power.name}
phaseType={game.getPhaseType()}
coordinates={Coordinates}
symbolSizes={SymbolSizes}
colors={Colors}/>
);
} else {
throw new Error(`Unknown error to render (${order}).`);
}
}
}
}
if (this.props.orderBuilding && this.props.orderBuilding.path.length) {
const clicked = parseLocation(this.props.orderBuilding.path[0]);
const province = this.props.mapData.getProvince(clicked);
if (!province)
throw new Error(('Unknown clicked province ' + clicked));
const clickedID = province.getID(classes);
if (!clicked)
throw new Error(`Unknown path (${clickedID}) for province (${clicked}).`);
classes[clickedID] = 'provinceRed';
const neighbors = this.getNeighbors();
if (neighbors) {
for (let neighbor of neighbors) {
const neighborProvince = this.props.mapData.getProvince(neighbor);
if (!neighborProvince)
throw new Error('Unknown neighbor province ' + neighbor);
const neighborID = neighborProvince.getID(classes);
if (!neighborID)
throw new Error(`Unknown neoghbor path (${neighborID}) for province (${neighbor}).`);
classes[neighborID] = neighborProvince.isWater() ? 'provinceBlue' : 'provinceGreen';
}
}
}
if (this.props.showAbbreviations === false) {
classes['BriefLabelLayer'] = 'visibilityHidden';
}
return (
%(svg)s
);
}
}
%(classname)s.propTypes = {
game: PropTypes.instanceOf(Game).isRequired,
mapData: PropTypes.instanceOf(MapData).isRequired,
orders: PropTypes.object,
onHover: PropTypes.func,
onError: PropTypes.func.isRequired,
onSelectLocation: PropTypes.func,
onSelectVia: PropTypes.func,
onOrderBuilding: PropTypes.func,
onOrderBuilt: PropTypes.func,
orderBuilding: PropTypes.object,
showAbbreviations: PropTypes.bool
};
""" % {'style_content': "import './%s.css';" % class_name if data.style_lines else '',
'extra_content': 'import {Coordinates, SymbolSizes, Colors} from "./%s";' %
(extra_class_name) if data.extra else '',
'classname': class_name,
'classes': to_json_string(data.id_to_class),
'svg': '\n'.join(lines)})
# Adding license and minifying
map_js_code = LICENSE_TEXT \
+ '\n/** Generated with parameters: %s **/\n' % args \
+ minify(map_js_code) \
+ '// eslint-disable-line semi'
# Writing to disk
with open(output_file_name, 'w') as file:
file.write(map_js_code)
if __name__ == '__main__':
main()
|