-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase.templ
More file actions
1714 lines (1582 loc) · 69.4 KB
/
Copy pathbase.templ
File metadata and controls
1714 lines (1582 loc) · 69.4 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
package layouts
import "context"
import "github.com/sarg3nt/gearbox/internal/framework/auth"
import "github.com/sarg3nt/gearbox/internal/framework/models"
import "github.com/sarg3nt/gearbox/internal/framework/ui"
import "github.com/sarg3nt/gearbox/internal/framework/middleware"
import "strings"
// isActivePath checks if the current path matches the nav link
func isActivePath(href, currentPath string) bool {
if href == "/" {
return currentPath == "/" || currentPath == ""
}
return strings.HasPrefix(currentPath, href)
}
// getPath extracts the path from the variadic argument
func getPath(paths []string) string {
if len(paths) > 0 {
return paths[0]
}
return ""
}
// shouldHideSidebar determines if the sidebar should be hidden based on context
// Returns true if there are no servers configured (initial setup state)
func shouldHideSidebar(ctx context.Context, currentPath string) bool {
// Check if plugin status is in context - if not, we're in initial setup
_, hasPluginStatus := auth.GetPluginStatusFromContext(ctx)
_, hasPluginOrder := auth.GetPluginOrderFromContext(ctx)
// If neither plugin status nor order is set, we're in initial setup (no servers)
// Hide the sidebar to provide a cleaner first-time experience
return !hasPluginStatus && !hasPluginOrder
}
templ Base(title string, user *models.User, currentPath ...string) {
<!DOCTYPE html>
<html lang="en" class="h-full">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>{ title } - Gearbox</title>
<link rel="icon" type="image/svg+xml" href="/favicon.svg"/>
<link rel="alternate icon" href="/favicon.ico"/>
<!-- Asset Loading: CDN (production) vs Local (dev with USE_LOCAL_ASSETS=true) -->
if middleware.UseLocalAssets(ctx) {
<!-- Local assets for CSP-compliant development -->
<script src="/static/js/vendor/tailwind.js"></script>
} else {
<!-- CDN assets for production (always up-to-date) -->
<script src="https://cdn.tailwindcss.com"></script>
}
<script>
// Configure Tailwind for dark mode
tailwind.config = {
darkMode: 'class',
theme: {
extend: {
colors: {
sidebar: {
light: '#ffffff',
dark: '#1e293b'
}
}
}
}
}
</script>
<script>
// Immediately apply sidebar state to prevent flash
(function() {
const isCollapsed = localStorage.getItem('sidebarCollapsed') === 'true';
if (isCollapsed) {
document.documentElement.classList.add('sidebar-initially-collapsed');
}
})();
</script>
if middleware.UseLocalAssets(ctx) {
<!-- Local JavaScript libraries -->
<script src="/static/js/vendor/htmx.min.js"></script>
<script src="/static/js/vendor/morphdom-umd.min.js"></script>
<script src="/static/js/vendor/chart.umd.min.js"></script>
<script src="/static/js/vendor/hammer.min.js"></script>
<script src="/static/js/vendor/chartjs-plugin-zoom.min.js"></script>
<link rel="stylesheet" href="/static/css/vendor/tabulator.min.css"/>
<script src="/static/js/vendor/tabulator.min.js"></script>
} else {
<!-- CDN JavaScript libraries -->
<script src="https://unpkg.com/htmx.org@1.9.10/dist/htmx.min.js"></script>
<script src="https://unpkg.com/morphdom@2.7.4/dist/morphdom-umd.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/hammerjs@2.0.8/hammer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-zoom@2.0.1/dist/chartjs-plugin-zoom.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/tabulator-tables@6.3.0/dist/css/tabulator.min.css"/>
<script src="https://unpkg.com/tabulator-tables@6.3.0/dist/js/tabulator.min.js"></script>
}
<style>
/* Base styles */
.metric-card {
@apply bg-white dark:bg-slate-800 rounded-lg shadow p-6;
}
.metric-value {
@apply text-3xl font-bold text-blue-600 dark:text-blue-400;
}
.metric-label {
@apply text-sm text-gray-600 dark:text-gray-400;
}
.status-up {
@apply text-green-600 dark:text-green-400;
}
.status-down {
@apply text-red-600 dark:text-red-400;
}
.status-degraded {
@apply text-yellow-600 dark:text-yellow-400;
}
/* Global form control styles */
select, input[type="text"], input[type="email"], input[type="password"], input[type="number"], input[type="search"] {
height: 42px;
min-height: 42px;
}
select {
cursor: pointer;
}
input[type="checkbox"] {
width: 1.25rem;
height: 1.25rem;
cursor: pointer;
}
/* Sidebar transition */
.sidebar {
transition: width 0.3s ease-in-out;
overflow: hidden;
}
.sidebar-collapsed {
width: 4rem;
}
.sidebar-expanded {
width: 16rem;
}
.sidebar-text {
/* When expanding: delay opacity until sidebar has expanded enough */
transition: opacity 0.15s ease-in-out 0.15s;
white-space: nowrap;
}
.sidebar-collapsed .sidebar-text {
/* When collapsed/collapsing: no delay, hide immediately */
transition: opacity 0.1s ease-in-out 0s;
opacity: 0;
}
.sidebar-collapsed #toggle-container {
justify-content: center;
}
/* Initial sidebar state from localStorage */
.sidebar-initially-collapsed #sidebar {
width: 4rem;
}
.sidebar-initially-collapsed #main-content {
margin-left: 4rem;
}
.sidebar-initially-collapsed header {
left: 4rem;
}
.sidebar-initially-collapsed .sidebar-text {
opacity: 0;
}
.sidebar-initially-collapsed #toggle-container {
justify-content: center;
}
/* Main content transition */
.main-content {
transition: margin-left 0.3s ease-in-out;
}
/* Sidebar-aware responsive grid for backend cards */
/* When sidebar is expanded (256px), switch to 2 cols earlier and 1 col earlier */
@media (max-width: 1279px) {
.sidebar-expanded ~ #main-content .backend-card-grid,
:not(.sidebar-initially-collapsed) #main-content .backend-card-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (max-width: 1023px) {
.backend-card-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (max-width: 767px) {
.backend-card-grid {
grid-template-columns: repeat(1, minmax(0, 1fr));
}
}
/* Dark mode Tabulator */
.dark .tabulator {
background-color: #1e293b;
border-color: #475569;
}
.dark .tabulator .tabulator-header {
background-color: #334155;
border-color: #475569;
color: #e2e8f0;
}
.dark .tabulator .tabulator-header .tabulator-col {
background-color: #334155;
border-color: #475569;
}
.dark .tabulator .tabulator-header .tabulator-col .tabulator-col-content {
color: #e2e8f0;
}
.dark .tabulator .tabulator-header .tabulator-col.tabulator-sortable .tabulator-col-title {
color: #e2e8f0;
}
/* Header column hover */
.dark .tabulator .tabulator-header .tabulator-col:hover {
background-color: #475569 !important;
}
.dark .tabulator .tabulator-header .tabulator-col:hover .tabulator-col-content,
.dark .tabulator .tabulator-header .tabulator-col:hover .tabulator-col-title {
color: #ffffff !important;
}
.dark .tabulator .tabulator-header .tabulator-header-filter input,
.dark .tabulator .tabulator-header .tabulator-header-filter select {
background-color: #1e293b;
border-color: #475569;
color: #e2e8f0;
}
.dark .tabulator .tabulator-tableholder .tabulator-table .tabulator-row {
background-color: #1e293b !important;
border-color: #475569;
color: #e2e8f0;
}
.dark .tabulator .tabulator-tableholder .tabulator-table .tabulator-row .tabulator-cell {
background-color: #1e293b !important;
border-color: #475569;
}
.dark .tabulator .tabulator-tableholder .tabulator-table .tabulator-row.tabulator-row-even,
.dark .tabulator .tabulator-tableholder .tabulator-table .tabulator-row.tabulator-row-even .tabulator-cell {
background-color: #273549 !important;
}
.dark .tabulator .tabulator-tableholder .tabulator-table .tabulator-row.tabulator-row-odd,
.dark .tabulator .tabulator-tableholder .tabulator-table .tabulator-row.tabulator-row-odd .tabulator-cell {
background-color: #1e293b !important;
}
/* Hover states - Tabulator uses .tabulator-selectable:hover */
@media (hover:hover) and (pointer:fine) {
.dark .tabulator .tabulator-tableholder .tabulator-table .tabulator-row.tabulator-selectable:hover {
background-color: #64748b !important;
color: #ffffff !important;
}
.dark .tabulator .tabulator-tableholder .tabulator-table .tabulator-row.tabulator-selectable:hover .tabulator-cell {
background-color: #64748b !important;
color: #ffffff !important;
}
.dark .tabulator .tabulator-tableholder .tabulator-table .tabulator-row.tabulator-selectable:hover .tabulator-frozen {
background-color: #64748b !important;
color: #ffffff !important;
}
}
.dark .tabulator .tabulator-footer {
background-color: #334155;
border-color: #475569;
color: #e2e8f0;
}
.dark .tabulator .tabulator-footer .tabulator-page {
background-color: #1e293b;
border-color: #475569;
color: #e2e8f0;
}
.dark .tabulator .tabulator-footer .tabulator-page.active {
background-color: #3b82f6;
color: white;
}
/* Dropdown menu */
.dropdown-menu {
display: none;
}
.dropdown-menu.show {
display: block;
}
</style>
<!-- Custom CSS Components -->
<link rel="stylesheet" href="/static/css/utilities.css"/>
<link rel="stylesheet" href="/static/css/components/cards.css"/>
<link rel="stylesheet" href="/static/css/components/modals.css"/>
<link rel="stylesheet" href="/static/css/components/buttons.css"/>
<script>
// Theme management
function getThemePreference() {
const stored = localStorage.getItem('theme');
if (stored) return stored;
return 'system';
}
function getEffectiveTheme() {
const pref = getThemePreference();
if (pref === 'system') {
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
return pref;
}
function applyTheme() {
const theme = getEffectiveTheme();
if (theme === 'dark') {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
updateThemeIcon();
}
function setTheme(theme) {
localStorage.setItem('theme', theme);
applyTheme();
// Close dropdown
document.getElementById('theme-dropdown')?.classList.remove('show');
}
function updateThemeIcon() {
const pref = getThemePreference();
const btnLight = document.getElementById('theme-btn-light');
const btnDark = document.getElementById('theme-btn-dark');
const btnSystem = document.getElementById('theme-btn-system');
// Reset all buttons
[btnLight, btnDark, btnSystem].forEach(btn => {
if (btn) {
btn.classList.remove('bg-blue-100', 'dark:bg-blue-900', 'text-blue-600', 'dark:text-blue-400');
}
});
// Highlight active button
const activeBtn = pref === 'light' ? btnLight : pref === 'dark' ? btnDark : btnSystem;
if (activeBtn) {
activeBtn.classList.add('bg-blue-100', 'dark:bg-blue-900', 'text-blue-600', 'dark:text-blue-400');
}
}
function toggleUserDropdown() {
const dropdown = document.getElementById('user-dropdown');
const button = document.getElementById('user-button');
if (dropdown && button) {
const isShowing = dropdown.classList.contains('show');
if (!isShowing) {
// Position the dropdown above the button, to the right of the sidebar
const buttonRect = button.getBoundingClientRect();
const dropdownHeight = dropdown.offsetHeight || 300; // Estimate if not visible
// Position dropdown to appear above the button and to its right
dropdown.style.left = buttonRect.right + 8 + 'px';
dropdown.style.bottom = (window.innerHeight - buttonRect.bottom) + 'px';
dropdown.style.top = 'auto';
}
dropdown.classList.toggle('show');
}
}
// Apply theme immediately to prevent flash
applyTheme();
// Listen for system theme changes
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
if (getThemePreference() === 'system') {
applyTheme();
}
});
// Close dropdown when clicking outside
document.addEventListener('click', function(e) {
const userDropdown = document.getElementById('user-dropdown');
const userButton = document.getElementById('user-button');
if (userDropdown && userButton && !userButton.contains(e.target) && !userDropdown.contains(e.target)) {
userDropdown.classList.remove('show');
}
});
// Sidebar management
function getSidebarState() {
const stored = localStorage.getItem('sidebarCollapsed');
return stored === 'true';
}
function toggleSidebar() {
const sidebar = document.getElementById('sidebar');
const mainContent = document.getElementById('main-content');
const header = document.querySelector('header');
const iconCollapse = document.getElementById('sidebar-icon-collapse');
const iconExpand = document.getElementById('sidebar-icon-expand');
const isCollapsed = sidebar.classList.contains('sidebar-collapsed');
if (isCollapsed) {
sidebar.classList.remove('sidebar-collapsed');
sidebar.classList.add('sidebar-expanded');
mainContent.classList.remove('ml-16');
mainContent.classList.add('ml-64');
if (header) {
header.style.left = '16rem'; // 64 * 4px = 256px = 16rem
}
// Show collapse icon, hide expand icon
if (iconCollapse) iconCollapse.classList.remove('hidden');
if (iconExpand) iconExpand.classList.add('hidden');
localStorage.setItem('sidebarCollapsed', 'false');
} else {
sidebar.classList.add('sidebar-collapsed');
sidebar.classList.remove('sidebar-expanded');
mainContent.classList.add('ml-16');
mainContent.classList.remove('ml-64');
if (header) {
header.style.left = '4rem'; // 16 * 4px = 64px = 4rem
}
// Show expand icon, hide collapse icon
if (iconCollapse) iconCollapse.classList.add('hidden');
if (iconExpand) iconExpand.classList.remove('hidden');
localStorage.setItem('sidebarCollapsed', 'true');
}
}
function applySidebarState() {
const isCollapsed = getSidebarState();
const sidebar = document.getElementById('sidebar');
const mainContent = document.getElementById('main-content');
const header = document.querySelector('header');
const iconCollapse = document.getElementById('sidebar-icon-collapse');
const iconExpand = document.getElementById('sidebar-icon-expand');
// Remove the initial state class
document.documentElement.classList.remove('sidebar-initially-collapsed');
if (sidebar && mainContent) {
if (isCollapsed) {
sidebar.classList.add('sidebar-collapsed');
sidebar.classList.remove('sidebar-expanded');
mainContent.classList.add('ml-16');
mainContent.classList.remove('ml-64');
if (header) {
header.style.left = '4rem';
}
// Show expand icon, hide collapse icon
if (iconCollapse) iconCollapse.classList.add('hidden');
if (iconExpand) iconExpand.classList.remove('hidden');
} else {
sidebar.classList.remove('sidebar-collapsed');
sidebar.classList.add('sidebar-expanded');
mainContent.classList.remove('ml-16');
mainContent.classList.add('ml-64');
if (header) {
header.style.left = '16rem';
}
// Show collapse icon, hide expand icon
if (iconCollapse) iconCollapse.classList.remove('hidden');
if (iconExpand) iconExpand.classList.add('hidden');
}
}
}
// Sidebar edit mode state
let sidebarEditMode = false;
let sidebarSortable = null;
function toggleSidebarEditMode() {
sidebarEditMode = !sidebarEditMode;
const iconEdit = document.getElementById('sidebar-icon-edit');
const iconSave = document.getElementById('sidebar-icon-save');
const dragHandles = document.querySelectorAll('.nav-drag-handle');
const navLinks = document.querySelectorAll('.nav-link');
if (sidebarEditMode) {
// Enter edit mode
if (iconEdit) iconEdit.classList.add('hidden');
if (iconSave) iconSave.classList.remove('hidden');
// Show drag handles
dragHandles.forEach(handle => handle.classList.remove('hidden'));
// Disable link clicks
navLinks.forEach(link => {
link.style.pointerEvents = 'none';
link.style.cursor = 'grab';
});
// Initialize Sortable if not already done
initSidebarSortable();
} else {
// Exit edit mode (save)
if (iconEdit) iconEdit.classList.remove('hidden');
if (iconSave) iconSave.classList.add('hidden');
// Hide drag handles
dragHandles.forEach(handle => handle.classList.add('hidden'));
// Re-enable link clicks
navLinks.forEach(link => {
link.style.pointerEvents = '';
link.style.cursor = '';
});
// Save the new order
saveSidebarOrder();
}
}
function initSidebarSortable() {
if (typeof window.Sortable === 'undefined') {
console.error('Sortable not loaded!');
return;
}
const navList = document.getElementById('sidebar-nav-list');
if (!navList) {
console.error('Navigation list not found!');
return;
}
// Destroy existing sortable instance if it exists
if (sidebarSortable) {
sidebarSortable.destroy();
}
// Create new sortable instance
sidebarSortable = window.Sortable.create(navList, {
animation: 200,
handle: '.nav-drag-handle',
draggable: '.nav-item-draggable',
ghostClass: 'bg-blue-50 dark:bg-slate-700',
chosenClass: 'opacity-50',
dragClass: 'opacity-75',
onEnd: function(evt) {
console.log('Item moved from index', evt.oldIndex, 'to', evt.newIndex);
}
});
}
function saveSidebarOrder() {
const navItems = document.querySelectorAll('.nav-item-draggable');
const order = [];
navItems.forEach((item, index) => {
const pluginName = item.dataset.pluginName;
if (pluginName) {
order.push({
name: pluginName,
sortOrder: index
});
}
});
console.log('Saving sidebar order:', order);
// Get the selected server ID
const serverID = window.ServerSelector ? window.ServerSelector.getSelectedServer() : null;
if (!serverID) {
console.error('No server selected');
return;
}
// Send to server
fetch(`/api/integrations/sort-order?server=${encodeURIComponent(serverID)}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'same-origin',
body: JSON.stringify({ order: order })
})
.then(response => {
if (response.ok) {
console.log('Sidebar order saved successfully');
} else {
console.error('Failed to save sidebar order');
}
})
.catch(error => {
console.error('Error saving sidebar order:', error);
});
}
// Session keep-alive and timeout tracking
let sessionKeepAliveInterval = null;
let sessionTimeoutChecker = null;
let sessionExpiresAt = null;
function startSessionKeepAlive() {
// Ping every 5 minutes to keep session alive when page is focused
sessionKeepAliveInterval = setInterval(() => {
if (document.hasFocus()) {
fetch('/api/keepalive', { method: 'POST', credentials: 'same-origin' })
.then(response => {
if (response.status === 401 || response.status === 403) {
// Session expired, redirect to login
redirectToLogin('Your session has expired. Please log in again.');
} else if (response.ok) {
// Update session expiration time on successful keep-alive
return response.json();
}
})
.then(data => {
if (data && data.expiresAt) {
sessionExpiresAt = new Date(data.expiresAt);
}
})
.catch(() => {}); // Ignore network errors silently
}
}, 5 * 60 * 1000);
// Start session timeout checker (runs every 10 seconds)
startSessionTimeoutChecker();
}
function stopSessionKeepAlive() {
if (sessionKeepAliveInterval) {
clearInterval(sessionKeepAliveInterval);
sessionKeepAliveInterval = null;
}
stopSessionTimeoutChecker();
}
function startSessionTimeoutChecker() {
// Check session expiration every 10 seconds
sessionTimeoutChecker = setInterval(() => {
if (sessionExpiresAt) {
const now = new Date();
if (now >= sessionExpiresAt) {
// Session has expired, redirect to login
redirectToLogin('Your session has expired. Please log in again.');
}
}
}, 10 * 1000);
// Fetch initial session expiration time
fetch('/api/session-info', { credentials: 'same-origin' })
.then(response => {
if (response.ok) {
return response.json();
}
})
.then(data => {
if (data && data.expiresAt) {
sessionExpiresAt = new Date(data.expiresAt);
}
})
.catch(() => {});
}
function stopSessionTimeoutChecker() {
if (sessionTimeoutChecker) {
clearInterval(sessionTimeoutChecker);
sessionTimeoutChecker = null;
}
}
function redirectToLogin(message) {
// Clear intervals before redirect
stopSessionKeepAlive();
// Build redirect URL with return path
const returnURL = window.location.pathname;
let redirectURL = '/login?message=' + encodeURIComponent(message);
if (returnURL && returnURL !== '/' && returnURL !== '/login' && returnURL !== '/logout') {
redirectURL += '&return=' + encodeURIComponent(returnURL);
}
window.location.href = redirectURL;
}
// Global fetch interceptor for session timeout detection
(function() {
const originalFetch = window.fetch;
window.fetch = function(...args) {
return originalFetch.apply(this, args)
.then(response => {
// If we get a 401/403 on any API call, redirect to login
if ((response.status === 401 || response.status === 403) &&
!args[0].includes('/login') &&
!args[0].includes('/api/keepalive') &&
!args[0].includes('/api/session-info')) {
redirectToLogin('Your session has expired. Please log in again.');
}
return response;
});
};
})();
// Global server selection management
// Uses sessionStorage for tab isolation - each tab maintains its own server selection
const ServerSelector = {
STORAGE_KEY: 'global-selected-server',
// Get the currently selected server for this tab
getSelectedServer: function() {
return sessionStorage.getItem(this.STORAGE_KEY) || null;
},
// Set the selected server for this tab and notify listeners
setSelectedServer: function(serverID) {
const oldServer = this.getSelectedServer();
sessionStorage.setItem(this.STORAGE_KEY, serverID);
if (oldServer !== serverID) {
// Dispatch custom event for pages to listen to
window.dispatchEvent(new CustomEvent('serverChanged', {
detail: { serverID: serverID, previousServerID: oldServer }
}));
}
},
// Initialize server selector from a dropdown/select element
// If no selection exists in sessionStorage, uses the first option
initFromSelect: function(selectElement) {
if (!selectElement) return null;
const savedServer = this.getSelectedServer();
// Check if saved server exists in options
if (savedServer) {
const optionExists = Array.from(selectElement.options).some(opt => opt.value === savedServer);
if (optionExists) {
selectElement.value = savedServer;
return savedServer;
}
}
// Use first option as default
if (selectElement.options.length > 0) {
const firstServer = selectElement.options[0].value;
this.setSelectedServer(firstServer);
selectElement.value = firstServer;
return firstServer;
}
return null;
}
};
// Expose globally
window.ServerSelector = ServerSelector;
// Alert badge management
let alertBadgeInterval = null;
function updateAlertBadge() {
fetch('/api/alerts/count', { credentials: 'same-origin' })
.then(response => {
if (response.ok) return response.json();
return null;
})
.then(data => {
const badge = document.getElementById('alert-badge');
if (badge && data) {
const count = data.total_active || 0;
if (count > 0) {
badge.textContent = count > 99 ? '99+' : count;
badge.classList.remove('hidden');
badge.classList.add('flex');
// Add pulse animation for critical alerts
if (data.critical_count > 0) {
badge.classList.add('animate-pulse');
} else {
badge.classList.remove('animate-pulse');
}
} else {
badge.classList.add('hidden');
badge.classList.remove('flex', 'animate-pulse');
}
}
})
.catch(() => {});
}
function startAlertBadgeUpdates() {
// Initial update
updateAlertBadge();
// Update every 30 seconds
alertBadgeInterval = setInterval(updateAlertBadge, 30000);
}
function stopAlertBadgeUpdates() {
if (alertBadgeInterval) {
clearInterval(alertBadgeInterval);
alertBadgeInterval = null;
}
}
// Start keep-alive when page loads
document.addEventListener('DOMContentLoaded', function() {
applySidebarState();
updateThemeIcon();
startSessionKeepAlive();
startAlertBadgeUpdates();
});
// Handle visibility changes
document.addEventListener('visibilitychange', function() {
if (document.hidden) {
stopSessionKeepAlive();
stopAlertBadgeUpdates();
} else {
startSessionKeepAlive();
startAlertBadgeUpdates();
}
});
</script>
<!-- Common JavaScript Utilities -->
<script src="/static/js/utils/formatting.js" defer></script>
<script src="/static/js/utils/dom.js" defer></script>
<script src="/static/js/utils/api.js" defer></script>
<script src="/static/js/common/page-header.js" defer></script>
<script src="/static/js/common/box-selector.js" defer></script>
</head>
<body class="h-full bg-gray-100 dark:bg-slate-900">
@ui.CollapsibleRestoreScript()
if user != nil {
// Check if we should hide the sidebar (e.g., on initial setup pages)
if shouldHideSidebar(ctx, getPath(currentPath)) {
<!-- No sidebar, full-width layout for initial setup -->
<main class="min-h-screen">
{ children... }
</main>
} else {
@Sidebar(user, getPath(currentPath))
<div id="main-content" class="main-content ml-64 min-h-screen flex flex-col pt-[57px]">
@Header()
<main class="flex-1 p-6">
{ children... }
</main>
</div>
}
} else {
<main class="min-h-screen">
{ children... }
</main>
}
@ConfirmDialog()
@PromptDialog()
@AlertDialog()
@ui.Toast()
</body>
</html>
}
// ConfirmDialog provides a reusable custom confirmation dialog that replaces browser confirm()
templ ConfirmDialog() {
<!-- Global Confirmation Dialog -->
<div id="confirm-dialog" class="fixed inset-0 z-[100] hidden overflow-y-auto" aria-labelledby="confirm-dialog-title" role="dialog" aria-modal="true">
<div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
<!-- Background overlay -->
<div class="fixed inset-0 bg-gray-500 bg-opacity-75 dark:bg-gray-900 dark:bg-opacity-75 transition-opacity" onclick="closeConfirmDialog(false)"></div>
<span class="hidden sm:inline-block sm:align-middle sm:h-screen">​</span>
<!-- Dialog panel -->
<div class="inline-block align-bottom bg-white dark:bg-slate-800 rounded-lg px-4 pt-5 pb-4 text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full sm:p-6">
<div class="sm:flex sm:items-start">
<!-- Icon - changes based on type -->
<div id="confirm-dialog-icon-warning" class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-yellow-100 dark:bg-yellow-900 sm:mx-0 sm:h-10 sm:w-10">
<svg class="h-6 w-6 text-yellow-600 dark:text-yellow-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path>
</svg>
</div>
<div id="confirm-dialog-icon-danger" class="hidden mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-red-100 dark:bg-red-900 sm:mx-0 sm:h-10 sm:w-10">
<svg class="h-6 w-6 text-red-600 dark:text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path>
</svg>
</div>
<div id="confirm-dialog-icon-info" class="hidden mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-blue-100 dark:bg-blue-900 sm:mx-0 sm:h-10 sm:w-10">
<svg class="h-6 w-6 text-blue-600 dark:text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
</svg>
</div>
<div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left flex-1">
<h3 class="text-lg leading-6 font-medium text-gray-900 dark:text-white" id="confirm-dialog-title">
Confirm Action
</h3>
<div class="mt-2">
<p id="confirm-dialog-message" class="text-sm text-gray-500 dark:text-gray-400">
Are you sure you want to proceed?
</p>
</div>
</div>
</div>
<div class="mt-5 sm:mt-4 sm:flex sm:flex-row-reverse">
<button
type="button"
id="confirm-dialog-confirm-btn"
onclick="closeConfirmDialog(true)"
class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:ml-3 sm:w-auto sm:text-sm"
>
Confirm
</button>
<button
type="button"
onclick="closeConfirmDialog(false)"
class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 dark:border-gray-600 shadow-sm px-4 py-2 bg-white dark:bg-slate-700 text-base font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-slate-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:mt-0 sm:w-auto sm:text-sm"
>
Cancel
</button>
</div>
</div>
</div>
</div>
<script>
// Global confirmation dialog API
let confirmDialogResolve = null;
/**
* Show a custom confirmation dialog
* @param {Object} options - Dialog options
* @param {string} options.title - Dialog title
* @param {string} options.message - Dialog message
* @param {string} [options.confirmText='Confirm'] - Confirm button text
* @param {string} [options.type='warning'] - Dialog type: 'warning', 'danger', or 'info'
* @returns {Promise<boolean>} - Resolves to true if confirmed, false if cancelled
*/
function showConfirmDialog(options) {
return new Promise((resolve) => {
confirmDialogResolve = resolve;
const dialog = document.getElementById('confirm-dialog');
const title = document.getElementById('confirm-dialog-title');
const message = document.getElementById('confirm-dialog-message');
const confirmBtn = document.getElementById('confirm-dialog-confirm-btn');
const iconWarning = document.getElementById('confirm-dialog-icon-warning');
const iconDanger = document.getElementById('confirm-dialog-icon-danger');
const iconInfo = document.getElementById('confirm-dialog-icon-info');
// Set content
title.textContent = options.title || 'Confirm Action';
message.textContent = options.message || 'Are you sure you want to proceed?';
confirmBtn.textContent = options.confirmText || 'Confirm';
// Set button style based on type
const type = options.type || 'warning';
confirmBtn.className = confirmBtn.className.replace(/bg-\w+-600/g, '').replace(/hover:bg-\w+-700/g, '').replace(/focus:ring-\w+-500/g, '');
// Hide all icons first
iconWarning.classList.add('hidden');
iconDanger.classList.add('hidden');
iconInfo.classList.add('hidden');
if (type === 'danger') {
confirmBtn.classList.add('bg-red-600', 'hover:bg-red-700', 'focus:ring-red-500');
iconDanger.classList.remove('hidden');
} else if (type === 'info') {
confirmBtn.classList.add('bg-blue-600', 'hover:bg-blue-700', 'focus:ring-blue-500');
iconInfo.classList.remove('hidden');
} else {
confirmBtn.classList.add('bg-yellow-600', 'hover:bg-yellow-700', 'focus:ring-yellow-500');
iconWarning.classList.remove('hidden');
}
// Show dialog
dialog.classList.remove('hidden');
});
}
function closeConfirmDialog(result) {
const dialog = document.getElementById('confirm-dialog');
dialog.classList.add('hidden');
if (confirmDialogResolve) {
confirmDialogResolve(result);
confirmDialogResolve = null;
}
}
// Close dialog on Escape key
document.addEventListener('keydown', function(e) {
if (e.key === 'Escape') {
const dialog = document.getElementById('confirm-dialog');
if (dialog && !dialog.classList.contains('hidden')) {
closeConfirmDialog(false);
}
const promptDialog = document.getElementById('prompt-dialog');
if (promptDialog && !promptDialog.classList.contains('hidden')) {
closePromptDialog(null);
}
const alertDialog = document.getElementById('alert-dialog');
if (alertDialog && !alertDialog.classList.contains('hidden')) {
closeAlertDialog();
}
}
});
</script>
}
// PromptDialog provides a reusable custom prompt dialog that replaces browser prompt()
templ PromptDialog() {
<!-- Global Prompt Dialog -->
<div id="prompt-dialog" class="fixed inset-0 z-[100] hidden overflow-y-auto" aria-labelledby="prompt-dialog-title" role="dialog" aria-modal="true">
<div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
<!-- Background overlay -->
<div class="fixed inset-0 bg-gray-500 bg-opacity-75 dark:bg-gray-900 dark:bg-opacity-75 transition-opacity" onclick="closePromptDialog(null)"></div>
<span class="hidden sm:inline-block sm:align-middle sm:h-screen">​</span>
<!-- Dialog panel -->
<div class="inline-block align-bottom bg-white dark:bg-slate-800 rounded-lg px-4 pt-5 pb-4 text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full sm:p-6">
<div class="sm:flex sm:items-start">
<!-- Icon -->
<div class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-blue-100 dark:bg-blue-900 sm:mx-0 sm:h-10 sm:w-10">