-
Notifications
You must be signed in to change notification settings - Fork 43
/
CypherPokerUI.js
2574 lines (2489 loc) · 108 KB
/
CypherPokerUI.js
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
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file Basic user interface management for CypherPoker.JS.
*
* @version 0.5.1
* @author Patrick Bay
* @copyright MIT License
*/
/**
* @class Basic user interface management for CypherPoker.JS
*/
class CypherPokerUI {
/**
* @property {Object} UISelectors Name/value pairs for general UI elements and their
* associated CSS-style DOM selectors.
* @property {String} UISelectors.dialog="#mainDialog" The main or primary dialog element.
* @property {String} UISelectors.accounts="#accounts" The main accounts container element.
* @property {String} UISelectors.accountLoginForm="#accounts>#loginForm" The main account login container element.
* @property {String} UISelectors.accountManageForm="#accounts>#manageForm" The main account management container element.
* @property {String} UISelectors.accountCreateForm="#accounts>#createAccountForm" The main account creation container element.
* @property {String} UISelectors.clipboardData="#clipboardData" Proxy data container for global clipboard copy commands.
* @property {String} UISelectors.lobby="#lobby" The main lobby container element.
*/
get UISelectors() {
return({
"dialog":"#mainDialog",
"dialogMessage":"#mainDialog > #message",
"accounts":"#accounts",
"accountLoginForm": "#accounts > #loginForm",
"accountManageForm": "#accounts > #manageForm",
"accountCreateForm": "#accounts > #createAccountForm",
"clipboardData":"#clipboardData",
"lobby":"#lobby"
});
}
/**
* @property {Object} gameUISelectors Name/value pairs for game UI elements and their
* associated CSS-style DOM selectors. Note that these selectors are relative to/children of
* each game element cloned from the {@link CypherPokerUI#protoGameElement}.
* @property {String} gameUISelectors.betButton="#betButton" The game's bet button.
* @property {String} gameUISelectors.foldButton="#foldButton" The game's fold button.
* @property {String} gameUISelectors.newHandButton="#newHandButton" The game's new hand button.
* @property {String} gameUISelectors.totalBet="#totalBet" The game's total bet amount display element.
* @property {String} gameUISelectors.balance="#balance" The remaining game balance amount display element.
* @property {String} gameUISelectors.potAmount="#potAmount" The game's pot amount input element.
* @property {String} gameUISelectors.betAmount="#betAmount" The game's bet amount input element.
* @property {String} gameUISelectors.publicCards="#publicCards" The game's public cards container element.
* @property {String} gameUISelectors.privateCards="#privateCards" The game's private cards container element.
* @property {String} gameUISelectors.timeoutAmount="#timeoutAmount" The game's timeout counter container element.
*/
get gameUISelectors() {
return({
"betButton":"#betButton",
"foldButton":"#foldButton",
"newHandButton":"#newHandButton",
"totalBet":"#totalBet",
"balance":"#balance",
"potAmount":"#potAmount",
"betAmount":"#betAmount",
"timeoutAmount":"#timeoutAmount",
"publicCards":"#publicCards",
"privateCards":"#privateCards",
"handHistory":"#handHistory"
});
}
/**
* Creates a new instance.
*
* @param {HTMLElement} protoElement A reference to the prototype element that will
* be cloned for use with each new game instance. The original element will
* remain unchanged (it should be hidden by default).
*/
constructor(protoElement) {
this._protoGameElement = protoElement;
this.lobbyActive = false;
window.__closing = false;
}
/**
* Intializes the UI by loading defined templates and setting
* the [ready]{@link CypherPokerUI#ready} flag to <code>true</code>.
*
* @async
*/
async initialize() {
var complete = await this.loadTemplates();
window.addEventListener("beforeunload", this.onWindowClose);
window.addEventListener("click", this.onWindowClick);
this._ready = true;
}
/**
* @property {Boolean} ready=false Becomes true when the UI has completed loading and initializing
* all data such as templates, configurations, etc.
* @readonly
*/
get ready() {
if (this._ready == undefined) {
this._ready = false;
}
return (this._ready);
}
/**
* @property {Boolean} lobbyActive=false True if the lobby interface is currently displayed and
* enabled, otherwise false. Setting this value to true enables automatic table culling in the lobby.
*/
get lobbyActive() {
return (this._lobbyActive);
}
set lobbyActive(activeSet) {
if ((activeSet == true) && (this._lobbyActive == false)) {
this.startLobbyCull();
}
if ((activeSet == false) && (this._lobbyActive == true)) {
this.stopLobbyCull();
}
this._lobbyActive = activeSet;
}
/**
* Starts the lobby table culling timer to remove inactive / invalid tables.
*/
startLobbyCull() {
this._lobbyCullTimer = setInterval(this.onLobbyCullTick, 3000, this);
}
/**
* Stops the lobby table culling timer if active.
*/
stopLobbyCull() {
try {
clearInterval(this._lobbyCullTimer);
this._lobbyCullTimer = null;
} catch (err) {
}
}
/**
* Timer function invoked to cull (remove) any inactive or unavailable tables appearing
* in the lobby.
*
* @private
*/
onLobbyCullTick(ui) {
for (var count=0; count<ui.cypherpoker.announcedTables.length; count++) {
var currentTable = ui.cypherpoker.announcedTables[count];
var tableInfo = currentTable.tableInfo;
var announceTimeout = Number(ui.cypherpoker.settings.lobbyDefaults.announceTimeout) * 1000; //seconds to milliseconds
var nowDate = new Date();
var tableDate = new Date(tableInfo.announcedAt);
var delta = nowDate.valueOf() - tableDate.valueOf();
if (delta >= announceTimeout) {
try {
tableInfo.buttonElement.removeEventListener("click", ui.onJoinTableButtonClick);
tableInfo.buttonElement.remove();
} catch (err) {}
ui.cypherpoker.removeTable(currentTable, true);
}
}
}
/**
* @property {Boolean} autoDeal=true If true, cards are automatically dealt when
* betting is done and it's our turn to deal. If <code>false</code>, the
* [CypherPokerGame.dealCards]{@link CypherPokerGame#dealCards} function of the
* [game]{@link CypherPokerUI#game} reference will need to be invoked manually.
*/
get autoDeal() {
if (this._autoDeal == undefined) {
this._autoDeal = true;
}
return (this._autoDeal);
}
set autoDeal(adSet) {
this._autoDeal = adSet;
}
/**
* @property {CypherPokerAccount} selectedAccount=null The currently selected
* {@link CypherPokerAccount} instance to use when creating or joining games.
* Note that once created, a {@link CypherPokerGame#account} reference may be different
* than this one.
*/
get selectedAccount() {
if (this._selectedAccount == undefined) {
this._selectedAccount = null;
}
return (this._selectedAccount);
}
set selectedAccount(accountSet) {
this._selectedAccount = accountSet;
}
/**
* @property {Array} gameElements An indexed array of all game container elements
* cloned from the [protoGameElement]{@link CypherPokerUI#protoGameElement} object.
*/
get gameElements() {
if (this._gameElements == undefined) {
this._gameElements = new Array();
}
return (this._gameElements);
}
/**
* @property {HTMLElement} protoGameElement A reference to the prototype element in which
* the game user interface is contained, as set at instantiation time. This element will be
* cloned for each new game instance.
* @readonly
*/
get protoGameElement() {
return (this._protoGameElement);
}
/**
* @property {CypherPoker} cypherpoker A reference to the main {@link CypherPoker} instance.
* This property may only be set once. When set, a number of event listeners are
* added to the instance so that the user interface can respond to them.
*/
set cypherpoker(cpSet) {
if ((this._cypherpoker == undefined) || (this._cypherpoker == null)) {
this._cypherpoker = cpSet;
this.addCypherPokerHandlers();
if (this._cypherpoker.apiConnected) {
var msg = "Connected to API services provider.<br/>";
if (this._cypherpoker.p2pConnected) {
msg += "Connected to peer-to-peer network.";
} else {
msg += "Connection to peer-to-peer network not established.";
}
this.showDialog(msg);
this.hideDialog(5000);
this.updateAccountsUI();
} else {
this._cypherpoker.addEventListener("start", event => {
if (this._cypherpoker.apiConnected) {
var msg = "Connected to API services provider.<br/>";
} else {
msg = "Connection to API services provider not established.<br/>";
}
if (this._cypherpoker.p2pConnected) {
msg += "Connected to peer-to-peer network.";
} else {
msg += "Connection to peer-to-peer network not established.";
}
this.showDialog(msg);
this.hideDialog(5000);
this.updateAccountsUI();
}, this);
}
} else {
throw (new Error("The \"cypherpoker\" reference can only be set once."));
}
}
get cypherpoker() {
if (this._cypherpoker == undefined) {
return (null);
}
return (this._cypherpoker);
}
/**
* @property {Array} templates The indexed list of sucecssfully loaded, parsed,
* and appended HTML templates as specified in the templates index JSON data.
* In addition to containing a copy of that data, each element in the array also
* contains a <code>document</code> property containing the original <code>HTMLDocument</code>
* object of the template and a <code>elements</code> array which contains references
* appended element(s), copied from the <code>document</code> within the main index HTML.
*/
get templates() {
if (this._templates == undefined) {
this._templates = new Array();
}
return (this._templates);
}
/**
* Returns a successfully loaded HTML template by its name from the
* [templates]{@link CypherPokerUI#templates} array.
*
* @param {String} name The HTML template name to reterieve, as specified in the associated
* templates JSON data.
*
* @return {Object} The object containing data and references matching the specified template,
* or <code>null</code> if no matching template can be found.
*/
getTemplateByName(name) {
for (var count=0; count < this.templates.length; count++) {
if (this.templates[count].name == name) {
return (this.templates[count]);
}
}
return (null);
}
/**
* Clones an HTML element, appends it to the DOM after the source element, and
* sets an internal reference to the clone in the source. Use this function
* to create copies of a dynamic template element that may change multiple times.
*
* @param {HTMLElement} sourceElement The HTML element to clone. This element
* will have an internal <code>_clone</code> reference to the cloned element.
* @param {Boolean} [internalReference=true] If true, the <code>sourceElement</code>
* will store a refence to the new clonet within itself as a <code>_clone</code>
* property so that it can be removed using {@link removeClone}.
*
* @return {HTMLElement} The cloned HTML element.
*/
cloneElement(sourceElement, internalReference=true) {
var clone = sourceElement.cloneNode(true);
if (internalReference == true) {
sourceElement._clone = clone;
}
sourceElement.parentNode.appendChild(clone);
return (clone);
}
/**
* Removes a cloned HTML element created by {@link cloneElement} with
* <code>internalReference=true</code>.
*
* @param {HTMLElement} sourceElement The soucre HTML element from which the
* clone was created. This element must have an internal <code>_clone</code>
* property.
*
* @return {Boolean} True if the cloned element could be properly removed.
*/
removeClone(sourceElement) {
if ((sourceElement["_clone"] == undefined) || (sourceElement["_clone"] == null)) {
return (false);
}
sourceElement.parentNode.removeChild(sourceElement._clone);
sourceElement._clone = null;
delete sourceElement._clone;
return (true);
}
/**
* Loads and parses HTML templates for the application, then adds them to their
* specified targets within the main page HTML. Every successfully loaded template
* can be accessed via the [templates]{@link CypherPokerUI#templates} array or the
* [getTemplate]{@link CypherPokerUI#getTemplate} function.
*
* Note that templates are appended to their specified targets in the order listed.
*
* @param {String} [indexURL="./templates/index.json"] The URL of the JSON file containing
* the list of templates to load.
*
* @async
*/
async loadTemplates(indexURL="./templates/index.json") {
this.debug("CypherPokerUI: Loading HTML templates...");
var promise = await loadJSON(indexURL).onEventPromise("load");
var templatesData = promise.target.response;
for (var count=0; count < templatesData.length; count++) {
var templateInfo = templatesData[count];
templateInfo.document = await this.loadHTMLTemplate(templateInfo.url);
templateInfo.sourceHTML = templateInfo.document.body.innerHTML
this.templates.push(templateInfo);
if (templateInfo.append == true) {
var target = document.querySelector(templateInfo.target);
this.cloneHTMLTemplate(templateInfo, target, templateInfo.hidden);
}
}
return (true);
}
/**
* Clones a specified HTML template, processes any meta tags, and appends it to a
* specified target. A reference to the clone is appended to the template information
* objects's internal <code>elements</code> array.
*
* @param {Object} templateInfo An object containing information about the template to generate.
* @param {HTMLElement} target The target element to append the generated template to as a child.
* @param {Boolean} [hidden=false] If true, the generated element is initially hidden.
* @param {Object} [metaData=null] Name-value pairs containing the data to replace in the
* document body. Each name is automatically surrounded by "%"; for example,
* <code>metaData["version"]="0.3.0"</code> replaces any <code>%version%</code> metatag
* in the document with <code>0.3.0</code>.
*
* @return {HTMLElement} The cloned, processed, and appended HTML template element.
*
* @private
*/
cloneHTMLTemplate(templateInfo, target, hidden=false, metaData=null) {
//assume document only has <head> (firstChild) and <body> (lastChild) tags within a <html> (documentElement) tag
var bodyNode = templateInfo.document.documentElement.lastChild;
if (templateInfo.elements == undefined) {
templateInfo.elements = new Array();
}
var nodeCopy = document.importNode(bodyNode.firstChild, true);
if (metaData != null) {
this.parseHTMLTemplateTags(nodeCopy, metaData);
}
var newChild = target.appendChild(nodeCopy);
templateInfo.elements.push(newChild);
if (hidden == true) {
this.hide(templateInfo.elements[templateInfo.elements.length-1]);
}
return (templateInfo.elements[templateInfo.elements.length-1]);
}
/**
* Builds a HTML template using a supplied template information object.
* Like {@link cloneHTMLTemplate} the template is cloned and any contained metatags
* are parsed but unlike {@link cloneHTMLTemplate} the template is destructively
* appended to the container specified in the template info (i.e. any children in
* the container are removed), and no reference is added to a internal <code>elements</code>
* array of the template information object.
*
* @param {Object} templateInfo An object containing information about the template to build.
* @param {Object} [metaData=null] Name-value pairs containing the data to replace in the
* document body. Each name is automatically surrounded by "%"; for example,
* <code>metaData["version"]="0.3.0"</code> replaces any <code>%version%</code> metatag
* in the document with <code>0.3.0</code>.
*
* @return {HTMLElement} The cloned, parsed, and appended HTML element.
*
* @private
*/
buildHTMLTemplate(templateInfo, metaData=null) {
//assume document only has <head> (firstChild) and <body> (lastChild) tags within a <html> (documentElement) tag
var bodyNode = templateInfo.document.documentElement.lastChild;
var target = document.querySelector(templateInfo.target);
var nodeCopy = document.importNode(bodyNode.firstChild, true);
if (metaData != null) {
this.parseHTMLTemplateTags(nodeCopy, metaData);
}
target.innerHTML = ""; //remove all children
var newChild = target.appendChild(nodeCopy);
return (newChild);
}
/**
* Loads and parses an external HTML template file using XMLHTTPRequest.
*
* @param {String} htmlURL The URL of the HTML template file to load.
* @return {HTMLDocument} A HTMLDocument object containing the loaded HTML
* document. Any meta tags found in the main body are automatically parsed
* using the [parseTemplateTags]{@link CypherPokerUI#parseTemplateTags} function.
*
* @private
* @async
*/
async loadHTMLTemplate(htmlURL) {
var xhr = new XMLHttpRequest();
if (_useCache == false) {
//force new data load
htmlURL = htmlURL + "?" + String(Math.random()).split("0.")[1];
}
xhr.open("GET", htmlURL);
xhr.responseType = "document";
xhr.send();
var promise = await xhr.onEventPromise("load");
if (promise.target.response != null) {
return (promise.target.response);
} else {
throw (new Error(`Couldn't load HTML template: (${htmlURL})`));
}
}
/**
* Parses/replaces any meta tags found in a HTML element.
*
* @param {HTMLElement} The element in which to search/replace metatags.
* @param {Object} metaData Name-value pairs containing the data to replace in the
* document body. Each name is automatically surrounded by "%"; for example,
* <code>metaData["version"]="0.3.0"</code> replaces any <code>%version%</code> metatag
* in the document with <code>0.3.0</code>.
*
* @private
*/
parseHTMLTemplateTags(element, metaData) {
var html = element.innerHTML;
for (var tag in metaData) {
html = html.split("%"+tag+"%").join(metaData[tag]);
}
element.innerHTML = html; //copy back to document body
}
/**
* Returns all of the selected radio button or checkbox elements contained in a specified
* container.
*
* @param {HTMLElement} containerElement The container element that contains
* the radio button or checkbox <code><input></code> nodes to check.
*
* @return {Array} Indexed list of all selected / checked radio buttons or checkboxes
* (<code>HTMLElement</code> objects). Note that radio buttons with the same
* <code>name</code> property are treated by the browser as a group and
* will only allow one selection among them.
*/
getGroupSelections(containerElement) {
var radioButtons = containerElement.querySelectorAll("input");
var returnButtons = new Array();
for (var count=0; count < radioButtons.length; count++) {
var radioButton = radioButtons[count];
if (radioButton.checked) {
returnButtons.push(radioButton);
}
}
return (returnButtons);
}
/**
* Adds game event listeners and callbacks to user interface elements defined in
* [gameUISelectors]{@link CypherPokerUI#gameUISelectors} and contained in a clone of the
* [protoGameElement]{@link CypherPokerUI#protoGameElement} element.
*
* @param {HTMLElement} gameElement The cloned game element to which to add handlers to.
* @param {CypherPokerGame} gameRef A reference to the game instance associated with the
* game element.
*/
addGameUIHandlers(gameElement, gameRef) {
//add references to game and this instance to all game elements
for (var item in this.gameUISelectors) {
try {
let element = gameElement.querySelector(this.gameUISelectors[item]);
element.game = gameRef;
element.ui = this;
} catch (err) {
}
}
//each of the following has a "game" and "ui" reference added to it
var betButton = gameElement.querySelector(this.gameUISelectors.betButton);
var foldButton = gameElement.querySelector(this.gameUISelectors.foldButton);
var newHandButton = gameElement.querySelector(this.gameUISelectors.newHandButton);
//element-scoped event listeners
betButton.addEventListener("click", this.onBetButtonClick);
foldButton.addEventListener("click", this.onFoldButtonClick);
newHandButton.addEventListener("click", this.onNewHandButtonClick);
//this-scoped event listeners
gameRef.addEventListener("gamedeal", this.onCardDeal, this);
gameRef.addEventListener("gamebet", this.onBetPlaced, this);
gameRef.addEventListener("gameend", this.onGameEnd, this);
gameRef.addEventListener("gamescored", this.onGameScored, this);
this.disable(betButton);
}
/**
* Event listener invoked when the containing window is about to be closed or
* refreshed. A dialog box with a warning is displayed to the user if a game is
* currently active.
*
* @param {Event} event A standard DOM event object.
*
* @private
*/
onWindowClose(event) {
for (var count=0; count < this.ui.cypherpoker.games.length; count++) {
if (this.ui.cypherpoker.games[count].gameStarted) {
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
//unfortunately custom leave messages are no longer supported by most browsers
event.returnValue = null;
return (null);
}
}
}
/**
* Starts the timeout timer for a specific game instance.
*
* @param {HTMLElement} timeoutElement The element containing the timeout
* time display.
* @param {Number} timeoutAmount The timeout amount, in seconds, to track.
* @param {CypherPokerGame} game The game instance for which to track
* the timeout (in the UI).
*
* @private
*/
startTimeoutTimer(timeoutElement, timeoutAmount, game) {
this.stopTimeoutTimer(timeoutElement);
var now = new Date();
//or Date.now()...
timeoutElement._startTime = now.valueOf();
timeoutElement._timeoutID = setTimeout(this.onTimeoutTimerTick, 1000, timeoutElement, timeoutAmount, game, this);
}
/**
* Stops the timeout timer started by {@link CypherPokerUI@startTimeoutTimer}.
*
* @param {HTMLElement} timeoutElement The element containing the timer
* time display.
*
* @private
*/
stopTimeoutTimer(timeoutElement) {
try {
//stop any existing timers
clearTimeout(timeoutElement._timeoutID);
} catch (err){}
}
/**
* Timer function invoked on every tick of the timeout timer for a specific game.
*
* @param {HTMLElement} timeoutElement The element containing the timer time
* display.
* @param {Number} timeoutAmount The timeout amount, in seconds, being tracked.
* @param {CypherPokerGame} game The game instance for which the timer is active.
* @param {CypherPokerUI} ui The UI handler to be used to update the <code>timeoutElement</code>.
*
* @private
*/
onTimeoutTimerTick(timeoutElement, timeoutAmount, game, ui) {
var now = new Date();
//use system timestamp to determine number of elapsed seconds rather than imprecise timer
var secondsElapsed = Math.floor((now.valueOf() - timeoutElement._startTime) / 1000);
var secondsRemaining = timeoutAmount - secondsElapsed;
if (secondsRemaining < 0) {
secondsRemaining = 0;
}
if (secondsRemaining > 0) {
var timeoutHours = Math.floor(secondsRemaining / 3600);
var timeoutMinutes = Math.floor(secondsRemaining / 60) % 60;
var timeoutSeconds = secondsRemaining % 60;
var timeStr = String(timeoutHours) + ":";
if (timeoutMinutes < 10) {
timeStr += "0";
}
timeStr += String(timeoutMinutes) + ":";
if (timeoutSeconds < 10) {
timeStr += "0";
}
timeStr += String(timeoutSeconds);
if (secondsRemaining <= 5) {
timeoutElement.innerHTML = "<span id=\"timeoutCritical\">" + timeStr + "</span>";
} else {
timeoutElement.innerHTML = "<span id=\"timeout\">" + timeStr + "</span>";
}
timeoutElement._timeoutID = setTimeout(ui.onTimeoutTimerTick, 1000, timeoutElement, timeoutAmount, game, ui);
} else {
//contract has timed out
timeStr = "0:00:00";
timeoutElement.innerHTML = "<span id=\"timeoutCritical\">" + timeStr + "</span>";
ui.disableGameUI.call(ui, game);
ui.showDialog("A player has timed out. Awaiting confirmation from contract...");
}
}
/**
* Adds event listeners and callbacks to the {@link CypherPoker} instance assigned to
* the [cypherpoker]{@link CypherPokerUI#cypherpoker} property.
*/
addCypherPokerHandlers() {
this.cypherpoker.addEventListener("newgame", this.onNewGame, this);
this.cypherpoker.addEventListener("tablenew", this.onNewTableAnnouncement, this);
this.cypherpoker.captureNewTables = true;
}
/**
* Invoked when a dropdown button is clicked to toggle an associated menu.
*
* @param {String} dropdownSelector The dropdown menu selector to toggle.
*
* @private
*/
toggleDropdown(dropdownSelector) {
var element = document.querySelector(dropdownSelector);
element.classList.toggle("showDropdownMenu");
}
/**
* Event listener invoked when the main window is clicked. This triggers
* functionality such as hiding any currently open dropdowns.
*
* @param {Event} event A standard DOM event object.
*
* @private
*/
onWindowClick(event) {
//only trigger if target isn't a dropdown menu toggle button
if (event.target.matches(".dropdownMenuButton") == false) {
var dropdowns = document.querySelectorAll(".dropdownMenuContent");
for (var count = 0; count < dropdowns.length; count++) {
var openDropdown = dropdowns[count];
if (openDropdown.classList.contains('showDropdownMenu')) {
openDropdown.classList.remove('showDropdownMenu');
}
}
}
}
/**
* Invoked when a main menu option is clicked on.
*
* @param {String} selection The identifier of the main menu option that was
* just clicked on.
*
* @private
*/
onMainMenuClick(selection) {
switch (selection) {
case "newWindow":
if (isDesktop()) {
var requestData = new Object();
var result = IPCSend("new-window", requestData)
} else {
try {
var windowName = "CypherPoker.JS-"+String(Math.random()).split("0.")[1];
var windowURL = document.location; //use current full URL
var windowFeatures = ""; //use default window features
var window = document.open(windowURL, windowName, windowFeatures);
} catch (err) {
alert (err.stack);
}
}
break;
case "manageConnections":
var manageElement = this.getTemplateByName("connectivityManage").elements[0];
cypherpoker.connectivityManager.populateConnectionsList("api");
cypherpoker.connectivityManager.populateAPIConnectionInputs();
cypherpoker.connectivityManager.populateConnectionsList("p2p");
cypherpoker.connectivityManager.populateP2PConnectionInputs();
var serverTableElement = manageElement.querySelector("#serverTableDivider");
if (isDesktop()) {
this.show(serverTableElement);
cypherpoker.connectivityManager.populateGatewaysList();
} else {
this.hide(serverTableElement);
}
this.toggleShow(manageElement);
break;
case "manageAccount":
if (this.selectedAccount == null) {
if (this.cypherpoker.apiConnected == false) {
var msg = "You must connect to an API services provider in order to manage accounts";
} else {
msg = "You must login to the account (\"USE ACCOUNT\") you want to manage."
}
this.showDialog (msg);
this.hideDialog(5000);
return;
}
var manageElement = this.getTemplateByName("accountManage").elements[0];
var loginElement = this.getTemplateByName("accountLogin").elements[0];
var minerFeeInput = manageElement.querySelector("#minerFee");
if (this.isHidden(manageElement) == true) {
this.show(manageElement);
} else {
this.hide(manageElement);
}
manageElement.querySelector("#accountBalance").innerHTML = "updating...";
loginElement.querySelector("#accountBalance").innerHTML = "updating...";
this.selectedAccount.update().then(done => {
var satoshiAmount = this.selectedAccount.balance.toString(10);
var btcAmount = this.convertDenom(satoshiAmount, "satoshi", "bitcoin");
manageElement.querySelector("#accountBalance").innerHTML = satoshiAmount+ " satoshis";
loginElement.querySelector("#accountBalance").innerHTML = satoshiAmount+ " satoshis";
minerFeeInput.value = this.selectedAccount.fees.cashout;
this.cypherpoker.saveAccounts();
}).catch(error => {
manageElement.querySelector("#accountBalance").innerHTML = "unavailable";
loginElement.querySelector("#accountBalance").innerHTML = "unavailable";
console.error(error);
this.showDialog(error.message);
this.hideDialog(4000);
});
break;
case "gameLobby":
if (this.cypherpoker.apiConnected == false) {
var msg = "You must connect to an API services provider<br/>";
msg += "in order to access to the lobby.";
this.showDialog(msg);
this.hideDialog(5000);
return;
}
if (this.lobbyActive) {
var confirmElement = this.getTemplateByName("lobbyConfirm").elements[0];
this.hide(confirmElement.querySelector("#gameActive"));
this.show(confirmElement.querySelector("#lobbyActive"));
this.show(confirmElement);
this.showDialog();
return;
} else {
for (var count=0; count < this.cypherpoker.games.length; count++) {
var currentGame = this.cypherpoker.games[count];
if ((currentGame.gameStarted == true) || (currentGame.gameEnding == true)) {
confirmElement = this.getTemplateByName("lobbyConfirm").elements[0];
this.hide(confirmElement.querySelector("#lobbyActive"));
this.show(confirmElement.querySelector("#gameActive"));
this.show(confirmElement);
this.showDialog();
return;
}
}
}
if (this.selectedAccount == null) {
this.showDialog("You must login to an account (\"USE ACCOUNT\") with a balance in order to access the lobby.");
this.hideDialog(5000);
} else {
//lobby is not active or game has ended
this.cypherpoker.removeAllGames(true); //remove any completed games
var lobbyContainer = document.querySelector(ui.UISelectors.lobby);
this.show(lobbyContainer);
this.resetLobbyUI(true);
this.lobbyActive = true;
this.cypherpoker.captureNewTables = true;
this.startLobbyCull();
}
break;
case "logOut":
var confirmElement = this.getTemplateByName("logOutConfirm").elements[0];
if (this.lobbyActive) {
this.hide(confirmElement.querySelector("#gameActive"));
this.hide(confirmElement.querySelector("#standard"));
this.show(confirmElement.querySelector("#lobbyActive"));
this.show(confirmElement);
this.showDialog();
return;
} else {
for (var count=0; count < this.cypherpoker.games.length; count++) {
var currentGame = this.cypherpoker.games[count];
if ((currentGame.gameStarted == true) || (currentGame.gameEnding == true)) {
this.show(confirmElement.querySelector("#gameActive"));
this.hide(confirmElement.querySelector("#standard"));
this.hide(confirmElement.querySelector("#lobbyActive"));
this.show(confirmElement);
this.showDialog();
return;
}
}
}
//neither lobby or game are currently active
this.hide(confirmElement.querySelector("#gameActive"));
this.show(confirmElement.querySelector("#standard"));
this.hide(confirmElement.querySelector("#lobbyActive"));
this.show(confirmElement);
this.showDialog();
break;
case "about":
if (isDesktop()) {
var runtime = "desktop";
var dbInfoObj = IPCSend("database-info");
var databaseInfo = "";
for (var db in dbInfoObj) {
var currentDBInfo = dbInfoObj[db];
//info object may also contain a function reference
if (typeof(currentDBInfo) == "object") {
databaseInfo += currentDBInfo.version + " ("+currentDBInfo.dbSizeMB+" MB of "+currentDBInfo.dbMaxMB+" MB)<br/>";
}
}
} else {
runtime = "web";
databaseInfo = "";
}
var element = this.getTemplateByName("help").elements[0];
var helpElement = element.querySelector("#about");
helpElement.innerHTML = helpElement.innerHTML.split("%appTitle%").join(appTitle);
helpElement.innerHTML = helpElement.innerHTML.split("%runtime%").join(runtime);
helpElement.innerHTML = helpElement.innerHTML.split("%runtimeDetails%").join(platform.description);
helpElement.innerHTML = helpElement.innerHTML.split("%databaseInfo%").join(databaseInfo);
this.show(helpElement);
this.showDialog();
break
default:
break;
}
}
/**
* Invoked by the confirmation dialog opened by the main menu's "Game Lobby" option.
*
* @param {Boolean} confirm If true, the user has confirmed that they wish to take the desired
* action (open the game lobby), and accept the consequences. If false, the currently opened
* dialog is closed.
* @private
* @async
*/
async onOpenLobbyButtonClick(confirm) {
var confirmElement = this.getTemplateByName("lobbyConfirm").elements[0];
this.hide(confirmElement.querySelector("#lobbyActive"));
this.hide(confirmElement.querySelector("#gameActive"));
this.hide(confirmElement);
this.hideDialog();
if (confirm == true) {
//player has confirmed that they want to return to lobby
if (this.lobbyActive) {
//lobby is active
this.cypherpoker.removeAllTables(true, true);
} else {
//game(s) is active
this.cypherpoker.removeAllGames(true);
}
var lobbyContainer = document.querySelector(ui.UISelectors.lobby);
this.show(lobbyContainer);
this.resetLobbyUI(true);
this.lobbyActive = true;
this.cypherpoker.captureNewTables = true;
this.startLobbyCull();
} else {
//nothing to do
}
}
/**
* Invoked by the post-cashout dialog when the "Okay" button is clicked.
*
* @private
* @async
*/
async onPostCashoutOkayClick() {
var postCashoutElement = this.getTemplateByName("postCashout").elements[0];
this.removeClone(postCashoutElement);
this.hideDialog();
}
/**
* Invoked by the confirmation dialog opened by the main menu's "Log Out" option.
*
* @param {Boolean} confirm If true, the user has confirmed that they wish to take the desired
* action (log out), and accept the consequences. If false, the currently opened dialog is closed.
* @private
* @async
*/
async onLogOutButtonClick(confirm) {
var confirmElement = this.getTemplateByName("logOutConfirm").elements[0];
this.hide(confirmElement.querySelector("#lobbyActive"));
this.hide(confirmElement.querySelector("#gameActive"));
this.hide(confirmElement.querySelector("#gameAPIChange"));
this.hide(confirmElement.querySelector("#standard"));
this.hide(confirmElement);
this.hideDialog();
if (confirm == true) {
//prevent refresh notification since we've already asked for confirmation
window.removeEventListener("beforeunload", this.onWindowClose);
location.reload();
}
}
/**
* Event listener invoked when an account-related button is clicked. The event
* is raised by the DOM via something like a <code>onclick</code> attribute.
*
* @param {String} buttonType The type of button being clicked.
* @param {String} [subType=subType] Additional information provided with the button click.
*
* @async
* @private
*/
async onAccountButtonClick(buttonType, subType=null) {
switch (buttonType) {
case "first_run_ok":
this.hide(this.getTemplateByName("firstRun").elements[0]);
this.hideDialog();
this.show(this.getTemplateByName("accountCreate").elements[0]);
break;
case "create_account":
if (subType == "login") {
var element = this.getTemplateByName("accountCreate").elements[0];
this.show(element);
element = this.getTemplateByName("accountLogin").elements[0];
this.hide(this.getTemplateByName("accountManage").elements[0]);
this.hide(element);
return (true);
}
this.hide(this.getTemplateByName("firstRun").elements[0]);
element = this.getTemplateByName("accountCreate").elements[0];
var accountTypeSelect = element.querySelector("#newAccountType");
var accountType = accountTypeSelect.options[accountTypeSelect.selectedIndex].value;
var password = element.querySelector("#newAccountPassword").value;
if (password.split(" ").join("") == "") {
//insert additional password valifity checks here
this.showDialog("Password can't be empty.");
this.hideDialog(4000);
return (false);
}
var typeSplit = accountType.split("/");
this.cypherpoker.createAccount(typeSplit[0], password, typeSplit[1]).then(newAccount => {
this.hide(element);
element = this.getTemplateByName("help").elements[0];
if (typeSplit[0] == "bitcoin") {
if (typeSplit[1] == "test3") {
var helpElement = element.querySelector("#new_account_btc_test3");
} else {
helpElement = element.querySelector("#new_account_btc");
}
} else if (typeSplit[0] == "bitcoincash") {
if (typeSplit[1] == "test") {
var helpElement = element.querySelector("#new_account_bch_test");
} else {
helpElement = element.querySelector("#new_account_bch");
}
}
helpElement.innerHTML = helpElement.innerHTML.split("%address%").join(newAccount.address);
helpElement.innerHTML = helpElement.innerHTML.split("%depositfee%").join(newAccount.fees.deposit);
this.show(helpElement);
this.showDialog();
var newOptionElement = document.createElement("option");
var optionValue = newAccount.address + ":" + newAccount.type + "/" + newAccount.network;