Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
4991 lines (4269 loc) · 155 KB
/
Copy pathapp.js
File metadata and controls
4991 lines (4269 loc) · 155 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
// --- Icon Image Support ---
function setupIconImageInput() {
const fileInput = byId("app-icon-image");
const browseBtn = byId("app-icon-image-btn");
const extractBtn = byId("app-icon-extract-btn");
const preview = byId("app-icon-image-preview");
const removeBtn = byId("app-icon-image-remove");
const dropzone = byId("app-icon-dropzone");
const iconText = byId("app-icon");
let imageDataUrl = null;
function updatePreview() {
if (imageDataUrl) {
preview.style.backgroundImage = `url('${imageDataUrl}')`;
preview.style.display = "inline-block";
removeBtn.style.display = "inline-block";
iconText.style.display = "none";
} else {
preview.style.backgroundImage = "none";
preview.style.display = "none";
removeBtn.style.display = "none";
iconText.style.display = "inline-block";
}
}
function setImageFromFile(file) {
if (!file || !file.type.startsWith("image/")) {
return;
}
const reader = new FileReader();
reader.onload = (ev) => {
imageDataUrl = ev.target.result;
updatePreview();
};
reader.readAsDataURL(file);
}
browseBtn.addEventListener("click", () => fileInput.click());
extractBtn.addEventListener("click", async () => {
const appPath = byId("app-path").value.trim();
if (!appPath) {
showToast("Please select an executable file first.", "warning");
return;
}
if (!appPath.toLowerCase().endsWith(".exe")) {
showToast("Icon extraction only works for .exe files.", "warning");
return;
}
if (!isDesktop) {
showToast("Icon extraction is only available in desktop mode.", "warning");
return;
}
extractBtn.disabled = true;
extractBtn.textContent = "Extracting...";
try {
const iconDataUrl = await window.launcherAPI.extractIcon(appPath);
if (iconDataUrl) {
imageDataUrl = iconDataUrl;
updatePreview();
showToast("Icon extracted successfully!", "success");
} else {
showToast("Failed to extract icon from the executable.", "error");
}
} catch (error) {
console.error("Icon extraction error:", error);
showToast("Error extracting icon: " + error.message, "error");
} finally {
extractBtn.disabled = false;
extractBtn.textContent = "Extract from EXE";
}
});
fileInput.addEventListener("change", (e) => {
const file = e.target.files[0];
setImageFromFile(file);
});
removeBtn.addEventListener("click", () => {
imageDataUrl = null;
fileInput.value = "";
updatePreview();
});
// Drag and drop
dropzone.addEventListener("dragover", (e) => {
e.preventDefault();
dropzone.style.borderColor = "#ff7a1a";
});
dropzone.addEventListener("dragleave", (e) => {
e.preventDefault();
dropzone.style.borderColor = "#aaa";
});
dropzone.addEventListener("drop", (e) => {
e.preventDefault();
dropzone.style.borderColor = "#aaa";
const file = e.dataTransfer.files[0];
setImageFromFile(file);
});
// Save/Load integration
return {
getImageData: () => imageDataUrl,
setImageData: (dataUrl) => {
imageDataUrl = dataUrl;
updatePreview();
},
clear: () => {
imageDataUrl = null;
updatePreview();
}
};
}
let iconImageInput = null;
// --- Context Menu ---
let contextMenuVisible = false;
function showContextMenu(x, y) {
const menu = byId("context-menu");
menu.style.left = `${x}px`;
menu.style.top = `${y}px`;
menu.classList.remove("hidden");
menu.setAttribute("aria-hidden", "false");
contextMenuVisible = true;
}
function hideContextMenu() {
const menu = byId("context-menu");
menu.classList.add("hidden");
menu.setAttribute("aria-hidden", "true");
contextMenuVisible = false;
}
function isContextMenuTarget(element) {
return element.closest("#context-menu") !== null;
}
document.addEventListener("DOMContentLoaded", () => {
iconImageInput = setupIconImageInput();
// Context menu - right-click on empty areas
document.addEventListener("contextmenu", (e) => {
const target = e.target;
const isAppTile = target.closest(".app-tile");
const isButton = target.closest("button");
const isInput = target.closest("input");
const isModal = target.closest(".modal");
const isContextMenu = isContextMenuTarget(target);
if (isAppTile || isButton || isInput || isModal || isContextMenu) {
return;
}
e.preventDefault();
showContextMenu(e.clientX, e.clientY);
});
// Dismiss context menu on click outside
document.addEventListener("click", (e) => {
if (contextMenuVisible && !isContextMenuTarget(e.target)) {
hideContextMenu();
}
});
// Dismiss context menu on ESC
document.addEventListener("keydown", (e) => {
if (e.key === "Escape" && contextMenuVisible) {
hideContextMenu();
}
});
// Context menu - Edit Apps button
byId("ctx-open-settings").addEventListener("click", async () => {
hideContextMenu();
state.settingsTab = "profiles";
await openSettingsModal();
});
// Top bar profile dropdown
byId("profile-dropdown-btn").addEventListener("click", (e) => {
e.stopPropagation();
toggleProfileDropdown();
});
// Top bar theme dropdown
byId("theme-dropdown-btn").addEventListener("click", (e) => {
e.stopPropagation();
toggleThemeDropdown();
});
// Dismiss profile dropdown on click outside
document.addEventListener("click", (e) => {
if (profileDropdownVisible && !e.target.closest(".profile-dropdown-wrapper")) {
hideProfileDropdown();
}
if (themeDropdownVisible && !e.target.closest(".theme-dropdown-wrapper")) {
hideThemeDropdown();
}
});
// Dismiss dropdowns on ESC
document.addEventListener("keydown", (e) => {
if (e.key === "Escape") {
if (profileDropdownVisible) hideProfileDropdown();
if (themeDropdownVisible) hideThemeDropdown();
}
});
});
const defaultConfig = {
title: "Forge",
subtitle: "",
persistToTray: false,
startupOnBoot: false,
globalHotkey: "",
settingsPinEnabled: false,
settingsPinHash: "",
tileSizePreset: "comfortable",
tileSizeCustom: {
minWidth: 190,
minHeight: 150
},
showTileTips: true,
theme: {
bg1: "#1a0f08",
bg2: "#3a2014",
accent: "#ff7a1a",
text: "#f7eee3",
hover: "#ffb167"
},
themePresets: [
{
id: "obsidian-steelblue",
name: "Obsidian Steel Blue",
theme: {
bg1: "#181c20",
bg2: "#232a32",
accent: "#4682b4",
text: "#f8f8f2",
hover: "#6fa3d9"
}
},
{
id: "minimalist",
name: "Minimalist",
theme: {
bg1: "#1a1a1a",
bg2: "#262626",
accent: "#7a9b8f",
text: "#c8c8c8",
hover: "#8fab9f"
}
}
],
templates: [],
apps: [
{
name: "Example Web App",
type: "web",
icon: "🌐",
iconImage: null,
description: "A sample web target",
url: "https://example.com"
}
],
profiles: [
{
id: "default",
name: "Default",
apps: [
{
name: "Example Web App",
type: "web",
icon: "🌐",
iconImage: null,
description: "A sample web target",
url: "https://example.com"
}
]
}
],
activeProfileId: "default"
};
const CATEGORY_FILTER_ALL = "__all__";
const CATEGORY_FILTER_UNCATEGORIZED = "__uncategorized__";
const CATEGORY_FILTER_RECENT = "__recent__";
const CATEGORY_FILTER_MOST_USED = "__mostused__";
const TAG_FILTER_NONE = "__notag__";
// App tag color palette
const APP_TAG_COLORS = [
{ id: "red", name: "Red", bg: "rgba(239, 68, 68, 0.15)", border: "#ef4444" },
{ id: "orange", name: "Orange", bg: "rgba(249, 115, 22, 0.15)", border: "#f97316" },
{ id: "yellow", name: "Yellow", bg: "rgba(234, 179, 8, 0.15)", border: "#eab308" },
{ id: "green", name: "Green", bg: "rgba(34, 197, 94, 0.15)", border: "#22c55e" },
{ id: "blue", name: "Blue", bg: "rgba(59, 130, 246, 0.15)", border: "#3b82f6" },
{ id: "purple", name: "Purple", bg: "rgba(168, 85, 247, 0.15)", border: "#a855f7" },
{ id: "pink", name: "Pink", bg: "rgba(236, 72, 153, 0.15)", border: "#ec4899" },
{ id: "gray", name: "Gray", bg: "rgba(107, 114, 128, 0.15)", border: "#6b7280" }
];
// Health check state — runtime only, never persisted.
const healthBroken = new Set();
let healthCheckGen = 0;
function isAppBroken(app) {
return app.type === "local" && healthBroken.has(getTelemetryKey(app));
}
async function runHealthChecks() {
if (!isDesktop) return;
const gen = ++healthCheckGen;
healthBroken.clear();
const apps = getActiveApps();
const localApps = apps.filter((a) => a.type === "local" && a.path);
await Promise.all(localApps.map(async (app) => {
const result = await window.launcherAPI.validateLocalPath(app.path);
if (gen !== healthCheckGen) return;
if (!result?.ok) {
healthBroken.add(getTelemetryKey(app));
}
}));
if (gen !== healthCheckGen) return;
renderApps();
}
function getTelemetryKey(app) {
const base = app.path || app.url || app.id || app.steamId || "";
return `${app.type || "web"}:${(app.name || "").toLowerCase()}:${base}`;
}
function getAppTelemetry(app) {
const telemetry = state.config.appTelemetry;
if (!telemetry) return null;
return telemetry[getTelemetryKey(app)] || null;
}
function getOrCreateAppTelemetry(app) {
if (!state.config.appTelemetry) {
state.config.appTelemetry = {};
}
const key = getTelemetryKey(app);
const existing = state.config.appTelemetry[key] || {};
const rec = {
launchCount: existing.launchCount || 0,
lastLaunched: existing.lastLaunched || null,
lastError: existing.lastError || "",
lastFailedAt: existing.lastFailedAt || null
};
state.config.appTelemetry[key] = rec;
return rec;
}
function recordLaunch(app) {
const rec = getOrCreateAppTelemetry(app);
rec.launchCount = (rec.launchCount || 0) + 1;
rec.lastLaunched = new Date().toISOString();
persistConfig();
}
function recordLaunchFailure(app, errorMessage) {
const rec = getOrCreateAppTelemetry(app);
rec.lastError = String(errorMessage || "Unknown launch failure");
rec.lastFailedAt = new Date().toISOString();
persistConfig();
}
function clearLaunchFailure(app) {
const telemetry = getAppTelemetry(app);
if (!telemetry) {
return;
}
if (telemetry.lastError || telemetry.lastFailedAt) {
telemetry.lastError = "";
telemetry.lastFailedAt = null;
persistConfig();
}
}
const state = {
config: structuredClone(defaultConfig),
editingAppIndex: null,
searchQuery: "",
categoryFilter: CATEGORY_FILTER_ALL,
settingsTab: "general",
selectedThemePresetId: "",
pendingImport: null,
pendingLaunchApp: null,
selectedAppIndices: new Set()
};
const isDesktop = Boolean(window.launcherAPI);
let pendingSettingsPinResolver = null;
const SETTINGS_PIN_MAX_ATTEMPTS = 5;
const SETTINGS_PIN_LOCKOUT_MS = 30_000;
let settingsPinFailedAttempts = 0;
let settingsPinLockoutUntil = 0;
let settingsPinLockoutTimer = null;
let pendingPromptResolver = null;
let pendingPromptFocusTimer = null;
let promptReturnFocusElement = null;
let commandPaletteSelectionIndex = 0;
let commandPaletteReturnFocusElement = null;
let appHealthRefreshToken = 0;
let currentHotkeyRecording = null;
async function hashPin(pin) {
const text = String(pin || "").trim();
const buffer = new TextEncoder().encode(text);
const digest = await crypto.subtle.digest("SHA-256", buffer);
return Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, "0")).join("");
}
async function verifySettingsPin(pin) {
if (!state.config.settingsPinHash) {
return false;
}
const hash = await hashPin(pin);
return hash === state.config.settingsPinHash;
}
function getSettingsPinLockoutRemainingMs() {
return Math.max(0, settingsPinLockoutUntil - Date.now());
}
function isSettingsPinLockedOut() {
return getSettingsPinLockoutRemainingMs() > 0;
}
function stopSettingsPinLockoutTicker() {
if (settingsPinLockoutTimer) {
clearInterval(settingsPinLockoutTimer);
settingsPinLockoutTimer = null;
}
}
function updateSettingsPinModalState(errorText = "") {
const input = byId("settings-pin-input");
const unlockButton = byId("unlock-settings-pin");
const error = byId("settings-pin-error");
if (!input || !unlockButton || !error) {
return;
}
if (isSettingsPinLockedOut()) {
const seconds = Math.ceil(getSettingsPinLockoutRemainingMs() / 1000);
input.disabled = true;
unlockButton.disabled = true;
error.textContent = `Too many failed attempts. Try again in ${seconds}s.`;
error.classList.remove("hidden");
return;
}
input.disabled = false;
unlockButton.disabled = false;
if (errorText) {
error.textContent = errorText;
error.classList.remove("hidden");
} else {
error.classList.add("hidden");
}
}
function startSettingsPinLockoutTicker() {
stopSettingsPinLockoutTicker();
updateSettingsPinModalState();
settingsPinLockoutTimer = setInterval(() => {
if (!isSettingsPinLockedOut()) {
stopSettingsPinLockoutTicker();
}
updateSettingsPinModalState();
}, 250);
}
const TILE_SIZE_PRESETS = {
compact: { minWidth: "132px", minHeight: "108px" },
comfortable: { minWidth: "170px", minHeight: "136px" },
large: { minWidth: "228px", minHeight: "170px" }
};
const TILE_SIZE_LIMITS = {
minWidth: { min: 120, max: 280 },
minHeight: { min: 100, max: 220 }
};
function normalizeTileSizePreset(value) {
const preset = String(value || "").toLowerCase();
return TILE_SIZE_PRESETS[preset] || preset === "custom" ? preset : "comfortable";
}
function clampNumber(value, min, max, fallback) {
const num = Number(value);
if (!Number.isFinite(num)) {
return fallback;
}
return Math.min(Math.max(Math.round(num), min), max);
}
function normalizeTileSizeCustom(value) {
const source = value || {};
return {
minWidth: clampNumber(
source.minWidth,
TILE_SIZE_LIMITS.minWidth.min,
TILE_SIZE_LIMITS.minWidth.max,
defaultConfig.tileSizeCustom.minWidth
),
minHeight: clampNumber(
source.minHeight,
TILE_SIZE_LIMITS.minHeight.min,
TILE_SIZE_LIMITS.minHeight.max,
defaultConfig.tileSizeCustom.minHeight
)
};
}
function syncCustomTileSizeUI() {
const panel = byId("tile-size-custom-controls");
const widthInput = byId("cfg-tile-min-width");
const heightInput = byId("cfg-tile-min-height");
const widthValue = byId("cfg-tile-min-width-value");
const heightValue = byId("cfg-tile-min-height-value");
const custom = normalizeTileSizeCustom(state.config.tileSizeCustom);
state.config.tileSizeCustom = custom;
if (widthInput) {
widthInput.value = String(custom.minWidth);
}
if (heightInput) {
heightInput.value = String(custom.minHeight);
}
if (widthValue) {
widthValue.textContent = `${custom.minWidth}px`;
}
if (heightValue) {
heightValue.textContent = `${custom.minHeight}px`;
}
if (panel) {
panel.classList.toggle("hidden", normalizeTileSizePreset(state.config.tileSizePreset) !== "custom");
}
}
function applyTileSizePreset(value) {
const preset = normalizeTileSizePreset(value);
const custom = normalizeTileSizeCustom(state.config.tileSizeCustom);
const size = preset === "custom"
? { minWidth: `${custom.minWidth}px`, minHeight: `${custom.minHeight}px` }
: TILE_SIZE_PRESETS[preset];
const root = document.documentElement;
root.style.setProperty("--tile-min", size.minWidth);
root.style.setProperty("--tile-min-height", size.minHeight);
state.config.tileSizePreset = preset;
state.config.tileSizeCustom = custom;
syncCustomTileSizeUI();
}
function normalizeHotkeyInput(raw) {
const parts = String(raw || "")
.split("+")
.map((part) => part.trim())
.filter(Boolean);
if (!parts.length) {
return "";
}
const normalized = parts.map((part) => {
const lower = part.toLowerCase();
if (lower === "ctrl" || lower === "control" || lower === "cmdorctrl") {
return "CommandOrControl";
}
if (lower === "alt" || lower === "option") {
return "Alt";
}
if (lower === "shift") {
return "Shift";
}
if (lower === "meta" || lower === "win" || lower === "super" || lower === "command") {
return "Super";
}
if (lower === "space" || lower === "spacebar") {
return "Space";
}
if (/^f\d{1,2}$/i.test(part)) {
return part.toUpperCase();
}
if (part.length === 1) {
return part.toUpperCase();
}
return part;
});
const unique = [];
normalized.forEach((part) => {
if (!unique.includes(part)) {
unique.push(part);
}
});
const modifiers = ["CommandOrControl", "Alt", "Shift", "Super"];
const orderedModifiers = modifiers.filter((key) => unique.includes(key));
const primary = unique.find((part) => !modifiers.includes(part));
if (!primary) {
return "";
}
return [...orderedModifiers, primary].join("+");
}
function acceleratorFromKeyEvent(event) {
const isModifierOnly = ["Control", "Shift", "Alt", "Meta"].includes(event.key);
if (isModifierOnly) {
return "";
}
let primary = "";
if (event.key === " ") {
primary = "Space";
} else if (/^F\d{1,2}$/.test(event.key)) {
primary = event.key.toUpperCase();
} else if (event.key.length === 1) {
primary = event.key.toUpperCase();
} else {
const keyMap = {
Enter: "Enter",
Escape: "Esc",
Tab: "Tab",
Backspace: "Backspace",
Delete: "Delete",
Insert: "Insert",
Home: "Home",
End: "End",
PageUp: "PageUp",
PageDown: "PageDown",
ArrowUp: "Up",
ArrowDown: "Down",
ArrowLeft: "Left",
ArrowRight: "Right"
};
primary = keyMap[event.key] || "";
}
if (!primary) {
return "";
}
const parts = [];
if (event.ctrlKey || event.metaKey) {
parts.push("CommandOrControl");
}
if (event.altKey) {
parts.push("Alt");
}
if (event.shiftKey) {
parts.push("Shift");
}
// Keep accidental single-key global shortcuts from being registered.
if (!parts.length) {
return "";
}
parts.push(primary);
return parts.join("+");
}
function createProfileId() {
return `profile-${Date.now()}-${Math.floor(Math.random() * 1000)}`;
}
function normalizeThemePresets(rawPresets) {
if (!Array.isArray(rawPresets)) {
return [];
}
const seenIds = new Set();
const output = [];
rawPresets.forEach((preset, index) => {
if (output.length >= 3) {
return;
}
const idBase = preset?.id ? String(preset.id) : `theme-preset-${index + 1}`;
const id = seenIds.has(idBase) ? `${idBase}-${index + 1}` : idBase;
seenIds.add(id);
const legacyTheme = {
bg1: preset?.bg1,
bg2: preset?.bg2,
accent: preset?.accent,
text: preset?.text,
hover: preset?.hover
};
const sourceTheme = (preset?.theme && typeof preset.theme === "object")
? preset.theme
: legacyTheme;
output.push({
id,
name: preset?.name ? String(preset.name) : `Theme ${index + 1}`,
theme: {
...defaultConfig.theme,
...(sourceTheme || {})
}
});
});
return output;
}
function normalizeConfigObject(config) {
const fallbackApps = Array.isArray(config.apps) ? config.apps : [];
let profiles = Array.isArray(config.profiles) ? config.profiles : [];
if (!profiles.length) {
profiles = [{ id: "default", name: "Default", apps: fallbackApps }];
}
profiles = profiles.map((profile, index) => ({
id: profile?.id ? String(profile.id) : createProfileId(),
name: profile?.name ? String(profile.name) : `Profile ${index + 1}`,
apps: Array.isArray(profile?.apps) ? profile.apps : []
}));
let activeProfileId = config.activeProfileId;
if (!profiles.some((profile) => profile.id === activeProfileId)) {
activeProfileId = profiles[0].id;
}
const activeProfile = profiles.find((profile) => profile.id === activeProfileId) || profiles[0];
return {
...config,
profiles,
activeProfileId,
apps: [...activeProfile.apps],
tileSizePreset: normalizeTileSizePreset(config.tileSizePreset),
tileSizeCustom: normalizeTileSizeCustom(config.tileSizeCustom),
themePresets: normalizeThemePresets(config.themePresets)
};
}
function normalizeConfig() {
state.config = normalizeConfigObject(state.config);
}
function getActiveProfile() {
return state.config.profiles.find((profile) => profile.id === state.config.activeProfileId) || state.config.profiles[0];
}
function getActiveApps() {
return getActiveProfile().apps;
}
function syncAppsMirror() {
state.config.apps = [...getActiveApps()];
}
async function persistConfig() {
syncAppsMirror();
if (isDesktop) {
await window.launcherAPI.saveConfig(JSON.stringify(state.config));
return;
}
localStorage.setItem("forge-launcher-settings", JSON.stringify(state.config));
}
function byId(id) {
return document.getElementById(id);
}
function showImportPreviewModal(visible) {
const modal = byId("import-preview-modal");
modal.classList.toggle("hidden", !visible);
modal.setAttribute("aria-hidden", String(!visible));
}
function showSettingsPinModal(visible) {
const modal = byId("settings-pin-modal");
modal.classList.toggle("hidden", !visible);
modal.setAttribute("aria-hidden", String(!visible));
}
function showModal(visible) {
const modal = byId("settings-modal");
modal.classList.toggle("hidden", !visible);
modal.setAttribute("aria-hidden", String(!visible));
document.body.classList.toggle("settings-open", visible);
}
function showNotesModal(visible) {
const modal = byId("app-notes-modal");
modal.classList.toggle("hidden", !visible);
modal.setAttribute("aria-hidden", String(!visible));
}
function showLaunchArgsModal(visible) {
const modal = byId("launch-args-modal");
modal.classList.toggle("hidden", !visible);
modal.setAttribute("aria-hidden", String(!visible));
}
function openAppNotesEditor() {
const currentNotes = byId("app-notes").value || "";
byId("app-notes-input").value = currentNotes;
showNotesModal(true);
setTimeout(() => byId("app-notes-input").focus(), 0);
}
function saveAppNotes() {
const notes = byId("app-notes-input").value;
byId("app-notes").value = notes;
const preview = notes.split('\n')[0].substring(0, 50) || "(no notes)";
byId("app-notes-preview").value = preview;
showNotesModal(false);
}
function setSettingsTab(tabKey) {
const tabsRoot = byId("settings-tabs");
const panelsRoot = byId("settings-panels");
if (!tabsRoot || !panelsRoot) {
return;
}
const buttons = Array.from(tabsRoot.querySelectorAll(".settings-tab-btn[data-settings-tab]"));
const panels = Array.from(panelsRoot.querySelectorAll(".settings-panel[data-settings-panel]"));
const validKeys = new Set(buttons.map((button) => button.getAttribute("data-settings-tab")));
const next = validKeys.has(tabKey) ? tabKey : "general";
state.settingsTab = next;
buttons.forEach((button) => {
const key = button.getAttribute("data-settings-tab");
const active = key === next;
button.classList.toggle("active", active);
button.setAttribute("aria-selected", String(active));
button.tabIndex = 0;
});
panels.forEach((panel) => {
const key = panel.getAttribute("data-settings-panel");
const active = key === next;
panel.classList.toggle("hidden", !active);
});
if (next === "data") {
loadConfigBackupList();
}
if (next === "hotkeys") {
renderHotkeysList();
}
}
function getSettingsTabButtons() {
const tabsRoot = byId("settings-tabs");
if (!tabsRoot) {
return [];
}
return Array.from(tabsRoot.querySelectorAll(".settings-tab-btn[data-settings-tab]"));
}
function focusAndActivateSettingsTabByIndex(index) {
const buttons = getSettingsTabButtons();
if (!buttons.length) {
return;
}
const nextIndex = Math.min(Math.max(index, 0), buttons.length - 1);
const button = buttons[nextIndex];
const tabKey = button.getAttribute("data-settings-tab") || "general";
setSettingsTab(tabKey);
button.focus();
}
function focusSettingsTab(tabKey) {
const buttons = getSettingsTabButtons();
if (!buttons.length) {
return;
}
const key = tabKey || state.settingsTab || "general";
const match = buttons.find((button) => button.getAttribute("data-settings-tab") === key) || buttons[0];
match.focus();
}
function getFocusableElements(root) {
if (!root) {
return [];
}
const candidates = Array.from(root.querySelectorAll(
"button, [href], input, select, textarea, [tabindex]:not([tabindex='-1'])"
));
return candidates.filter((el) => {
if (!(el instanceof HTMLElement)) {
return false;
}
if (el.hasAttribute("disabled") || el.getAttribute("aria-hidden") === "true") {
return false;
}
return el.offsetParent !== null;
});
}
function getCategoryFilterButtons() {
const rail = byId("category-rail");
if (!rail) {
return [];
}
return Array.from(rail.querySelectorAll("button[data-category-filter]"));
}
function focusCategoryFilterByKey(key) {
const buttons = getCategoryFilterButtons();
const match = buttons.find((button) => button.getAttribute("data-category-filter") === key);
match?.focus();
}
function showHelpModal(visible) {
const modal = byId("help-modal");
modal.classList.toggle("hidden", !visible);
modal.setAttribute("aria-hidden", String(!visible));
}
function showToast(message, kind = "info", durationMs = 2800) {
const region = byId("toast-region");
if (!region) {
return;
}
const toast = document.createElement("div");
toast.className = `toast toast-${kind}`;
toast.setAttribute("role", "status");
toast.textContent = message;
region.appendChild(toast);
setTimeout(() => {
toast.remove();
}, durationMs);
}
function showCommandPaletteModal(visible) {
const modal = byId("command-palette-modal");
modal.classList.toggle("hidden", !visible);
modal.setAttribute("aria-hidden", String(!visible));
}
function isCommandPaletteOpen() {
return !byId("command-palette-modal").classList.contains("hidden");
}
async function openSettingsModal() {
const unlocked = await requestSettingsUnlock();
if (!unlocked) {
return false;
}
syncSettingsForm();
setSettingsTab(state.settingsTab || "general");
showModal(true);
setTimeout(() => focusSettingsTab(state.settingsTab), 0);
return true;
}
async function togglePersistToTray() {
state.config.persistToTray = !state.config.persistToTray;
if (isDesktop) {
await window.launcherAPI.setCloseToTray(state.config.persistToTray);
}