-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
5488 lines (4814 loc) · 211 KB
/
Copy pathapp.js
File metadata and controls
5488 lines (4814 loc) · 211 KB
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
// ===== LOGGING SYSTEM =====
const LogLevel = {
DEBUG: 'debug',
INFO: 'info',
WARN: 'warn',
ERROR: 'error'
};
const SENSITIVE_IPC_KEYS = new Set([
'password',
'currentPassword',
'newPassword',
'confirmPassword',
'code',
'state',
'authorizationUrl',
'accessToken',
'access_token',
'refreshToken',
'refresh_token',
'token',
'sessionToken',
'session_token',
'userId',
'user_id',
'username',
'email',
'user',
]);
function sanitizeIpcValue(value) {
if (Array.isArray(value)) {
return value.map(sanitizeIpcValue);
}
if (!value || typeof value !== 'object') {
return value;
}
const sanitized = {};
for (const [key, innerValue] of Object.entries(value)) {
sanitized[key] = SENSITIVE_IPC_KEYS.has(key)
? '[redacted]'
: sanitizeIpcValue(innerValue);
}
return sanitized;
}
function sanitizeIpcPayload(command, payload) {
if (!payload || typeof payload !== 'object') return payload;
if (typeof command === 'string' && command.startsWith('Auth')) {
return sanitizeIpcValue(payload);
}
if (command === 'GetUiConfig' && Object.prototype.hasOwnProperty.call(payload, 'authState')) {
return {
...payload,
authState: sanitizeIpcValue(payload.authState)
};
}
return payload;
}
function sanitizeIpcEventData(event, data) {
if (event === 'AuthStateChanged') {
return {
authenticated: !!(data && data.authenticated),
provider: data && typeof data.provider === 'string' ? data.provider : null,
user: data && data.user ? '[redacted]' : null
};
}
return data;
}
const logger = {
_queue: [],
_initialized: false,
_uiLogging: true,
_ipcTracing: false,
async _sendToRust(level, message, context = null) {
if (!this._uiLogging) {
return false;
}
if (window.__LAUNCHER__) {
try {
await window.__LAUNCHER__.invoke("LogMessage", {
level,
message,
context: context ? JSON.stringify(context) : null
});
return true;
} catch (e) {
// Rust logging failed, will fall back to console
return false;
}
}
return false;
},
_formatMessage(level, message, context) {
const timestamp = new Date().toISOString();
const prefix = `[${timestamp}] [${level.toUpperCase()}]`;
if (context) {
return `${prefix} ${message} | ${JSON.stringify(context)}`;
}
return `${prefix} ${message}`;
},
async _log(level, message, context = null) {
// Try Rust first
const sentToRust = await this._sendToRust(level, message, context);
// Always log to console as well (for dev tools)
const formatted = this._formatMessage(level, message, context);
switch (level) {
case LogLevel.DEBUG:
console.debug(formatted);
break;
case LogLevel.INFO:
console.info(formatted);
break;
case LogLevel.WARN:
console.warn(formatted);
break;
case LogLevel.ERROR:
console.error(formatted);
break;
default:
console.log(formatted);
}
},
debug(message, context = null) {
this._log(LogLevel.DEBUG, message, context);
},
info(message, context = null) {
this._log(LogLevel.INFO, message, context);
},
warn(message, context = null) {
this._log(LogLevel.WARN, message, context);
},
error(message, context = null) {
this._log(LogLevel.ERROR, message, context);
},
// IPC-specific logging
ipcCall(command, args = null) {
if (!this._ipcTracing) return;
this._log(LogLevel.DEBUG, `IPC Call: JS → Rust`, {
command,
args: sanitizeIpcPayload(command, args)
});
},
ipcResult(command, result = null, error = null) {
if (!this._ipcTracing) return;
if (error) {
// Extract error message properly - handle Error objects, strings, and plain objects
var errorMsg = error;
if (error instanceof Error) {
errorMsg = error.message || error.toString();
} else if (typeof error === 'object' && error !== null) {
errorMsg = error.message || error.error || JSON.stringify(error);
}
this._log(LogLevel.ERROR, `IPC Error: ${command}`, { error: errorMsg });
} else {
this._log(LogLevel.DEBUG, `IPC Result: ${command}`, {
result: sanitizeIpcPayload(command, result)
});
}
},
ipcEvent(event, data = null) {
if (!this._ipcTracing) return;
this._log(LogLevel.DEBUG, `IPC Event: Rust → JS`, {
event,
data: sanitizeIpcEventData(event, data)
});
}
};
// ===== GLOBAL ERROR HANDLERS =====
function logGlobalError(details, errorType = "error") {
const message = details && (details.message || details.reason || details) || "Unknown error";
const stack = (details && (details.stack || (details.error && details.error.stack) || (details.reason && details.reason.stack))) || null;
const filename = details && details.filename;
const lineno = details && details.lineno;
const colno = details && details.colno;
// Log locally
logger.error("Global error", { message, stack, filename, lineno, colno });
// Forward to Rust for centralized error tracking
if (window.__LAUNCHER__ && typeof window.__LAUNCHER__.invoke === 'function') {
try {
window.__LAUNCHER__.invoke('LogMessage', {
level: 'error',
message: `[JS ${errorType}] ${message}`,
context: JSON.stringify({
stack: stack,
filename: filename,
lineno: lineno,
colno: colno,
type: errorType
})
}).catch(function() { /* Ignore IPC errors during error reporting */ });
} catch (e) {
// Ignore errors during error reporting to prevent infinite loops
}
}
}
function showUiCrashOverlay(message, details = {}) {
if (typeof document === "undefined") {
return;
}
const root = document.body || document.documentElement;
if (!root) {
return;
}
let overlay = document.getElementById("uiCrashOverlay");
if (!overlay) {
overlay = document.createElement("div");
overlay.id = "uiCrashOverlay";
overlay.setAttribute("role", "alertdialog");
overlay.setAttribute("aria-live", "assertive");
overlay.style.cssText = [
"position:fixed",
"inset:0",
"z-index:2147483647",
"display:flex",
"align-items:center",
"justify-content:center",
"padding:24px",
"background:rgba(10,10,15,0.96)",
"backdrop-filter:blur(10px)"
].join(";");
root.appendChild(overlay);
}
const safeMessage = String(message || "Unexpected launcher error");
const safeDetails = details && details.stack ? String(details.stack) : "";
overlay.innerHTML = `
<div style="width:min(560px,100%);background:#14141f;border:1px solid #252535;border-radius:16px;padding:24px;box-shadow:0 20px 60px rgba(0,0,0,0.45);color:#e8e8f0;font-family:Inter,'Segoe UI',sans-serif;">
<div style="font-size:20px;font-weight:700;margin-bottom:8px;">Launcher UI ran into a problem</div>
<div style="font-size:14px;line-height:1.6;color:#b8b8c8;margin-bottom:16px;">${safeMessage}</div>
<div style="font-size:13px;line-height:1.5;color:#8f8fa3;margin-bottom:20px;">You can safely reload the launcher UI. If the problem keeps happening, close and reopen the launcher.</div>
${safeDetails ? `<pre style="max-height:180px;overflow:auto;white-space:pre-wrap;background:#0f0f18;border:1px solid #1f1f2d;border-radius:10px;padding:12px;color:#9d9db3;font-size:12px;margin:0 0 20px;">${safeDetails}</pre>` : ""}
<div style="display:flex;gap:12px;justify-content:flex-end;">
<button id="uiCrashReloadBtn" style="border:none;border-radius:10px;padding:10px 16px;background:#7c5cff;color:white;font-weight:600;cursor:pointer;">Reload UI</button>
<button id="uiCrashCloseBtn" style="border:1px solid #2a2a38;border-radius:10px;padding:10px 16px;background:#181824;color:#e8e8f0;font-weight:600;cursor:pointer;">Close Launcher</button>
</div>
</div>
`;
overlay.querySelector("#uiCrashReloadBtn")?.addEventListener("click", () => {
requestReload();
});
overlay.querySelector("#uiCrashCloseBtn")?.addEventListener("click", () => {
closeWindow();
});
reportFatalFrontendProblem(message, {
errorType: details.errorType || "fatal-ui-problem",
stack: details.stack || null,
filename: details.filename || null,
line: details.line,
column: details.column
});
}
function reportFatalFrontendProblem(message, details = {}) {
if (!window.__LAUNCHER__ || typeof window.__LAUNCHER__.invoke !== "function") {
return Promise.resolve();
}
return window.__LAUNCHER__.invoke("ReportUiCrash", {
page: "main",
errorType: details.errorType || "fatal-ui-problem",
message: String(message || "Unexpected launcher UI error"),
stack: details.stack || null,
filename: details.filename || null,
line: Number.isInteger(details.line) ? details.line : null,
column: Number.isInteger(details.column) ? details.column : null
}).catch(function() {});
}
if (typeof window !== "undefined") {
// Global error handler for uncaught exceptions
window.addEventListener("error", (event) => {
const message = event.message || "Unexpected UI error";
logGlobalError({
message,
stack: event.error && event.error.stack,
filename: event.filename,
lineno: event.lineno,
colno: event.colno,
error: event.error
}, "uncaught-exception");
showUiCrashOverlay(message, {
errorType: "uncaught-exception",
stack: event.error && event.error.stack,
filename: event.filename,
line: event.lineno,
column: event.colno
});
});
// Unhandled promise rejection handler
window.addEventListener("unhandledrejection", (event) => {
const message = event.reason && (event.reason.message || String(event.reason)) || "Unexpected async UI error";
logGlobalError({
message,
stack: event.reason && event.reason.stack,
reason: event.reason
}, "unhandled-rejection");
showUiCrashOverlay(message, {
errorType: "unhandled-rejection",
stack: event.reason && event.reason.stack
});
});
// // Console error override to capture console.error calls
// const originalConsoleError = console.error;
// console.error = function(...args) {
// originalConsoleError.apply(console, args);
// // Forward significant console errors to Rust (avoid recursion by checking)
// if (args.length > 0 && !String(args[0]).includes('[IPC]')) {
// const message = args.map(arg => {
// if (typeof arg === 'object') {
// try { return JSON.stringify(arg); } catch { return String(arg); }
// }
// return String(arg);
// }).join(' ');
// if (window.__LAUNCHER__ && typeof window.__LAUNCHER__.invoke === 'function') {
// try {
// window.__LAUNCHER__.invoke('LogMessage', {
// level: 'error',
// message: '[JS console.error] ' + message.substring(0, 500),
// context: null
// }).catch(function() {});
// } catch (e) {}
// }
// }
// };
}
// ===== IPC WRAPPER WITH LOGGING =====
const ipcBridge = {
async invoke(command, args = null) {
logger.ipcCall(command, args);
if (!window.__LAUNCHER__) {
logger.warn(`IPC unavailable for command: ${command}`);
return null;
}
try {
const result = await window.__LAUNCHER__.invoke(command, args);
logger.ipcResult(command, result);
return result;
} catch (error) {
logger.ipcResult(command, null, error);
throw error;
}
},
on(event, handler) {
if (!window.__LAUNCHER__) {
logger.warn(`Cannot register event handler - IPC unavailable: ${event}`);
return;
}
window.__LAUNCHER__.on(event, (data) => {
logger.ipcEvent(event, data);
handler(data);
});
}
};
// ===== STATE MANAGEMENT =====
const AppState = {
STARTUP: 'startup',
READY: 'ready',
EULA_PENDING: 'eula_pending',
AUTH_PENDING: 'auth_pending',
CHECKING: 'checking_manifest',
UPDATE_AVAILABLE: 'update_available',
DOWNLOADING: 'downloading',
VERIFYING: 'verifying',
APPLYING: 'patching',
LAUNCH_READY: 'launch_ready',
LAUNCHING: 'launching',
MAINTENANCE: 'maintenance',
ERROR: 'error'
};
// ===== APPLICATION STATE =====
const state = {
current: AppState.READY,
isDownloading: false,
downloadPaused: false,
currentSlideIndex: 0,
currentTab: 'news',
currentLang: 'en',
currentTheme: 'dark',
sliderInterval: null,
sliderProgressInterval: null,
sliderPaused: false,
sliderProgressValue: 0,
slideDuration: 6000,
translations: {},
newsItems: [],
changelogItems: [],
plugins: [],
links: {},
serverOnline: false,
availableLanguages: ['en'],
version: '1.0.0',
gameVersion: null,
manifestVersion: null,
stage: 'production',
splashShownKey: null,
splashConfig: null,
popupNoticeShownKey: null,
popupNoticeConfig: null,
noticeShownKeys: new Set(),
maintenanceMode: false,
maintenanceMessage: null,
authConfig: null,
launcherUpdate: null,
launcherUpdateForced: false,
launcherUpdateCheckPending: false,
launcherUpdateCheckError: null,
authState: {
authenticated: false,
provider: null,
userId: null,
username: null,
email: null,
user: null
},
authModal: {
open: false,
mode: 'login',
oauthProvider: null,
awaitingCode: false,
authorizationUrl: null
},
startup: {
checkForUpdates: true,
minimizeToTray: false,
launchOnBoot: false
},
logging: {
uiLogging: true,
ipcTracing: false
},
hasSettingsManager: false,
};
// ===== MANIFEST LOADING OVERLAY =====
// Shown until the remote manifest fetch resolves (success, error, or skipped).
// Guards are idempotent — safe to call multiple times.
let _manifestOverlayDismissed = false;
function dismissManifestOverlay() {
if (_manifestOverlayDismissed) return;
_manifestOverlayDismissed = true;
const overlay = document.getElementById('manifestLoadingOverlay');
if (!overlay) return;
overlay.classList.add('hidden');
// Remove from layout after transition completes (250ms defined in CSS)
setTimeout(() => overlay.classList.add('gone'), 300);
}
function updateManifestOverlayStatus(key, fallback) {
if (_manifestOverlayDismissed) return;
const el = document.getElementById('manifestLoadingStatus');
if (el) el.textContent = t(key) || fallback;
}
function updateAuxButtons() {
const pauseResumeBtn = $('#pauseResumeBtn');
const pauseResumeIcon = $('#pauseResumeIcon');
const utilitiesBtn = $('#utilitiesBtn');
const isBusy =
state.current === AppState.CHECKING ||
state.current === AppState.DOWNLOADING ||
state.current === AppState.VERIFYING ||
state.current === AppState.APPLYING ||
state.current === AppState.LAUNCHING ||
state.current === AppState.EULA_PENDING ||
state.current === AppState.AUTH_PENDING;
if (pauseResumeBtn && pauseResumeIcon) {
const show = state.current === AppState.DOWNLOADING;
pauseResumeBtn.style.display = show ? '' : 'none';
if (show) {
const isPaused = !!state.downloadPaused;
pauseResumeBtn.disabled = false;
pauseResumeBtn.setAttribute('title', isPaused ? (t('button.resume') || 'Resume') : (t('button.pause') || 'Pause'));
pauseResumeBtn.setAttribute('data-tooltip', pauseResumeBtn.getAttribute('title'));
pauseResumeIcon.innerHTML = isPaused
? '<polygon points="5 3 19 12 5 21 5 3"/>'
: '<rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/>';
}
}
if (utilitiesBtn) {
utilitiesBtn.disabled = isBusy;
if (isBusy) {
const wrapper = $('#utilitiesWrapper');
if (wrapper) wrapper.classList.remove('open');
}
}
}
function updateGameSettingsItem() {
const item = $('#gameSettingsItem');
if (!item) return;
if (state.hasSettingsManager) {
item.classList.remove('folder-option-disabled');
} else {
item.classList.add('folder-option-disabled');
}
}
// ===== HELPER FUNCTIONS =====
function t(key, params = {}) {
const template = state.translations[key] || key;
return template.replace(/\{(\w+)\}/g, (_, k) =>
params[k] !== undefined ? params[k] : `{${k}}`
);
}
// Picks the localized value for `field` from item.i18n[currentLang], with
// base-language fallback (e.g. "de-AT" -> "de") and default to item[field].
function getLocalized(item, field) {
if (item.i18n) {
const lang = state.currentLang;
const exact = item.i18n[lang];
if (exact != null && exact[field] != null) return exact[field];
const base = lang.indexOf('-') !== -1 ? lang.split('-')[0] : null;
if (base) {
const baseEntry = item.i18n[base];
if (baseEntry != null && baseEntry[field] != null) return baseEntry[field];
}
}
const v = item[field];
return v != null ? v : '';
}
function tf(key, fallback, params = {}) {
const value = t(key, params);
return value === key ? fallback : value;
}
function launcherUpdateRequiredVersion() {
const update = state.launcherUpdate || {};
return update.minVersion || update.min_version || update.version || state.version;
}
function launcherUpdateRequiredStatus() {
const version = launcherUpdateRequiredVersion();
return tf(
"status.launcher_update_required",
`Launcher ${version} is required. Update to continue.`,
{ version }
);
}
function normalizeStateForForcedLauncherUpdate(nextState) {
if (!state.launcherUpdateForced) return nextState;
if (nextState === AppState.APPLYING || nextState === AppState.ERROR) return nextState;
return AppState.UPDATE_AVAILABLE;
}
function $(selector) {
return document.querySelector(selector);
}
function $$(selector) {
return document.querySelectorAll(selector);
}
function setText(id, value) {
const el = document.getElementById(id);
if (el) el.textContent = value;
}
function formatErrorMessage(error) {
if (!error) return "Unknown error";
if (typeof error === 'string') return error;
if (error instanceof Error) return error.message || error.toString();
if (typeof error === 'object') {
if (typeof error.error === 'string') return error.error;
if (error.error) return formatErrorMessage(error.error);
if (typeof error.message === 'string') return error.message;
if (typeof error.reason === 'string') return error.reason;
if (typeof error.code === 'string' || typeof error.code === 'number') return String(error.code);
try {
const serialized = JSON.stringify(error);
return serialized === '{}' ? "Unknown error" : serialized;
} catch {
// ignore
}
}
const fallback = String(error);
return fallback === "[object Object]" ? "Unknown error" : fallback;
}
function escapeHtml(value) {
return String(value ?? '')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function buildCdnRegionOptions(selectedRegion, cdnStatus) {
const selectedCdnRegion = selectedRegion || 'auto';
const cdnRegions = Array.from(new Set(
(Array.isArray(cdnStatus) ? cdnStatus : [])
.map(cdn => typeof cdn.region === 'string' ? cdn.region.trim() : '')
.filter(Boolean)
));
if (selectedCdnRegion !== 'auto' && !cdnRegions.includes(selectedCdnRegion)) {
cdnRegions.push(selectedCdnRegion);
}
cdnRegions.sort((a, b) => a.localeCompare(b));
return [
`<option value="auto" ${selectedCdnRegion === 'auto' ? 'selected' : ''}>${escapeHtml(t("settings.cdn_auto") || "Auto")}</option>`,
...cdnRegions.map(region => {
const safeRegion = escapeHtml(region);
return `<option value="${safeRegion}" ${region === selectedCdnRegion ? 'selected' : ''}>${safeRegion}</option>`;
})
].join('');
}
function formatBytes(bytes) {
if (bytes === 0) return "0 B";
const k = 1024;
const sizes = ["B", "KB", "MB", "GB"];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
}
function formatSpeed(bytesPerSec) {
return formatBytes(bytesPerSec) + "/s";
}
function formatETA(seconds) {
if (!seconds || seconds <= 0) return "--";
if (seconds < 60) return `${Math.round(seconds)}s`;
if (seconds < 3600) return `${Math.floor(seconds / 60)}m ${Math.round(seconds % 60)}s`;
return `${Math.floor(seconds / 3600)}h ${Math.floor((seconds % 3600) / 60)}m`;
}
// ===== WINDOW CONTROLS =====
function minimizeWindow() {
ipcBridge.invoke("MinimizeWindow").catch(err => logger.error("MinimizeWindow failed", { error: err }));
}
function closeWindow() {
ipcBridge.invoke("CloseWindow").catch(() => window.close());
}
// ===== THEME MANAGEMENT =====
function getSystemThemePreference() {
try {
if (typeof window !== 'undefined' && typeof window.matchMedia === 'function') {
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
} catch (err) {
logger?.debug?.('Could not read system theme preference', { error: String(err) });
}
return 'dark';
}
function resolveThemePreference(theme) {
return theme === 'light' || theme === 'dark' ? theme : getSystemThemePreference();
}
function applyTheme(theme) {
const resolvedTheme = resolveThemePreference(theme);
const isDark = resolvedTheme === 'dark';
document.body.classList.toggle('light-theme', !isDark);
state.currentTheme = resolvedTheme;
logger.debug("Theme applied", { theme: resolvedTheme });
}
function toggleTheme() {
const newTheme = state.currentTheme === 'dark' ? 'light' : 'dark';
applyTheme(newTheme);
// Save theme preference via settings
ipcBridge.invoke("SaveSettings", { settings: { theme: newTheme } })
.then(() => {
logger.info("Theme preference saved", { theme: newTheme });
})
.catch(err => {
logger.warn("Failed to save theme preference", { error: err });
});
}
async function loadThemePreference() {
applyTheme(getSystemThemePreference());
try {
const settings = await ipcBridge.invoke("GetSettings");
applyTheme(settings && settings.theme);
} catch (err) {
logger.debug("Could not load theme preference, using system default", { error: err });
}
}
// ===== NAVIGATION =====
function openLink(type) {
if (typeof type !== 'string' || !type.trim()) {
logger.warn('openLink called with invalid type');
return;
}
const normalizedType = type.toLowerCase();
if (normalizedType === 'register' && state.authConfig) {
const endpoints = state.authConfig.endpoints || {};
if (state.authState.authenticated) {
if (endpoints.changePasswordUrl) {
showAuthModal('change-password');
}
return;
}
if (endpoints.registerUrl) {
showAuthModal('register');
}
return;
}
const url = state.links[normalizedType];
if (!url) {
logger.warn(`No URL configured for link type: ${type}`);
showToast(t("error.link_not_configured") || "Link not available", "warning");
return;
}
openExternalUrl(url)
.then(() => {
logger.debug(`Opened external URL: ${type}`);
})
.catch((err) => {
logger.error(`Failed to open URL: ${err}`);
showToast(t("error.open_url_failed") || "Could not open link", "error");
});
}
async function openExternalUrl(url) {
if (!isValidUrl(url)) {
throw new Error(t("error.invalid_url") || "Invalid URL");
}
try {
await ipcBridge.invoke("OpenExternalUrl", { url });
} catch (err) {
logger.warn(`Failed to open URL via IPC, trying fallback: ${err}`);
const newWindow = window.open(url, "_blank", "noopener,noreferrer");
if (!newWindow) {
throw new Error(t("error.popup_blocked") || "Popup blocked - please allow popups");
}
}
}
function isValidUrl(url) {
if (typeof url !== 'string') return false;
try {
const parsed = new URL(url);
return ['http:', 'https:', 'mailto:'].includes(parsed.protocol);
} catch {
return false;
}
}
function isValidHttpUrl(url) {
if (typeof url !== 'string') return false;
try {
const parsed = new URL(url);
return parsed.protocol === 'http:' || parsed.protocol === 'https:';
} catch {
return false;
}
}
function normalizeSplashConfig(raw) {
if (!raw || typeof raw !== 'object') return null;
const enabled = raw.enabled === true;
if (!enabled) return { enabled: false };
const title = typeof raw.title === 'string' ? raw.title.trim() : '';
const message = typeof raw.message === 'string' ? raw.message.trim() : '';
const imageUrl = isValidHttpUrl(raw.imageUrl) ? raw.imageUrl : null;
const ctaLabel = typeof raw.ctaLabel === 'string' ? raw.ctaLabel.trim() : '';
const ctaUrl = isValidUrl(raw.ctaUrl) ? raw.ctaUrl : null;
const durationSeconds = Number.isFinite(raw.durationSeconds)
? Math.max(1, Math.min(60, Math.floor(raw.durationSeconds)))
: 3;
let dismissible = raw.dismissible !== false;
if (!dismissible && !(ctaLabel && ctaUrl)) {
dismissible = true;
}
if (!title && !message && !imageUrl) return null;
return {
enabled,
title,
message,
imageUrl,
ctaLabel,
ctaUrl,
dismissible,
durationSeconds
};
}
function normalizePopupNoticeConfig(raw) {
if (!raw || typeof raw !== 'object') return null;
const enabled = raw.enabled === true;
if (!enabled) return { enabled: false };
const imageUrl = isValidHttpUrl(raw.imageUrl) ? raw.imageUrl : null;
if (!imageUrl) return null;
const imageAlt = typeof raw.imageAlt === 'string' ? raw.imageAlt.trim() : '';
const ctaLabel = typeof raw.ctaLabel === 'string' ? raw.ctaLabel.trim() : '';
const ctaUrl = isValidUrl(raw.ctaUrl) ? raw.ctaUrl : null;
let dismissible = raw.dismissible !== false;
if (!dismissible && !(ctaLabel && ctaUrl)) {
dismissible = true;
}
return {
enabled,
imageUrl,
imageAlt,
ctaLabel,
ctaUrl,
dismissible
};
}
function getSplashKey(splash, manifestVersion) {
const versionKey = typeof manifestVersion === 'string' && manifestVersion.trim()
? manifestVersion.trim()
: 'unversioned';
return `${versionKey}:${JSON.stringify({
title: splash.title,
message: splash.message,
imageUrl: splash.imageUrl,
durationSeconds: splash.durationSeconds,
ctaLabel: splash.ctaLabel,
ctaUrl: splash.ctaUrl
})}`;
}
function getPopupNoticeKey(popupNotice, manifestVersion) {
const versionKey = typeof manifestVersion === 'string' && manifestVersion.trim()
? manifestVersion.trim()
: 'unversioned';
return `${versionKey}:${JSON.stringify({
imageUrl: popupNotice.imageUrl,
imageAlt: popupNotice.imageAlt,
ctaLabel: popupNotice.ctaLabel,
ctaUrl: popupNotice.ctaUrl
})}`;
}
function applySplashConfig(raw, manifestVersion) {
const splash = normalizeSplashConfig(raw);
if (!splash || !splash.enabled) {
state.splashConfig = null;
state.splashShownKey = null;
hideSplash();
return;
}
splash.splashKey = getSplashKey(splash, manifestVersion);
state.splashConfig = splash;
}
function applyPopupNoticeConfig(raw, manifestVersion) {
const popupNotice = normalizePopupNoticeConfig(raw);
if (!popupNotice || !popupNotice.enabled) {
state.popupNoticeConfig = null;
state.popupNoticeShownKey = null;
hidePopupNotice();
return;
}
popupNotice.popupNoticeKey = getPopupNoticeKey(popupNotice, manifestVersion);
state.popupNoticeConfig = popupNotice;
}
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function showSplash(config, splashKey) {
if (!config) return;
const overlay = renderSplashOverlay(config);
overlay.classList.add('visible');
state.splashShownKey = splashKey || getSplashKey(config);
}
async function showLaunchSplashBeforeGameStart() {
const splash = state.splashConfig;
if (!splash || !splash.enabled || state.splashShownKey === splash.splashKey) {
return false;
}
showSplash(splash, splash.splashKey);
await delay(splash.durationSeconds * 1000);
hideSplash();
return true;
}
function hideSplash() {
const overlay = document.getElementById('splashOverlay');
if (overlay) {
overlay.classList.remove('visible');
}
}
function renderSplashOverlay(config) {
let overlay = document.getElementById('splashOverlay');
if (!overlay) {
overlay = document.createElement('div');
overlay.id = 'splashOverlay';
overlay.className = 'splash-overlay';
document.body.appendChild(overlay);
}
overlay.innerHTML = '';
const card = document.createElement('div');
card.className = 'splash-card';
if (!config.imageUrl) {
card.classList.add('no-media');
}
if (config.imageUrl) {
const media = document.createElement('div');
media.className = 'splash-media';
const img = document.createElement('img');
img.alt = config.title || t("ui.aria_splash");
img.src = config.imageUrl;
media.appendChild(img);
card.appendChild(media);
}
const body = document.createElement('div');
body.className = 'splash-body';
if (config.title) {
const title = document.createElement('h2');
title.className = 'splash-title';
title.textContent = config.title;
body.appendChild(title);
}
if (config.message) {
const message = document.createElement('p');
message.className = 'splash-message';
message.textContent = config.message;
body.appendChild(message);
}
const actions = document.createElement('div');
actions.className = 'splash-actions';
if (config.ctaUrl && config.ctaLabel) {
const ctaBtn = document.createElement('button');
ctaBtn.className = 'btn btn-primary';
ctaBtn.type = 'button';
ctaBtn.textContent = config.ctaLabel;