-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.js
3619 lines (3115 loc) · 106 KB
/
common.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
/*
* Code that is common to all web pages enhanced by BBO Helper
*
* BBO Helper browser add-on (Matthew Kidd, San Diego)
*/
// Rarely we have to do something slightly differently in Chrome vs. Firefox
var isChrome = isChromium();
// For Manifest V3, move away from using a polyfill.
if (isChrome) {
var browser = chrome;
}
// Default preferences
let default_pref = {
boardIncludeBorder: false,
boardIncludeNames: true,
boardPlayerNameMode: "bbohandle", // "seat"
boardShowAuction: true,
boardShowContract: true,
boardShowPlay: true,
boardShowHCP: true,
boardShowTiming: true,
boardShowDateTime: true,
boardShowLinks: true,
boardLinksTargetBlank: true,
boardShowDoubleDummy: true,
boardShowExplanations: true,
boardHideRobotExplanations: false,
boardPartialShowBoardNumber: false,
boardPartialShowContract: false,
timingInstantAction: 1,
timingBIT: 10,
timimgLongBIT: 30,
handVoidmdash: true,
cardUse10: true,
suitForceBlack: false,
suitFourColor: false,
auctionPosition: "center",
auctionTextNT: "NT",
auctionShortCalls: true,
auctionSeatLetters: true,
auctionBBOstyling: true,
auctionHideFinalPasses: true,
appTrafficLogging: true,
appTrafficLogFeed: false,
appTrafficLoggingFull: false,
appTrafficLogHidePassword: true,
appTrafficMaxKilobytes: 2000,
appSnifferConsoleLog: false,
appChatNameSubs: true,
appChatAutoSuits: true,
appClaimAutoSuits: true,
appAutoAlerts: true,
appAlertSubstitutions: true,
appShowAuctionClock: true,
appShowPlayClock: true,
appShowPeopleTooltip: true,
appBoardLocalization: true,
appDoubleDummyTricks: true,
appDoubleDummyMode: "always",
hvDoubleDummyMode: "always",
sessDoubleDummyAlways: false,
travSuitFourColor: true,
};
// Default automatic alerts
let aa = {
opening: {
"1D": "4+ diamonds unless 4=4=3=2",
"3N": "Gambling. Nothing on side",
FourthSeat2Bid: "Full opener with 6+ cards",
},
nt: { JacobyTransfers: true, TexasTransfers: true, "2S": "Relay to 3!c" },
ntdef: {
d: "Single-suited",
"2C": "!c + higher suit",
"2D": "!d + higher suit",
"2H": "!h + !s",
"2S": "Weak spades and/or only 5",
"2N": "!c + !d",
},
forcingNT: "semi-passed",
majorJumpRaise: "4 card limit raise",
majorSplinters: true,
Jacoby2NT: true,
invertedMinors: true,
minorJumpRaise: "5-8 HCP",
OneTwoJumpResponse: "0-5 HCP, 6+ cards",
weak2NT: "feature",
NTovercall: "15-18 HCP",
NTbalancing: "11-14 (up to 17 against 1!s)",
directCueBid: { type: "Michaels", style: "5-4-NV-not5422" },
jump2NT: { type: "Two Lowest", style: "5-4-NV-not5422" },
};
default_pref.aa = aa;
// In memory copy of preferences for best performance, updated by an Event Listener
// when changes are made to options in storage. We begin with default preferences
// in case prefs cans not be loaded from storage (should happen) or they are needed
// before they can be loaded (unlikely race condition that could be prevent but isn't
// worth the trouble.
var pref = default_pref;
// It would be better to put preference in sync storage. But if user has not set up
// synchronization or is not permitted it for add-ons, then this storage doesn't seem
// to fall back to local storage.
browser.storage.local.get("pref").then(onPrefLoad, (err) => {
console.error(
"BBO Helper: couldn't load user preferences: ",
err,
" (using defaults)"
);
});
function onPrefLoad(item) {
if (Object.keys(item).length === 0) {
pref = default_pref;
browser.storage.local.set({ pref: pref }).then(false, (err) => {
console.error("BBO Helper: failed to save preferences: ", err);
});
} else {
pref = item.pref;
// Add any new keys from default_pref in later releases of the add-on.
let newkeys = 0;
for (let key in default_pref) {
if (pref[key] === undefined) {
pref[key] = default_pref[key];
newkeys++;
}
}
if (newkeys) {
browser.storage.local.set({ pref: pref }).then(false, (err) => {
console.error("BBO Helper: failed to save preferences: ", err);
});
}
}
app.prefLoaded = true;
// The injected code, which is in the context of the BBO application, listens
// for pref_update to update its copy of PREF.
if (isChrome) {
document.dispatchEvent(new CustomEvent("pref_update", { detail: pref }));
} else {
// Firefox will not allow the page script to access anything in the detail object
// sent by the content script via CustomEvent unless you clone the event detail
// into the document first using the Firefox-specific cloneInto() function.
//
// See https://stackoverflow.com/questions/18744224/
// triggering-a-custom-event-with-attributes-from-a-firefox-extension
let clonedPref = cloneInto(pref, document.defaultView);
document.dispatchEvent(
new CustomEvent("pref_update", { detail: clonedPref })
);
}
// Now setup event listener to reload preferences if they change.
browser.storage.onChanged.addListener(onPrefChange);
}
function onPrefChange(changes, areaName) {
if (areaName === "local" && changes["pref"] !== undefined) {
browser.storage.local.get("pref").then(onPrefUpdate);
}
}
function onPrefUpdate(item) {
pref = item.pref;
if (isChrome) {
document.dispatchEvent(
new CustomEvent("pref_update", { detail: item.pref })
);
} else {
// See comment above in onPrefLoad()
let clonedPref = cloneInto(pref, document.defaultView);
document.dispatchEvent(
new CustomEvent("pref_update", { detail: clonedPref })
);
}
}
// Listen for user preference updates
document.addEventListener("pref_request", () => {
console.info("BBO Helper: responding to a request for user preferneces");
if (isChrome) {
document.dispatchEvent(new CustomEvent("pref_update", { detail: pref }));
} else {
// See comment above in onPrefLoad()
let clonedPref = cloneInto(pref, document.defaultView);
document.dispatchEvent(
new CustomEvent("pref_update", { detail: clonedPref })
);
}
});
// Listen for messages from the popup menu for menu items that invoke an action
// in the current tab supplied by this module.
browser.runtime.onMessage.addListener(function (msg) {
if (msg.type !== "menu") {
return;
}
switch (msg.action) {
case "toggleCopyboard":
copyboard("toggle");
return;
case "dd_bsol":
analyze();
return;
case "createpbn":
createpbn();
return;
case "toggleNameDisplay":
toggleNameDisplay();
return;
case "exportstorage":
exportstorage();
return;
case "importstorage":
selectfile(importstorage);
return;
}
});
function isChromium() {
// navigator.userAgentData.brands is the seemingly clean way because it includes
// brands for both 'Chrome' (etc) and 'Chromium', however Firefox does not yet
// implement navigator.userAgentData and it is not exposed in Chromium for
// insecurely served pages, so provide a fallback mechanism.
return navigator.userAgentData
? navigator.userAgentData.brands.some((data) => data.brand === "Chromium")
: navigator.userAgent.search("Firefox") === -1;
}
// Both these objects are indexed by BBO handles. The first stores caches
// lookup from the background service (fullname, state, mps) and the second
// caches BBO information from <sc_user_profile> messages elements.
// Note: VAR not LET. Need visibility outside common.js
var realnames = {};
var bboprofiles = {};
// Full name of player on a VuGraph. This one is indexed by the player label.
var vgnames = {};
function realnameResponse(msg) {
if (msg === undefined) {
// Shouldn't happen but was happening during switchover to a service worker
// for Manifest V3 compliance.
console.error(
"BBO Helper: realnameResponse() received undefined from service worker."
);
} else if (typeof msg.bbohandle === "object") {
// Note typeof arrays is "object", a JavaScript stupidity.
for (let i = 0; i < msg.bbohandle.length; i++) {
if (msg.fail[i]) {
realnames[msg.bbohandle[i]] = undefined;
continue;
}
realnames[msg.bbohandle[i]] = {
fullname: msg.fullname[i],
state: msg.state[i],
mp: msg.mp[i],
};
}
}
// Single BBO handle response.
else if (msg.lookupfail) {
// Note that lookup failed so that we don't try again.
realnames[msg.bbohandle] = undefined;
} else {
realnames[msg.bbohandle] = {
fullname: msg.fullname,
state: msg.state,
mp: msg.mp,
};
}
}
// BBO's seat order.
const seatletters = "SWNE";
const suitrank = "SHDC";
const suitclass = ["ss", "hs", "ds", "cs"];
const suitentity = ["♠", "♥", "♦", "♣"];
// TP suffix indicate the "text presentation" version that explicitly suppress the Emoji
// presentation that some downstream applications will otherwise convert the suit symbols to.
// '\uFE0E' is the Unicode text presentation selector.
const suitentityTP = suitentity.map((a) => {
return a + "\uFE0E";
});
const suitHTMLclass = suitentityTP.map((a, ix) => {
return `<span class="${suitclass[ix]}">` + a + "</span>";
});
// Black suits will be in foreground color unless user chooses to force them to be black.
const black = pref.suitForceBlack ? "black" : "";
const suit2color = [black, "red", "red", black];
const suit4color = ["#2c399f", "red", "#e86e23", "#40813f"];
// The TP suffixed version are the "text presentation" versions
const suitHTMLplain = new Array(4),
suitHTML4color = new Array(4);
const suitHTMLplainTP = new Array(4),
suitHTML4colorTP = new Array(4);
for (let i = 0; i < 4; i++) {
suitHTML4color[
i
] = `<span style="color: ${suit4color[i]}">${suitentity[i]}</span>`;
suitHTML4colorTP[i] =
`<span style="color: ${suit4color[i]}">` + suitentityTP[i] + "</span>";
if (suit2color[i] === "") {
suitHTMLplain[i] = suitentity[i];
suitHTMLplainTP[i] = suitentityTP[i];
} else {
suitHTMLplain[
i
] = `<span style="color: ${suit2color[i]}">${suitentity[i]}</span>`;
suitHTMLplainTP[i] =
`<span style="color: ${suit2color[i]}">` + suitentityTP[i] + "</span>";
}
}
function sleep(ms) {
// Invoke as 'await sleep(ms)'
return new Promise((resolve) => setTimeout(resolve, ms));
}
function rtrim(s, n) {
// Removes the last N characters from a string. Some version of SUBSTR or
// SUBSTRING should do this... but they don't in JavaScript.
return s.substr(0, s.length - n);
}
function zeroPadInt(n, places) {
s = n.toString();
if (s.length > places) {
return s;
}
return s.padStart(places, "0");
}
function encodedSuitFix(s) {
// Fixes a BBO issue where suit symbols are messed up in a LIN string downloaded
// from BBO My Hands.
return s.replace(/\u00E2\u2122[\u00A0\u00A3\u00A5\u00A6]/gi, suitlettersub);
function suitlettersub(match) {
// Note: the Unicode codepoints for the suit symnols are not consecutive
// and do not exactly follow the bridge suit order.
const suitletter = match.endsWith("\u00A0")
? "s"
: match.endsWith("\u00A3")
? "h"
: match.endsWith("\u00A5")
? "c"
: "d";
return "!" + suitletter;
}
}
function doubleEncodedSuitFix(s) {
// Fixes a BBO issue where suit symbols can end up doubly UTF-8 encoded
// in the LIN string passed to the BBO Handviewer.
// C2 A2 E2 84 A2 C2 A2 C2 Ax
return s.replace(/%C3%A2%E2%84%A2%C2%A[0356]/gi, suitlettersub);
function suitlettersub(match) {
// Note: the Unicode codepoints for the suit symbols are not consecutive
// and do not exactly follow the bridge suit order.
const suitletter = match.endsWith("0")
? "s"
: match.endsWith("3")
? "h"
: match.endsWith("5")
? "c"
: "d";
return "!" + suitletter;
}
}
function UTF8fix(s) {
// JavaScript strings are UTF-16 but with BBO there are situations where the
// UTF-16 string you have (e.g. a LIN string), is really the character code
// equivalents of a UTF-8 string. decodeURIComponent(escape(s)) is the quick
// and dirty solution but escape() is deprecated. So do it "right".
const len = s.length;
if (len === 0) {
return s;
}
// Despite failing to represent other symbols as UTF-8, BBO does so for the suit
// symbols (probably the result of downstream conversion). So undo this before
// the check below.
const u8 = new Uint8Array(len);
for (let i = 0; i < len; i++) {
const val = s.charCodeAt(i);
if (val > 256) {
return s;
} // Not a UTF-8 string packed as UTF-16. Bail.
u8[i] = val;
}
const decoder = new TextDecoder();
return decoder.decode(u8);
}
async function fetchWithTimeout(resource, options = {}) {
const { timeout = 8000 } = options; // 8 sec default
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeout);
const response = await fetch(resource, {
...options,
signal: controller.signal,
});
clearTimeout(id);
return response;
}
function bestAvailableName(bbohandle) {
let lchandle = bbohandle.toLowerCase();
// ACBL database is the best source of real names.
if (realnames[lchandle]) {
return realnames[lchandle].fullname;
}
if (!bboprofiles[lchandle]) {
return bbohandle;
}
let bboname = bboprofiles[lchandle].name;
// NAME field should always be present but guard against BBO changes.
if (bboname === undefined) {
return bbohandle;
}
bboname = bboname.trim();
if (bboname === "" || bboname === "Private" || bboname === "private") {
return bbohandle;
}
// User has some semblance of a real name in their BBO profile. Remove any
// spurious white space and attempt to address capitalization issues.
let parts = bboname.split(/\s+/);
for (let i = 0; i < parts.length; i++) {
let part = parts[i];
// Fix obnoxiously fully capitalized names put ignore suffixes like III
if (
part.length > 1 &&
part.match(/^[A-Z]+$/) !== null &&
part.match(/^[IV]+$/) === null
) {
part = part.toLowerCase();
}
// Capitalize first character of Latin alphabet names except for nobiliary particles.
if (
part.charAt(0) >= "a" &&
part.charAt(0) <= "z" &&
part !== "de" &&
part !== "von" &&
part !== "zu" &&
part !== "of"
) {
part = part.charAt(0).toUpperCase() + part.substr(1);
}
parts[i] = part;
}
// If only a single name is given in the BBO profile add the BBO handle for clarity.
return parts.length === 1
? parts[0] + " (" + bbohandle + ")"
: parts.join(" ");
}
async function boardhtml(d, inlineCSS, includeAll = false) {
// inlineCSS (boolean) - If true, all styling will be inline CSS
// includeAll (boolean) - Include auction, cardplay, timing information,
// double dummy table, contract, HCP, and links regardless of user
// preferences (used when generating session HTML)
let cos;
const seatlabels = seatLabels(d.name, d.isVugraph);
const localize =
pref.appBoardLocalization && app.lang !== "en" && d.handL !== undefined;
let [west, north, east, south] = localize
? [d.handL[1], d.handL[2], d.handL[3], d.handL[0]]
: d.deal.split(":");
const suithtml = !inlineCSS
? suitHTMLclass
: pref.suitFourColor
? suitHTML4colorTP
: suitHTMLplainTP;
const showTiming =
(pref.boardShowTiming || includeAll) &&
d.auctionTimes !== undefined &&
d.playTimes !== undefined;
const showDD =
(pref.boardShowDoubleDummy || includeAll) && d.dd !== undefined;
// Partial deals don't show the action, double dummy table + par contract,
// the card play table, and the alert explanations, handviewer links, and
// event time.
const isFullDeal = d.deal.length === 67;
const showAuction = (pref.boardShowAuction || includeAll) && isFullDeal;
// Even if we are requested to show a table of the trick by trick card
// play, it is only possible if the BBO Hand Viewer was invoked with the
// 'lin' URL parameter because we can not read the internal state of the
// BBO hand viewer or BBO application from the add-on. Also don't show the
// card play if the hand ended before any tricks were played. Will lift
// restriction of full deal later.
const showPlay =
(pref.boardShowPlay || includeAll) &&
isFullDeal &&
(d.cardplay !== undefined ||
(d.lin !== undefined && d.lin.indexOf("pc|") !== -1));
if (showPlay) {
playHTML = cardhtml(d, showTiming, inlineCSS);
}
let showExplanations =
(pref.boardShowExplanations || includeAll) && isFullDeal && d.alert;
if (showExplanations) {
let alert = new Array(d.alert.length);
if (!pref.boardHideRobotExplanations) {
alert = d.alert;
} else {
// Clear Robot alerts.
let dix = seatletters.indexOf(d.dealer);
for (let i = 0; i < d.alert.length; i++) {
let ix = (dix + i) % 4;
alert[i] = d.name[ix] === "Robot" && d.alert[i] ? "" : d.alert[i];
}
}
// See if there were any explained bids.
showExplanations = false;
for (let i = 0; i < d.alert.length; i++) {
if (alert[i] !== undefined && alert[i].trim() !== "") {
showExplanations = true;
break;
}
}
if (showExplanations) {
explainHTML = explainhtml(d.auction, alert, showPlay, inlineCSS);
}
}
// Need the approximate Auction Box width so that we can set padding-left
// For North and South hands to roughly center them while keeping them left aligned
// which they wouldn't be if we simply centered each on in its <td> element. The
// AuctionBox with depends whether we use full seatnames, Pass (or P), etc and is
// best computed in auctionhtml();
let auctionBoxHTML, auctionBoxWidthEm;
if (showAuction) {
[auctionBoxHTML, auctionBoxWidthEm] = auctionhtml(d, showTiming, inlineCSS);
}
// Right padding for West and left padding for East hand
const ewpadding = "0.7em";
let nspadding = (auctionBoxWidthEm - 4) / 2;
nspadding = nspadding > 0 ? nspadding.toFixed(2) + "em" : "0";
// Include the board #, deal, auction, and contract, and LIN string in custom data-
// attributes of the outer <div>. This is the HTML5 solution for including custom
// attributes that are fully valid. The data- attributes allow for programmatic parsing.
let dataAttribs = `data-board="${d.bstr}" data-deal="${d.deal}"`;
if (d.auctionstr !== undefined) {
dataAttribs += ` data-auction="${d.auctionstr}"`;
}
let data_contract =
d.contractLevel === -1
? "Incomplete Auction"
: d.contractLevel === 0
? "Passed Out"
: d.contractLevel + d.contractDenom + d.doubled + " " + d.declarer;
dataAttribs += ` data-contract="${data_contract}"`;
if (d.lin) {
// Don't need full uglification of encodeURIComponent() for the data- attribute.
const qlin = d.lin.replaceAll('"', "&");
dataAttribs += ` data-lin="${qlin}"`;
}
// Include a class for manipulation through CSS of the HTML document into which the
// code snipped is included. Note: Inline styling can be overridden using !important
// See https://cssdeck.com/blog/how-to-override-inline-css-styles/
// https://www.ghacks.net/2015/02/04/select-and-copy-multiple-text-bits-in-firefox-in-one-go/
cos = "";
if (inlineCSS) {
let dvstyle = "padding: 0.2em; break-inside: avoid";
if (pref.boardIncludeBorder) {
dvstyle += "; border: 1px solid #777";
}
cos = `style="${dvstyle}" `;
}
let html = `<div ${cos}class="bh-board" ${dataAttribs}>` + "\n";
html += "<table><tbody>";
// Board number with vulnerability indicator
html += "<tr>";
if (isFullDeal || pref.boardPartialShowBoardNumber) {
// When showing a partial board, don't show the vulnerability indicators.
let vul = pref.boardPartialShowBoardNumber ? "None" : d.vul;
html += numvulhtml(d.bstr, vul) + "\n";
} else {
html += "<td></td>";
}
// North hand
html +=
`<td class="bh-north" style="padding-left: ${nspadding}">` +
handhtml(north, seatlabels[2], inlineCSS) +
"</td>" +
"\n";
// Strip off the day (e.g. 'Sun') at the start.
let datehtml =
d.datestr === undefined || !pref.boardShowDateTime
? ""
: '<span style="font-size: 80%">' + d.datestr.substr(4) + "</span><br>";
if (!isFullDeal || (!pref.boardShowLinks && !includeAll)) {
html += `<td>${datehtml}</td>`;
} else {
// Matchpoint percentage or IMP gain/loss. (Note: Raw score, e.g. +450 is
// shown with the contract, downstream.)
let scorehtml = "";
if (d.score !== undefined) {
if (d.score.endsWith("%") || d.score.startsWith("A")) {
// Matchpoints or some type of average
scorehtml = d.score;
} else {
// Explicit + sign for IMPs won, for clarity.
scorehtml = (d.score > 0 ? "+" : "") + d.score + " IMPS";
}
const cos = inlineCSS
? 'style="margin-bottom: 0.3em"'
: 'class="bh-score"';
scorehtml = `<div ${cos}>` + scorehtml + "</div>";
}
// Add Traveller, BBO Handviewer and BSOL links.
let target = pref.boardLinksTargetBlank ? ' target="_blank"' : "";
const lin = d.lin !== undefined ? d.lin : deal2lin(d, seatlabels);
// It's kind of ugly to replace all the | symbols with %7C but technically | isn't
// a valid character in a URL, though browsers usually accept it and it doesn't
// have a special meaning (i.e. isn't reserved)
const encodedLIN = encodeURIComponent(lin);
let HVurl =
"https://www.bridgebase.com/tools/handviewer.html?lin=" + encodedLIN;
let BSOLurl =
"https://dds.bridgewebs.com/bsol2/ddummy.htm" + "?lin=" + encodedLIN;
if (d.title !== undefined) {
// & needs to be escaped because it is inside HTML.
BSOLurl += "&title=" + encodeURIComponent(d.title);
}
let linkhtml = '<div class="bh-links">' + "\n";
if (d.travellerURL !== undefined) {
let travellerURL = d.travellerURL.replaceAll("&", "&");
linkhtml += `<a href="${travellerURL}"${target}>Traveller</a><br>` + "\n";
}
linkhtml +=
`<a href="${HVurl}"${target}>BBO Viewer</a><br>` +
"\n" +
`<a href="${BSOLurl}"${target}>Bridge Solver</a>` +
"\n" +
"</div>";
// When we have both a score and the traveller link, it looks better to
// align to the top of the <td>, otherwise center vertically.
const alignTop = d.score !== undefined && d.travellerURL !== undefined;
let style =
"padding-left: 0.7em; vertical-align: " + (alignTop ? "top" : "middle");
let classList = "bh-score-links " + (alignTop ? "vtop" : "vmid");
cos = inlineCSS ? `style="${style}"` : `class="${classList}"`;
html += `<td ${cos}>${scorehtml}${datehtml}${linkhtml}</td>` + "\n";
}
// Create a <td> that spans all three rows if we are showing a play table.
if (showPlay) {
html +=
'<td rowspan="3" style="padding-left: 1.5em">' +
"\n" +
playHTML +
"</td>";
}
// Create a <td> that spans all three rows if we are showing explanations
if (showExplanations) {
let padding = showPlay ? "0.6em" : "1em";
let style = `vertical-align: middle; padding-left: ${padding}`;
html +=
`<td rowspan="3" class="bh-explanations" style="${style}">` +
explainHTML +
"</td>";
}
html += "</tr>" + "\n\n";
style = `vertical-align: middle; padding-right: ${ewpadding}`;
html +=
"<tr>" +
`<td class="bh-west" style="${style}">` +
handhtml(west, seatlabels[1], inlineCSS) +
"</td>" +
"\n";
if (showAuction && pref.auctionPosition === "center") {
html += '<td style="padding: 0">' + "\n";
html += auctionBoxHTML;
html += "</td>" + "\n";
} else {
html += "<td></td>";
}
// East hand
style = `vertical-align: middle; padding-left: ${ewpadding}`;
html +=
`<td class="bh-east" style="${style}">` +
handhtml(east, seatlabels[3], inlineCSS) +
"</td></tr>" +
"\n\n";
html += "<tr>";
// Double dummy information (or HCP if not including double dummy)
if (showDD) {
let [ddtablehtml, parhtml] = ddhtml(d.dd, "Board", inlineCSS);
html +=
'<td><div class="bh-dd-par">' +
ddtablehtml +
"\n" +
parhtml +
"</div></td>";
} else if (isFullDeal && (pref.boardShowHCP || includeAll)) {
html += "<td>" + hcphtml(d.hcp, inlineCSS) + "</td>";
} else {
html += "<td></td>";
}
html += "\n";
html +=
`<td class="bh-south" style="padding-left: ${nspadding}">` +
handhtml(south, seatlabels[0], inlineCSS) +
"</td>" +
"\n";
const showContract = isFullDeal
? pref.boardShowContract || includeAll
: pref.boardPartialShowContract;
if (!showContract) {
html += "<td></td>";
} else {
let showHCP = isFullDeal && (pref.boardShowHCP || includeAll) && showDD;
// Center contract (and optional raw score) they are the only thing(s) in the cell;
// otherwise leave a little space between it and the HCP diagram.
let cos = inlineCSS
? 'style="text-align: center; vertical-align: middle"'
: 'class="bh-td-contract"';
html += `<td ${cos}>`;
// Sometimes have the raw score.
const haveRawScore = d.rawScore !== undefined;
if (haveRawScore) {
// Make positive score (for your user's side) explicit.
const rawScore = (d.rawScore > 0 ? "+" : "") + d.rawScore;
const style = "font-size: 120%; font-weight: bold; margin-bottom: 0.2em";
const classList = "bh-rawscore sps";
cos = inlineCSS ? `style="${style}"` : `class="${classList}"`;
html += `<div ${cos}>` + rawScore + "</div>";
}
let contracthtml;
if (d.contractLevel === -1) {
contracthtml = "Incomplete<br>Auction";
} else if (d.contractLevel === 0) {
contracthtml = "Passed<br>Out";
} else {
const ix = suitrank.indexOf(d.contractDenom);
// localize ? app.locale.nt
const denomtxt =
ix !== -1 ? suithtml[ix] : localize ? app.locale.nt : "NT";
const declarertxt = !localize
? d.declarer
: app.locale.seatLetters.charAt(seatletters.indexOf(d.declarer));
contracthtml = d.contractLevel + denomtxt;
contracthtml += d.doubled + " " + declarertxt;
}
let style = "font-size: 120%; font-weight: bold";
let classList = "bh-contract";
if (showHCP) {
// Add appropriate vertical space before HCP table.
style += "; margin-bottom: " + (haveRawScore ? "0.2em" : "0.5em");
classList += " " + (haveRawScore ? "sps" : "spl");
}
cos = inlineCSS ? `style="${style}"` : `class="${classList}"`;
html += `<div ${cos}>` + contracthtml + "</div>";
// Drop HCP table diagram below the contract if the double dummy table
// displaced it from its default location at the bottom left.
if (showHCP) {
html += hcphtml(d.hcp, inlineCSS);
}
html += "</td>";
}
html += "</tr>" + "\n";
html += "</tbody></table>";
html += "</div>";
return html;
}
function numvulhtml(bstr, vul) {
// Units of em (for 200% font size)
let bwidth = bstr.length <= 2 ? 1.2 : 1.8;
let bheight = 1.2;
let bpadding = 0.16;
let vulsize = 0.5;
let fontsize = 200;
// display: inline-block so that width and height work.
const bstyle =
`text-align: center; vertical-align: middle; ` +
"background-color: white; border: solid 1px black; display: inline-block; " +
`width: ${bwidth}em; height: ${bheight}em; padding: ${bpadding}em`;
let bnhtml = `<div class="bh-bnum" style="${bstyle}">${bstr}</div>`;
if (vul === "None") {
const tstyle = `margin: auto; text-align: center; font-size: ${fontsize}%`;
return `<td style="${tstyle}">${bnhtml}</td>`;
}
let tstyle =
"display: flex; justify-content: center; align-items: center; " +
`font-size: ${fontsize}%`;
if (vul === "NS") {
// Final 0.06 compensates for width of border around board number box
let w = bwidth + bpadding * 2 + 0.06;
let h = bheight + bpadding * 2 + vulsize * 2;
let style =
`background-color: red; width: ${w}em; height: ${h}em; ` +
"display: flex; justify-content: center; align-items: center";
return (
`<td style="${tstyle}">` +
`<div style="${style}">` +
bnhtml +
"</div></td>"
);
}
if (vul === "EW") {
// Final 0.06 compensates for height of border around board number box
let h = bheight + bpadding * 2 + 0.06;
let w = bwidth + bpadding * 2 + vulsize * 2;
let style =
`background-color: red; width: ${w}em; height: ${h}em; ` +
"display: flex; justify-content: center; align-items: center";
return (
`<td style="${tstyle}">` +
`<div style="${style}">` +
bnhtml +
"</div></td>"
);
}
if (vul === "All") {
let h = bheight + bpadding * 2 + vulsize * 2;
let w = bwidth + bpadding * 2 + vulsize * 2;
let style =
`background-color: red; width: ${w}em; height: ${h}em; ` +
"display: flex; justify-content: center; align-items: center";
return (
`<td style="${tstyle}">` +
`<div style="${style}">` +
bnhtml +
"</div></td>"
);
}
console.log(
"BBO Helper: numvulhtml(): vul must be 'None', 'NS', 'EW' or 'All'"
);
return "";
}
function handhtml(hd, pname, inlineCSS) {
let html = "";
let cos; // COS (Class or Style)
let suitcolor = pref.suitFourColor ? suit4color : suit2color;
if (pref.boardIncludeNames) {
cos = inlineCSS
? 'style="background-color: #d3d3d3; padding: 0 0.2em 0 0.2em"'
: 'class="pname"';
html += `<span ${cos}>` + pname + "</span><br>";
}
html += inlineCSS
? '<span style="letter-spacing: 0.2em">'
: '<span class="hand">';
let suits = hd.split(".");
for (let i = 0; i < 4; i++) {
// 1em is wide enough for the heart symbol, the widest suit symbol in most fonts.
if (inlineCSS) {
let style = "display: inline-block; width: 1em; text-align: center";
if (suitcolor[i] !== "") {
style += `; color: ${suitcolor[i]}`;
}
cos = `style="${style}"`;
} else {
cos = `class="hsym ${suitclass[i]}"`;
}
// Use text presentation version. This should prevent later programs (say Microsoft
// Outlook) from converting the suit symbols to emoji style presentation.
html += `<span ${cos}>` + suitentityTP[i] + "</span>";
if (suits[i].length) {
if (!pref.cardUse10) {
html += suits[i];
} else {
let suit10sub = inlineCSS
? suits[i].replace("T", '<span style="letter-spacing: 0">1</span>0')
: suits[i].replace("T", '<span class="ten">1</span>0');
html += suit10sub;
}
} else {
// Void in suit.
if (pref.handVoidmdash) {
html += "—";
}
}
if (i < 3) {
html += "<br>";
}
}
html += "</span>";
return html;
}
function timecolor(tm, inlineCSS) {