/
natsuiro.js
5211 lines (4823 loc) · 217 KB
/
natsuiro.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
(function(){
"use strict";
_gaq.push(['_trackEvent', "Panel: Natsuiro Theme", 'clicked']);
// Mathematical Constants
var LOG3 = Math.log10(3);
// Flags
var currentLayout = "";
var isRunning = false;
var lastApiError = false;
var lastApiFlag2 = false;
// Interface values
var selectedFleet = 1;
var selectedExpedition = 1;
var plannerIsGreatSuccess = false;
var showCombinedFleetBars = true;
var isTakingScreenshot = false;
var isActiveTabInvoked = false;
var overrideFocus = false;
// a flag used by Fleet & ExpeditionStart to indicate
// whether a fleet info update is triggered because of
// sending out fleets.
var expeditionStarted = false;
// Critical Animation and Sound Effect
var critAnim = false;
var critSound = new Audio("../../../../assets/snd/heart.mp3");
critSound.loop = true;
// The URL prefix of current player's KC server
var myKcServerHost = "";
// Morale Timer
var moraleTimerHandler = 0;
var moraleTimerLastUpdated = 0;
var moraleClockValue = 100;
var moraleClockEnd = 0;
var moraleClockRemain = 0;
// UI Updating Timer
var uiTimerHandler = 0;
var uiTimerLastUpdated = 0;
// Panel Reload Reminder Timer
var reloadReminderHandler = 0;
// QuestList api result cache
var questCacheResult = [];
// A jquery-ui tooltip options like native one
var nativeTooltipOptions = {
position: { my: "left top", at: "left+25 bottom", collision: "flipfit" },
items: "[title],[titlealt]",
content: function(){
// Default escaping not used, keep html, simulate native one
return ($(this).attr("title") || $(this).attr("titlealt") || "")
.replace(/\n/g, "<br/>")
.replace(/\t/g, "  ");
}
};
(function($) {
// AOP around the dispatcher for any exception thrown from event handlers
var originalEventDispatch = $.event.dispatch;
$.event.dispatch = function() {
try {
originalEventDispatch.apply(this, arguments);
} catch(error) {
console.error("Uncaught event", error, this);
throw error;
}
};
// A lazy initializing method, prevent duplicate tooltip instance
$.fn.lazyInitTooltip = function(opts) {
if(typeof this.tooltip("instance") === "undefined") {
this.tooltip($.extend(true, {}, nativeTooltipOptions, opts));
}
return this;
};
// Actively close tooltips of element and its children
$.fn.hideChildrenTooltips = function() {
$.each($("[title]:not([disabled]),[titlealt]:not([disabled])", this), function(_, el){
if(typeof $(el).tooltip("instance") !== "undefined")
$(el).tooltip("close");
});
return this;
};
// Create native-like tooltips of element and its children
$.fn.createChildrenTooltips = function() {
$.each($("[title]:not([disabled])", this), function(_, el){
$(el).lazyInitTooltip();
});
return this;
};
}(jQuery));
// Reusable contents of Error Report
var errorReport = {
title: "",
message: "",
stack: "",
request: "",
params: "",
response: "",
serverUtc: 0,
kc3Version: [chrome.runtime.getManifest().name, chrome.runtime.getManifest().version].join(" "),
dmmPlay: "",
gameTabUrl: "",
userAgent: "",
utc: 0
};
// make sure localStorage.expedTab is available
// and is in correct format.
// returns the configuration for expedTab
// (previously called localStorage.expedTabLastPick)
function ExpedTabValidateConfig(idToValid) {
// data format for expedTab:
// data.fleetConf: an object
// data.fleetConf[fleetNum]:
// * fleetNum: 1,2,3,4
// * fleetNum could be either number or string
// they will all be implicitly converted
// to string (for indexing object) anyway
// data.fleetConf[fleetNum].expedition: a number
// data.expedConf: an object
// data.expedConf[expedNum]:
// * expedNum: 1..46, 100..105, 110..115, 131..133, 141..142
// * expedNum is number or string, just like fleetNum
// data.expedConf[expedNum].greatSuccess: boolean
var data;
const fillExpedConfDefaultGreatSuccess = (...ids) => {
ids.forEach(i => {
data.expedConf[i] = { greatSuccess: false };
});
};
if (! localStorage.expedTab) {
data = {};
data.fleetConf = {};
var i;
for (i=1; i<=4; ++i) {
data.fleetConf[i] = { expedition: 1 };
}
data.expedConf = {};
fillExpedConfDefaultGreatSuccess(...Array.numbers(1, 46));
fillExpedConfDefaultGreatSuccess(...Array.numbers(100, 105));
fillExpedConfDefaultGreatSuccess(...Array.numbers(110, 115));
fillExpedConfDefaultGreatSuccess(131, 132, 133, 141, 142);
localStorage.expedTab = JSON.stringify( data );
} else {
data = JSON.parse( localStorage.expedTab );
// add default GS config for new added expeditions
// * extended since 2017-10-18: 100~102 display name A1~A3 for World 1
// * extended since 2017-10-25: 110~111 B1~B2 for World 2
// * extended since 2019-07-18: A4, B3, B4 and World 7. Monthly.
// * extended since 2020-02-07: 45, D1, D2
// * extended since 2020-03-27: B5, E1 for World 5
// * extended since 2020-05-20: A5, A6
// * extended since 2020-09-17: 46, E2
// * extended since 2021-02-05: B6, D3
if(idToValid > 0 && data.expedConf[idToValid] === undefined) {
fillExpedConfDefaultGreatSuccess(idToValid);
}
}
return data;
}
// selectedExpedition, plannerIsGreatSuccess + selectedFleet => storage
function ExpedTabUpdateConfig() {
const conf = ExpedTabValidateConfig(selectedExpedition);
if(selectedFleet > 4) return;
conf.fleetConf[ selectedFleet ].expedition = selectedExpedition;
conf.expedConf[ selectedExpedition ].greatSuccess = plannerIsGreatSuccess;
localStorage.expedTab = JSON.stringify( conf );
}
// apply stored user settings, note that this function
// is not responsible for updating UI, so UpdateExpeditionPlanner() should be called after
// this to reflect the change
// storage + selectedFleet => selectedExpedition, plannerIsGreatSuccess
function ExpedTabApplyConfig() {
if(selectedFleet > 4) return;
let conf = ExpedTabValidateConfig(selectedExpedition);
selectedExpedition = conf.fleetConf[ selectedFleet ].expedition;
// re-validate config in case that fleet has just returned from a new exped
conf = ExpedTabValidateConfig(selectedExpedition);
plannerIsGreatSuccess = (conf.expedConf[selectedExpedition] || {}).greatSuccess || false;
}
function ExpedTabAutoFleetSwitch(needTabSwith) {
// set "needTabSwitch" to true
// for switching to expedition tab when a candidate fleet is found
var fleets = PlayerManager.fleets;
var availableFleetInd = -1;
// if combined fleet is in use, the second fleet is not available
// so we can skip it
// start from the 2nd fleet (or 3rd if we have a combined fleet)
var fleetStartInd = (PlayerManager.combinedFleet !== 0) ? 2 : 1;
for (var i = fleetStartInd; i < 4; ++i) {
// find one available fleet
if (fleets[i].missionOK()) {
availableFleetInd = i;
break;
}
}
if (availableFleetInd !== -1) {
selectedFleet = availableFleetInd + 1;
console.debug("Find available fleet:", selectedFleet);
switchToFleet(selectedFleet);
if (needTabSwith)
$("#atab_expeditionPlanner").trigger("click");
} else {
// knowing fleets are all unavailable
// we can return focus to the main fleet.
// or if combined fleet is in used, we go to combined fleet tab
switchToFleet(PlayerManager.combinedFleet !== 0 ? "combined" : 1);
// also return focus to basic tab
$("#atab_basic").trigger("click");
}
}
function switchToFleet(targetFleet) {
if (targetFleet === "combined") {
$(".module.controls .fleet_rengo").trigger("click");
} else if (targetFleet === "lbas") {
$(".module.controls .fleet_lbas").trigger("click");
} else {
var fleetControls = $(".module.controls .fleet_num").toArray();
for (var i=0; i<fleetControls.length; ++i) {
var thisFleet = parseInt( $(fleetControls[i]).text(), 10);
if (thisFleet === targetFleet) {
$( fleetControls[i] ).trigger("click");
break;
}
}
}
}
function attemptToSwitchFleet(targetFleet) {
// Won't switch when option is disabled at Settings
if (!ConfigManager.info_auto_fleet_view) {
return false;
}
// Won't switch if current selected is combined and target will be 1 or 2
if (selectedFleet == 5 && (targetFleet == 1 ||
targetFleet == 2 || targetFleet === "combined")) {
return false;
}
// Won't switch if current selected is LBAS
if (selectedFleet == 6 && targetFleet === "lbas") {
return false;
}
// Won't switch if target fleet is current
if (selectedFleet == targetFleet) {
return false;
}
switchToFleet(targetFleet);
return true;
}
/* Morale timers
- use end time difference not remaining decrements for accuracy against lag
--------------------------------------------*/
function runUpdatingMoraleTimer() {
moraleTimerLastUpdated = Date.now();
// console.log(moraleClockValue, moraleClockEnd, moraleClockRemain);
if(moraleClockEnd > 0){
moraleClockRemain = Math.ceil( (moraleClockEnd - Date.now())/1000);
if(moraleClockRemain > 0){
$(".module.status .status_morale .status_text").text("~"+(moraleClockRemain+"").toHHMMSS());
}else{
moraleClockValue = 100;
moraleClockEnd = 0;
moraleClockRemain = 0;
$(".module.status .status_morale .status_text").text( KC3Meta.term("PanelRecoveredMorale") );
// Morale desktop notification if not on sortie/PvP,
if(ConfigManager.alert_morale_notif &&
!(KC3SortieManager.isOnSortie() || KC3SortieManager.isPvP())
){
// Play sound if alert sound setting is not none
if(KC3TimerManager.notifSound){ KC3TimerManager.notifSound.pause(); }
switch(ConfigManager.alert_type){
case 1: KC3TimerManager.notifSound = new Audio("../../../../assets/snd/pop.mp3"); break;
case 2: KC3TimerManager.notifSound = new Audio(ConfigManager.alert_custom); break;
case 3: KC3TimerManager.notifSound = new Audio("../../../../assets/snd/ding.mp3"); break;
case 4: KC3TimerManager.notifSound = new Audio("../../../../assets/snd/dong.mp3"); break;
case 5: KC3TimerManager.notifSound = new Audio("../../../../assets/snd/bell.mp3"); break;
default: KC3TimerManager.notifSound = false; break;
}
if(KC3TimerManager.notifSound){
KC3TimerManager.notifSound.volume = ConfigManager.alert_volume / 100;
KC3TimerManager.notifSound.play();
}
// Send desktop notification
(new RMsg("service", "notify_desktop", {
notifId: "morale",
data: {
type: "basic",
title: KC3Meta.term("DesktopNotifyMoraleTitle"),
message: KC3Meta.term("DesktopNotifyMoraleMessage"),
iconUrl: "../../assets/img/ui/morale.png"
},
tabId: chrome.devtools.inspectedWindow.tabId
})).execute();
// Focus game tab if settings enabled
if(ConfigManager.alert_focustab){
(new RMsg("service", "focusGameTab", {
tabId: chrome.devtools.inspectedWindow.tabId
})).execute();
}
}
}
}
}
function checkAndRestartMoraleTimer() {
if(!moraleTimerHandler || Date.now() - moraleTimerLastUpdated >= 2000){
if(!!moraleTimerHandler){
console.debug("Old morale timer abandoned:", moraleTimerHandler);
clearInterval(moraleTimerHandler);
}
moraleTimerHandler = setInterval(runUpdatingMoraleTimer, 1000);
}
}
function runUpdatingUiTimer() {
uiTimerLastUpdated = Date.now();
// Basic Timer Stat
KC3TimerManager.update();
// Docking ~ Akashi Timer Stat
let scopedFleetIds = [];
if(selectedFleet == 6) {
// No docking or Akashi timer for LBAS,
// TODO show timer for all (max) moving LBAS planes ETA
} else {
scopedFleetIds = selectedFleet >= 5 ? [0, 1] : [selectedFleet - 1];
const data = scopedFleetIds
.map(id => PlayerManager.fleets[id].highestRepairTimes(true))
.reduce((acc, cur) => {
Object.keys(cur).forEach(k => {
if(typeof cur[k] === "number") {
acc[k] = Math.max(acc[k] || 0, cur[k]);
} else if(Array.isArray(cur[k])) {
if(acc[k] === undefined || cur[k].every(v => !!v)) acc[k] = cur[k];
} else {
acc[k] = cur[k];
}
});
return acc;
}, {});
UpdateRepairTimerDisplays(data);
}
// Akashi current timer for Ship Box list
const baseElement = scopedFleetIds.length ?
scopedFleetIds.length > 1 ? ['main','escort'] : ['single']
: [];
baseElement.forEach(function(baseKey, index){
const baseContainer = $([".shiplist",baseKey].join('_'));
$(".sship,.lship", baseContainer).each(function(index, shipBox){
const repairBox = $('.ship_repair_data',shipBox);
const shipData = KC3ShipManager.get(repairBox.data('sid')),
hpLost = shipData.hp[1] - shipData.hp[0],
dockTime = shipData.repair[0],
repairProgress = PlayerManager.akashiRepair.getProgress(dockTime, hpLost);
$('.ship_repair_tick', shipBox).attr('data-tick',
Number.isInteger(repairProgress.repairedHp) ? repairProgress.repairedHp : '?');
$('.ship_repair_timer', shipBox).text(
(function (t) {
if (t === 0) {
return '--:--:--';
} else if (!t || Number.isNaN(parseInt(t))) {
return '??:??:??';
}
return Math.ceil(t / 1000).toString().toHHMMSS();
})(repairProgress.timeToNextRepair)
);
});
});
}
function checkAndRestartUiTimer() {
if(!uiTimerHandler || Date.now() - uiTimerLastUpdated >= 2000){
if(!!uiTimerHandler){
console.debug("Old UI timer abandoned:", uiTimerHandler);
clearInterval(uiTimerHandler);
}
uiTimerHandler = setInterval(runUpdatingUiTimer, 1000);
}
}
$(document).on("ready", function(){
// Check localStorage
if(!window.localStorage){
$("#wait").hide();
$("<div>").css({
"width" : "450px",
"padding" : "15px 20px",
"background" : "#fcc",
"border-radius" : "10px",
"margin" : "30px auto 0px",
"text-align" : "center",
"font-weight" : "bold",
"font-size" : "12px",
"border" : "1px solid #c77"
}).html( KC3Meta.term("PanelErrorStorage") ).appendTo("body");
return true;
}
// Initialize data managers
ConfigManager.load();
KC3Master.init();
RemodelDb.init();
WhoCallsTheFleetDb.init("../../../../");
KC3Meta.init("../../../../data/");
KC3Master.loadAbyssalShips("../../../../data/");
KC3Meta.defaultIcon("../../../../assets/img/ui/empty.png");
KC3Meta.loadQuotes();
PlayerManager.init();
PlayerManager.loadConsumables();
KC3ShipManager.load();
KC3GearManager.load();
KC3SortieManager.load();
KC3Database.init();
KC3Translation.execute();
KC3QuestSync.init();
myKcServerHost = myKcServerHost || (() => {
let host = (new KC3Server()).setNum(PlayerManager.hq.server).ip;
return host ? `http://${host}` : "";
})();
// Live translations of Quests, only work for EN
if(ConfigManager.checkLiveQuests && ConfigManager.language=="en"){
$.ajax({
async: true,
dataType: "JSON",
url: "https://raw.githubusercontent.com/KC3Kai/kc3-translations/master/data/"+ConfigManager.language+"/quests.json?v="+(Date.now()),
success: function(newQuestTLs){
if(JSON.stringify(newQuestTLs) !== JSON.stringify(KC3Meta._quests)){
var enQuests = JSON.parse($.ajax({
url : '../../../../data/lang/data/en/quests.json',
async: false
}).responseText);
KC3Meta._quests = $.extend(true, enQuests, newQuestTLs);
//console.debug(KC3Meta._quests);
console.info("New quests detected, live updated");/*RemoveLogging:skip*/
}else{
console.info("Quests is up to date");
}
}
});
}
// Panel customizations: panel opacity
$(".wrapper_bg").css("opacity", ConfigManager.pan_opacity / 100);
$(".module.activity .activity_tab").css("background", ConfigManager.pan_box_bcolor);
$(".module.activity .activity_body").css("background", ConfigManager.pan_box_bcolor);
$(".module.fleet").css("background", ConfigManager.pan_shiplist_bg);
$(".ship_img,.timer-img img,.shipIcon img,.pvp_fleet_ship_icon img,.pvp_enemy_pic img"
+",.mod_ship_pic img,.expres_ship_img img,.fit_ship_pic img,.assistant_ship img")
.css("background", ConfigManager.pan_ship_icon_bg);
$(".ship_img,.timer-img img").css("border", "1px solid " + ConfigManager.pan_ship_icon_border);
// Some text or other elements aren't desirable to drop a shadow from, so these were selected manually.
const shadowDirStr = (
"-1px -1px 1px "+ConfigManager.pan_drop_shadow
+", 0px -1px 1px "+ConfigManager.pan_drop_shadow
+", 1px -1px 1px "+ConfigManager.pan_drop_shadow
+", -1px 0px 1px "+ConfigManager.pan_drop_shadow
+", 1px 0px 1px "+ConfigManager.pan_drop_shadow
+", -1px 1px 1px "+ConfigManager.pan_drop_shadow
+", 0px 1px 1px "+ConfigManager.pan_drop_shadow
+", 1px 1px 1px "+ConfigManager.pan_drop_shadow
);
$(".module.activity,.airbase,.base_plane_col,.module.admiral,.status_text,.summary_box,.quest,.ship_name,.ship_type"
+",.lship .ship_level,.sship .ship_level,.ship_hp_text,.ship_exp_label,.lship .ship_exp_next,.sship .ship_exp_next,.ship_gear_slot")
.css("text-shadow", shadowDirStr);
$(".quest_color,.ship_exp_bar,.ship_gear_icon")
.css("box-shadow", shadowDirStr);
$(".ship_hp_box .ship_hp_bar_metrics").toggle(!!ConfigManager.pan_hp_bar_metrics);
$(".module.quests").toggleClass("compact", !!ConfigManager.pan_compact_quests);
// Panel customizations: bg image
if(ConfigManager.pan_bg_image === ""){
$("body").css("background", ConfigManager.pan_bg_color);
}else{
$("body").css("background-image", "url("+ConfigManager.pan_bg_image+")");
$("body").css("background-color", ConfigManager.pan_bg_color);
$("body").css("background-size", ConfigManager.pan_bg_size);
$("body").css("background-position", ConfigManager.pan_bg_position);
$("body").css("background-repeat", "no-repeat");
}
// Panel customizations: custom css
var customCSS = document.createElement("style");
customCSS.type = "text/css";
customCSS.id = "pan_custom_css";
customCSS.innerHTML = ConfigManager.pan_custom_css;
$("head").append(customCSS);
const updateShipTooltipStatsIconset = () => {
$(".ship_face_tooltip .stat_icon img").each((_, img) => {
$(img).attr("src", KC3Meta.statIcon(
$(img).parent().data("stat"), ConfigManager.info_stats_iconset
));
});
$(".ship_face_tooltip").data("statsIconset", ConfigManager.info_stats_iconset);
};
updateShipTooltipStatsIconset();
// Listen config key changed
window.addEventListener("storage", function({key, timeStamp, url}){
if(key === ConfigManager.keyName()) {
ConfigManager.load();
console.debug("Reload ConfigManager caused by", (url || "").match(/\/\/[^\/]+\/([^\?]+)/)[1]);
if($("#pan_custom_css").html() !== ConfigManager.pan_custom_css){
$("#pan_custom_css").html(ConfigManager.pan_custom_css);
}
if($(".ship_face_tooltip").data("statsIconset") != ConfigManager.info_stats_iconset){
updateShipTooltipStatsIconset();
}
$(".module.controls .btn_alert_toggle").toggleClass("disabled",
!ConfigManager.alert_taiha || !ConfigManager.alert_taiha_sound);
$(".ship_hp_box .ship_hp_bar_metrics").toggle(!!ConfigManager.pan_hp_bar_metrics);
$(".module.quests").toggleClass("compact", !!ConfigManager.pan_compact_quests);
updateQuestActivityTab();
}
});
// Handle keyboard events passed to panel for hotkeys
$(document).on("keydown", function(e){
// Disable Tab key to prevent it scrolling any window
if(e.which === 9) {
e.stopPropagation();
e.preventDefault();
}
switch(e.keyCode) {
case 49: // 1 key switch to fleet #1 view
$(".module.controls .fleet_num:contains('1')").trigger("click");
break;
case 50: // 2 key switch to fleet #2 view
$(".module.controls .fleet_num:contains('2')").trigger("click");
break;
case 51: // 3 key switch to fleet #3 view
$(".module.controls .fleet_num:contains('3')").trigger("click");
break;
case 52: // 4 key switch to fleet #4 view
$(".module.controls .fleet_num:contains('4')").trigger("click");
break;
case 53: // 5 key switch to combined fleet view
$(".module.controls .fleet_rengo").trigger("click");
break;
case 54: // 6 key switch to LBAS view
$(".module.controls .fleet_lbas").trigger("click");
break;
case 81: // Q key switch to basic tab
$(".module.activity #atab_basic").trigger("click");
break;
case 87: // W key switch to battle tab
$(".module.activity #atab_battle").trigger("click");
break;
case 69: // E key switch to quest tab
if(ConfigManager.info_quest_activity)
$(".module.activity #atab_quest").trigger("click");
break;
case 82: // R key switch to exped planner tab
$(".module.activity #atab_expeditionPlanner").trigger("click");
break;
case 119: // F8 mute toggle OR Shift+F8 alert sound toggle
if(e.shiftKey) {
$(".module.controls .btn_alert_toggle").trigger("click");
} else {
$(".module.controls .btn_mute").trigger("click");
}
break;
case 120: // F9 screenshot
$(".module.controls .btn_ss1").trigger("click");
break;
}
});
// Close CatBomb modal
$(".modalBox").on("click", ".closebtn", function(){
$(this).parent().parent().fadeOut(300);
});
// Download error report
$("#catBomb .download").on("click", function(){
var blob = new Blob([JSON.stringify(errorReport)], {type: "application/json;charset=utf-8"});
saveAs(blob, 'KC3-Error-'+Math.floor((new Date()).getTime()/1000)+".json");
});
// HQ name censoring
$(".admiral_name").on("click", function(){
if($(this).hasClass("censor")){
$(this).removeClass("censor");
}else{
$(this).addClass("censor");
}
});
// HQ Exp Toggle
$(".admiral_lvnext").on("click",function(){
ConfigManager.scrollHQExpInfo();
NatsuiroListeners.HQ();
});
// Switch Rank Title vs Rank Points Counter
$(".admiral_rank").on("click",function(){
ConfigManager.scrollRankPtsMode();
NatsuiroListeners.HQ();
});
// HQ Info Toggle
$(".consumables").on("click",function(){
ConfigManager.scrollHqInfoPage();
NatsuiroListeners.Consumables();
});
// eLoS Toggle
$(".summary-eqlos").on("click",function(){
if(selectedFleet === 6) return;
ConfigManager.scrollElosMode();
NatsuiroListeners.Fleet();
}).addClass("hover");
// Fighter Power Toggle
$(".summary-airfp .summary_icon").on("click",function(){
if(selectedFleet !== 5) return;
ConfigManager.loadIfNecessary();
ConfigManager.air_combined = !ConfigManager.air_combined;
ConfigManager.save();
NatsuiroListeners.Fleet();
}).addClass("hover");
$(".summary-airfp .summary_text").on("click",function(){
if(selectedFleet === 6) return;
ConfigManager.scrollFighterPowerMode();
NatsuiroListeners.Fleet();
}).addClass("hover");
// AntiAir Formation Toggle
$(".summary-antiair").on("click",function(){
if(selectedFleet === 6) return;
ConfigManager.scrollAntiAirFormation(selectedFleet === 5);
NatsuiroListeners.Fleet();
}).addClass("hover");
// Timer Type Toggle
$(".status_docking,.status_akashi").on("click",function(){
if(selectedFleet === 6) return;
ConfigManager.scrollTimerType();
UpdateRepairTimerDisplays();
}).addClass("hover");
// Screenshot buttons
$(".module.controls .btn_ss1").on("click", function(){
if (isTakingScreenshot) return;
isTakingScreenshot = true;
$(this).addClass("active");
const tabId = chrome.devtools.inspectedWindow.tabId;
const doScreenshot = function() {
// Tell service to pass a message to gamescreen on inspected window to get a screenshot
(new RMsg("service", "screenshot", {
tabId: tabId,
playerName: PlayerManager.hq.name
}, function(response){
$(".module.controls .btn_ss1").removeClass("active");
isTakingScreenshot = false;
})).execute();
};
// Check if permission has been granted first
if(!isActiveTabInvoked){
(new RMsg("service", "checkPermission", {
tabId: tabId
}, function(response){
if(response && response.value){
isActiveTabInvoked = true;
doScreenshot();
} else {
NatsuiroListeners.ModalBox({
title: KC3Meta.term("PanelPermissionTitle"),
message: KC3Meta.term("PanelPermissionMessage"),
});
isActiveTabInvoked = false;
$(".module.controls .btn_ss1").removeClass("active");
isTakingScreenshot = false;
}
})).execute();
} else {
doScreenshot();
}
});
// Export button
$(".module.controls .btn_export").on("click", function(e){
if(e.altKey && window.KC3ImageBuilder) {
KC3ImageBuilder.exportCurrentFleets();
} else {
window.open("http://www.kancolle-calc.net/deckbuilder.html?predeck=".concat(encodeURI(
JSON.stringify(PlayerManager.prepareDeckbuilder())
)));
}
});
const prepareBattleLogsData = function(){
// Don't pop up if a battle has not started yet
if( !(KC3SortieManager.isOnSortie() || KC3SortieManager.isPvP())
|| KC3SortieManager.countNodes() < 1) { return false; }
const node = KC3SortieManager.currentNode();
if(node.type !== "battle"
|| !(node.battleDay || node.battleNight)) { return false; }
const isPvP = node.isPvP;
const sortie = {
id: KC3SortieManager.isOnSavedSortie() && KC3SortieManager.onSortie || (isPvP ? "TBD" : "???"),
diff: KC3SortieManager.map_difficulty,
world: isPvP ? 0 : KC3SortieManager.map_world,
mapnum: KC3SortieManager.map_num,
fleetnum: KC3SortieManager.fleetSent,
combined: PlayerManager.combinedFleet,
fleet1: PlayerManager.fleets[0].sortieJson(),
fleet2: PlayerManager.fleets[1].sortieJson(),
fleet3: PlayerManager.fleets[2].sortieJson(),
fleet4: PlayerManager.fleets[3].sortieJson(),
support1: isPvP ? 0 : KC3SortieManager.getSupportingFleet(false),
support2: isPvP ? 0 : KC3SortieManager.getSupportingFleet(true),
lbas: isPvP ? [] : KC3SortieManager.getWorldLandBases(KC3SortieManager.map_world, KC3SortieManager.map_num),
battles: [node.buildBattleDBData()]
};
return sortie;
};
const openBattleLogsWindow = function(data, isPopup){
try {
const url = "https://kc3kai.github.io/kancolle-replay/battleText.html#" + JSON.stringify(data);
const ref = window.open(url, "battle", (!isPopup ? undefined : "width=640,height=480,resizeable,scrollbars"));
if(ref && !ref.closed){
// Update hash with latest battle data even if window already opened
// this might not work for all browser versions as a vulnerability to bypass CORS
ref.location.replace(url);
// Switch focus to the window if possible
if(ref.focus) ref.focus();
}
} catch (e) {
console.warn("Failed to open battle logs", e);
}
};
// Open text-based battle replayer in new tab or popup window
$(".module.activity .map_world").addClass("hover").on("click", function(e){
const data = prepareBattleLogsData();
if(data) openBattleLogsWindow(data, e.altKey);
});
/* Expedition Planner
--------------------------------------------*/
$( ".module.activity .activity_expeditionPlanner .expres_greatbtn" )
.on("click",function() {
plannerIsGreatSuccess = !plannerIsGreatSuccess;
ExpedTabUpdateConfig();
NatsuiroListeners.UpdateExpeditionPlanner();
} );
/* Morale timers, and clickable to restart timer manually.
--------------------------------------------*/
checkAndRestartMoraleTimer();
$( ".module.status .status_morale" ).on("click",function() {
checkAndRestartMoraleTimer();
checkAndRestartUiTimer();
});
// Switching Activity Tabs
$(".module.activity .activity_tab").on("click", function(){
var target = $(this).data("target");
$(".module.activity .activity_tab").removeClass("active");
$(this).addClass("active");
$(".module.activity .activity_box").hide();
if(target === "expeditionPlanner"){
NatsuiroListeners.UpdateExpeditionPlanner();
}
$(".module.activity .activity_" + target).show();
});
$(".module.activity .activity_tab.active").trigger("click");
$(".module.activity .activity_dismissable").on("click", function(){
$("#atab_basic").trigger("click");
});
// Expedition Planner
$(".expedition_entry").on("click",function(){
selectedExpedition = parseInt( $(this).data("expId") );
var conf = ExpedTabValidateConfig(selectedExpedition);
plannerIsGreatSuccess = (conf.expedConf[selectedExpedition] || {}).greatSuccess || false;
ExpedTabUpdateConfig();
NatsuiroListeners.Fleet();
NatsuiroListeners.UpdateExpeditionPlanner();
});
// Fleet selection
$(".module.controls .fleet_num").on("click", function(){
$(".module.controls .fleet_num").removeClass("active");
$(".module.controls .fleet_rengo").removeClass("active");
$(".module.controls .fleet_lbas").removeClass("active");
$(this).addClass("active");
selectedFleet = parseInt( $(this).text(), 10);
ExpedTabApplyConfig();
NatsuiroListeners.Fleet();
NatsuiroListeners.UpdateExpeditionPlanner();
});
// Combined Fleet button
$(".module.controls .fleet_rengo").on("click", function(){
$(".module.controls .fleet_num").removeClass("active");
$(".module.controls .fleet_lbas").removeClass("active");
$(this).addClass("active");
selectedFleet = 5;
NatsuiroListeners.Fleet();
});
// LBAS button
$(".module.controls .fleet_lbas").on("click", function(){
$(".module.controls .fleet_num").removeClass("active");
$(".module.controls .fleet_rengo").removeClass("active");
$(this).addClass("active");
selectedFleet = 6;
NatsuiroListeners.Lbas();
});
// Toggle mini-bars under combined fleet ship list
$(".module.fleet .shiplist_combined").on("click", ".sship .ship_bars", function(){
if($(this).css("opacity") == "0"){
showCombinedFleetBars = true;
$(".module.fleet .sship .ship_bars").css("opacity", "1");
}else{
showCombinedFleetBars = false;
$(".module.fleet .sship .ship_bars").css("opacity", "0");
}
});
// Scrollable control buttons
$(".module.controls .scroll_btn").on("click", function(){
var buttonCount = $(".module.controls .control_btn").length;
var buttonSize = $(".module.controls .control_btn").outerWidth(true);
var containerSize = $(".module.controls .scrollable").outerWidth(true);
var maxLeft = buttonSize * (buttonCount - Math.floor(containerSize / buttonSize));
var currentLeft = $(".module.controls .scrollable").scrollLeft();
var goLeft = $(this).hasClass("scroll_left");
var newLeft = goLeft ?
Math.max(currentLeft - buttonSize, 0) :
Math.min(currentLeft + buttonSize, maxLeft);
$(".module.controls .scrollable").scrollLeft(newLeft);
$(".module.controls .scroll_left").toggleClass("disabled", newLeft <= 0);
$(".module.controls .scroll_right").toggleClass("disabled", newLeft >= maxLeft);
});
// Resize window to 1200x720
$(".module.controls .btn_resize").on("click", function(){
// Send fit-screen request to service to be forwarded to gameplay page
(new RMsg("service", "fitScreen", {
tabId: chrome.devtools.inspectedWindow.tabId
})).execute();
});
// Mute button
$(".module.controls .btn_mute").on("click", function(){
// Send toggle sound request to service to be forwarded to gameplay page
(new RMsg("service", "toggleSounds", {
tabId: chrome.devtools.inspectedWindow.tabId
},function(isMuted){
$(".module.controls .btn_mute img")
.attr("src", "../../../../assets/img/ui/mute{0}.png".format(isMuted ? "-x" : ""));
})).execute();
});
// Taiha Alert toggle button
$(".module.controls .btn_alert_toggle").on("click", function (){
if(critSound.paused) {
if($(this).hasClass("disabled")) return;
NatsuiroListeners.Fleet();
} else {
critSound.pause();
}
}).toggleClass("disabled", !ConfigManager.alert_taiha || !ConfigManager.alert_taiha_sound);
// Reload subtitle quotes
$(".module.controls .btn_reload_quotes").on("click", function(){
// TODO request latest quotes.json for current lang from remote repo
// Tell game screen tab use latest meta
(new RMsg("service", "reloadMeta", {
tabId: chrome.devtools.inspectedWindow.tabId,
type: "Quotes"
})).execute();
// TODO add UI response to show reloading status
});
// Reload meta of quests
$(".module.controls .btn_reload_quests").on("click", function(){
// TODO request latest quests.json for both EN and current lang from remote repo
KC3Meta.reloadQuests();
// Tell game screen tab use latest meta
(new RMsg("service", "reloadMeta", {
tabId: chrome.devtools.inspectedWindow.tabId,
type: "Quests"
})).execute();
// TODO add UI response to show reloading status
});
// Trigger initial selected fleet num
$(".module.controls .fleet_num.active").trigger("click");
// Initialize timer objects with bindings to their UI
KC3TimerManager.init([
$(".module.activity .expedition_1"),
$(".module.activity .expedition_2"),
$(".module.activity .expedition_3")
],
[
$(".module.activity .repair_1"),
$(".module.activity .repair_2"),
$(".module.activity .repair_3"),
$(".module.activity .repair_4")
],
[
$(".module.activity .build_1"),
$(".module.activity .build_2"),
$(".module.activity .build_3"),
$(".module.activity .build_4")
]);
// Restore build docks timer if panel reopened, not from game start
PlayerManager.setBuildDocksByCache();
// Update Timer UIs
checkAndRestartUiTimer();
// Devbuild: auto-activate dashboard while designing
// Activate();
// Start Network listener
KC3Network.initConfigs();
KC3Network.addGlobalListener(function(event, data){
if(isRunning || (["GameStart","HomeScreen","CatBomb"].indexOf(event)+1)){
if(typeof NatsuiroListeners[event] != "undefined"){
NatsuiroListeners[event](data);
} else {
console.warn("No event found for keyword", event);
}
}
});
KC3Network.listen();
// Get info of the inspected tab
(new RMsg("service", "getTabInfo", {
tabId: chrome.devtools.inspectedWindow.tabId
}, function(tabInfo){
localStorage.gameTabUrl = tabInfo.url;
errorReport.gameTabUrl = tabInfo.url;
try {
// if inspected tab is muted, update the mute icon
if(tabInfo.mutedInfo.muted){
$(".module.controls .btn_mute img").attr("src", "../../../../assets/img/ui/mute-x.png");
} else if(ConfigManager.mute_game_tab) {
// if not and mute on start setting enabled, try to mute it
const toggleTabSounds = function(expected) {
(new RMsg("service", "toggleSounds", {
tabId: chrome.devtools.inspectedWindow.tabId
}, function(isMuted){
$(".module.controls .btn_mute img")
.attr("src", "../../../../assets/img/ui/mute{0}.png".format(isMuted ? "-x" : ""));
if(typeof expected === "boolean" && isMuted !== expected)
toggleTabSounds();
})).execute();
};
// since Chromium m76?, muted tab but no audio actually played yet will still make sounds later,
// so polling tab info for audible state, mute the tab when the game actually begins to play audio.
// current polling timeout is 70 seconds, since will no audio played until game loaded, or if in-game music/SE is off.
const tabMutePollingTimeout = 70;
let tabMuteHandler = 0, tabMuteTimeout = 0;
const tabAudibleChecker = function() {
tabMuteTimeout += 1;
console.debug("Checking game tab audible for", tabMuteTimeout, "sec(s)");
(new RMsg("service", "getTabInfo", {
tabId: chrome.devtools.inspectedWindow.tabId
}, function(tab){
if(tab.audible) {
toggleTabSounds(true);
clearInterval(tabMuteHandler);
} else if(tabMuteTimeout >= tabMutePollingTimeout) {