forked from dcflachs/compose_plugin
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathComposeManager.php
More file actions
executable file
·6236 lines (5622 loc) · 281 KB
/
ComposeManager.php
File metadata and controls
executable file
·6236 lines (5622 loc) · 281 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
<?PHP
/**
* Compose Manager Main Page
* The stack list is loaded asynchronously via AJAX for better UX
*/
require_once("/usr/local/emhttp/plugins/compose.manager/include/Defines.php");
require_once("/usr/local/emhttp/plugins/compose.manager/include/Util.php");
// Load plugin config
$cfg = parse_plugin_cfg($sName);
$autoCheckUpdates = ($cfg['AUTO_CHECK_UPDATES'] ?? 'false') === 'true';
$autoCheckDays = floatval($cfg['AUTO_CHECK_UPDATES_DAYS'] ?? '1');
$showComposeOnTop = ($cfg['SHOW_COMPOSE_ON_TOP'] ?? 'false') === 'true';
$hideComposeFromDocker = ($cfg['HIDE_COMPOSE_FROM_DOCKER'] ?? 'false') === 'true';
// Get Docker Compose CLI version
$composeVersion = trim(shell_exec('docker compose version --short 2>/dev/null') ?? '');
// Host total memory in bytes for stack-level memory denominator.
$composeSystemMemBytes = 0;
$memKbRaw = trim(shell_exec("awk '/^MemTotal:/ {print \$2}' /proc/meminfo 2>/dev/null") ?? '');
if (is_numeric($memKbRaw)) {
$composeSystemMemBytes = (int)$memKbRaw * 1024;
}
// CPU count for load normalization (matches Docker manager's cpu_list approach).
// cpu_list() returns thread_siblings_list entries (e.g. "0-3,8-11").
// We expand each range segment so "0-3" counts as 4, not 2 endpoints.
function compose_manager_cpu_spec_count($cpuSpec)
{
$count = 0;
foreach (explode(',', trim((string)$cpuSpec)) as $segment) {
$segment = trim($segment);
if ($segment === '') continue;
if (strpos($segment, '-') !== false) {
[$start, $end] = explode('-', $segment, 2);
$start = (int)$start;
$end = (int)$end;
if ($end < $start) [$start, $end] = [$end, $start];
$count += max(0, $end - $start + 1);
} else {
$count += 1;
}
}
return $count;
}
$cpus = function_exists('cpu_list') ? cpu_list() : [];
$cpuCount = 0;
foreach ($cpus as $cpuSpec) {
$cpuCount += compose_manager_cpu_spec_count($cpuSpec);
}
if ($cpuCount <= 0) {
$cpuCount = (int)trim(shell_exec('nproc 2>/dev/null') ?: '1');
}
if ($cpuCount <= 0) {
$cpuCount = 1;
}
// Note: Stack list is now loaded asynchronously via ComposeList.php
// This improves page load time by deferring expensive docker commands
?>
<?php /* ── Critical inline CSS ──────────────────────────────────────────────
Guarantees table-layout, column widths, and advanced/basic visibility
are applied synchronously BEFORE any HTML renders — prevents FOUC.
Non-critical styles remain in comboButton.css loaded via <link>. */ ?>
<style>
/* Table structure — always fixed layout */
#compose_stacks {
width: 100%;
table-layout: fixed
}
/* Stabilize header row height across basic/advanced toggle transitions */
#compose_stacks thead tr th {
font-weight: normal;
font-size: 1.1rem;
text-transform: uppercase;
letter-spacing: 1px;
color: var(--dynamix-tablesorter-thead-th-text-color);
background-color: var(--dynamix-tablesorter-thead-th-bg-color);
padding: 8px 20px 8px 6px;
white-space: nowrap;
text-align: left;
}
/* Clip overflowing content in fixed-layout cells */
#compose_stacks th,
#compose_stacks td {
overflow: hidden;
text-overflow: ellipsis
}
/* Basic-view column widths (7 visible columns)
Arrow + Icon are fixed px (small fixed content); rest are % of table. */
#compose_stacks thead th.col-arrow {
width: 1%;
padding: 0;
}
#compose_stacks thead th.col-icon {
width: 2%;
padding: 0;
}
#compose_stacks thead th.col-name {
width: 12%;
}
#compose_stacks thead th.col-update {
width: 25%;
}
#compose_stacks thead th.col-containers {
width: 25%;
}
#compose_stacks thead th.col-uptime {
width: 25%;
}
#compose_stacks thead th.col-autostart {
width: 15%;
}
/* Advanced-view column widths (10 visible columns)
Arrow + Icon stay fixed px; Description + Path get the most %. */
#compose_stacks.cm-advanced-view thead th.col-arrow {
width: 1%;
}
#compose_stacks.cm-advanced-view thead th.col-icon {
width: 2%;
}
#compose_stacks.cm-advanced-view thead th.col-name {
width: 12%;
}
#compose_stacks.cm-advanced-view thead th.col-update {
width: 10%
}
#compose_stacks.cm-advanced-view thead th.col-containers {
width: 5%
}
#compose_stacks.cm-advanced-view thead th.col-uptime {
width: 6%
}
#compose_stacks.cm-advanced-view thead th.col-load {
width: 12%
}
#compose_stacks.cm-advanced-view thead th.col-description {
width: 22%
}
#compose_stacks.cm-advanced-view thead th.col-path {
width: 22%
}
#compose_stacks.cm-advanced-view thead th.col-autostart {
width: 8%
}
/* Center the Containers column */
#compose_stacks thead th.col-containers,
#compose_stacks td.col-containers {
text-align: center
}
/* Autostart column: right-align content to push toggles to edge */
#compose_stacks thead th.col-autostart,
#compose_stacks td.col-autostart {
text-align: right
}
/* Arrow and icon columns: no overflow clipping, no padding bloat */
#compose_stacks td.col-arrow,
#compose_stacks td.col-icon {
overflow: visible;
padding: 8px 0;
text-align: center;
vertical-align: middle
}
/* Advanced/basic visibility — CSS-only so no flash of hidden content */
#compose_stacks .cm-advanced {
display: none
}
#compose_stacks.cm-advanced-view .cm-advanced {
display: table-cell
}
#compose_stacks.cm-advanced-view div.cm-advanced {
display: block
}
/* Detail row */
#compose_stacks .stack-details-cell {
width: auto !important
}
#compose_stacks tbody tr.stack-details-row {
background-color: var(--dynamix-sb-body-bg-color) !important
}
/* Autostart cell */
#compose_stacks td.nine {
white-space: nowrap;
padding-right: 20px
}
.dropdown-menu {
z-index: 100 !important;
}
/* CPU & Memory load display (matches Docker manager usage-disk style) */
.compose-load-cell {
white-space: nowrap;
font-size: 0.9em;
}
.compose-load-cell .compose-load-cpu,
.compose-load-cell .compose-load-mem {
display: block;
}
.compose-load-cell .compose-load-mem {
margin-top: 2px;
}
.compose-load-cell .usage-disk.mm {
height: 3px;
margin: 3px 20px 0 0;
position: relative;
background-color: var(--usage-disk-background-color, #e0e0e0);
}
.compose-load-cell .usage-disk.mm > span:first-child {
position: absolute;
left: 0;
height: 3px;
background-color: var(--gray-400, #888);
}
.compose-load-cell .usage-disk.mm > span:last-child {
position: relative;
z-index: 1;
}
</style>
<?php
// Use Dynamix's bundled Ace if available (Unraid 7.0.0+), else fall back to our plugin-local copy
// (downloaded during install for pre-7.0.0 Unraid via the PLG post-install script)
$acePath = file_exists('/usr/local/emhttp/plugins/dynamix/javascript/ace/ace.js')
? '/webGui/javascript/ace'
: '/plugins/compose.manager/javascript/ace';
?>
<script src="<?php echo $acePath; ?>/ace.js" type="text/javascript"></script>
<script src="/plugins/compose.manager/javascript/js-yaml/js-yaml.min.js" type="text/javascript"></script>
<script src="/plugins/compose.manager/javascript/common.js" type="text/javascript"></script>
<script>
var compose_root = <?php echo json_encode($compose_root); ?>;
var caURL = "/plugins/compose.manager/include/Exec.php";
var compURL = "/plugins/compose.manager/include/ComposeUtil.php";
var aceTheme = <?php echo (in_array($theme, ['black', 'gray']) ? json_encode('ace/theme/tomorrow_night') : json_encode('ace/theme/tomorrow')); ?>;
var aceBasePath = <?php echo json_encode($acePath); ?>;
const icon_label = <?php echo json_encode($docker_label_icon); ?>;
// Configure Ace base path explicitly so it finds mode/theme files
// regardless of how the script URL was resolved
if (typeof ace !== 'undefined') {
ace.config.set('basePath', aceBasePath);
}
const webui_label = <?php echo json_encode($docker_label_webui); ?>;
const shell_label = <?php echo json_encode($docker_label_shell); ?>;
// Auto-check settings from config
var autoCheckUpdates = <?php echo json_encode($autoCheckUpdates); ?>;
var autoCheckDays = <?php echo json_encode($autoCheckDays); ?>;
var showComposeOnTop = <?php echo json_encode($showComposeOnTop); ?>;
var hideComposeFromDocker = <?php echo json_encode($hideComposeFromDocker); ?>;
var composeCliVersion = <?php echo json_encode($composeVersion); ?>;
var composeSystemMemBytes = <?php echo json_encode($composeSystemMemBytes); ?>;
var composeCpuCount = <?php echo json_encode($cpuCount); ?>;
// Parse a single memory value (for example "123.4MiB" or "512MB") to bytes.
// Supports both IEC (KiB, MiB, GiB, TiB) and SI (kB, MB, GB, TB) suffixes.
function parseMemValueToBytes(memVal) {
if (!memVal) return 0;
var cleaned = String(memVal).trim();
if (!cleaned) return 0;
var match = cleaned.match(/([\d.]+)\s*([kmgt]?i?b)?/i);
if (!match) return 0;
var num = parseFloat(match[1]);
if (!isFinite(num)) return 0;
var unit = (match[2] || 'b').toLowerCase();
switch (unit) {
case 'tb': return num * 1000000000000;
case 'tib': return num * 1099511627776;
case 'gb': return num * 1000000000;
case 'gib': return num * 1073741824;
case 'mb': return num * 1000000;
case 'mib': return num * 1048576;
case 'kb': return num * 1000;
case 'kib': return num * 1024;
default: return num;
}
}
// Parse docker stats memory string "used / limit" into bytes.
function parseMemUsagePair(memStr) {
if (!memStr) return {used: 0, limit: 0};
var parts = String(memStr).split('/');
var used = parseMemValueToBytes(parts[0] || '');
var limit = parseMemValueToBytes(parts[1] || '');
return {used: used, limit: limit};
}
// Backward-compatible helper used by existing code paths.
function parseMemToBytes(memStr) {
return parseMemUsagePair(memStr).used;
}
// Format bytes to human-readable string with fixed 2 decimals.
function formatBytes(bytes) {
var val = Number(bytes) || 0;
if (val < 0) val = 0;
if (val >= 1073741824) return (val / 1073741824).toFixed(2) + 'GiB';
if (val >= 1048576) return (val / 1048576).toFixed(2) + 'MiB';
if (val >= 1024) return (val / 1024).toFixed(2) + 'KiB';
return val.toFixed(2) + 'B';
}
function formatCpuPercent(value) {
var num = Number(value) || 0;
return num.toFixed(2) + '%';
}
function formatMemUsageText(usedBytes, limitBytes) {
return formatBytes(usedBytes) + ' / ' + formatBytes(limitBytes);
}
// ═══════════════════════════════════════════════════════════════════
// Standard factory functions for container and stack identity objects
// ═══════════════════════════════════════════════════════════════════
/**
* Create a normalized container info object from any raw source.
* Handles PascalCase→camelCase, resolves name from multiple field aliases,
* and derives hasUpdate/isPinned when not explicitly set.
*
* @param {Object} raw - Raw container object (from server, cache, or update response)
* @returns {Object} Normalized container info
*/
function createContainerInfo(raw) {
if (!raw) return null;
var name = raw.name || raw.Name || raw.container || raw.Service || raw.service || '';
var service = raw.service || raw.Service || name;
var updateStatus = raw.updateStatus || raw.UpdateStatus || '';
var hasUpdate = (raw.hasUpdate !== undefined) ? !!raw.hasUpdate : (updateStatus === 'update-available');
return {
name: name,
service: service,
image: raw.image || raw.Image || '',
state: raw.state || raw.State || '',
isRunning: (raw.state || raw.State || '') === 'running',
hasUpdate: hasUpdate,
updateStatus: updateStatus,
localSha: raw.localSha || raw.LocalSha || '',
remoteSha: raw.remoteSha || raw.RemoteSha || '',
isPinned: (raw.isPinned !== undefined) ? !!raw.isPinned : false,
pinnedDigest: raw.pinnedDigest || raw.PinnedDigest || '',
icon: raw.icon || raw.Icon || '',
shell: raw.shell || raw.Shell || '/bin/bash',
webUI: raw.webUI || raw.WebUI || '',
ports: raw.ports || raw.Ports || [],
networks: raw.networks || raw.Networks || [],
volumes: raw.volumes || raw.Volumes || [],
id: raw.id || raw.Id || raw.ID || '',
created: raw.created || raw.Created || '',
startedAt: raw.startedAt || raw.StartedAt || ''
};
}
/**
* Create a normalized stack info object.
*
* @param {string} project - The project/stack folder name
* @param {Array} containers - Array of raw container objects (will be normalized)
* @param {Object} [opts] - Optional overrides (totalServices, lastChecked, etc.)
* @returns {Object} Normalized stack info
*/
function createStackInfo(project, containers, opts) {
opts = opts || {};
var normalized = (containers || []).map(createContainerInfo).filter(Boolean);
var isRunning = normalized.some(function(c) { return c.isRunning; });
var hasUpdate = normalized.some(function(c) { return c.hasUpdate; });
return {
projectName: opts.projectName || project,
containers: normalized,
isRunning: (opts.isRunning !== undefined) ? opts.isRunning : isRunning,
hasUpdate: (opts.hasUpdate !== undefined) ? opts.hasUpdate : hasUpdate,
totalServices: opts.totalServices || normalized.length,
lastChecked: opts.lastChecked || null
};
}
/**
* Merge update status info from a previous stackInfo into a new one.
* Matches containers by name and copies update fields.
*
* @param {Object} stackInfo - The target stack info (mutated in place)
* @param {Object} prevStatus - Previously saved stack update status
* @returns {Object} The mutated stackInfo
*/
function mergeStackUpdateStatus(stackInfo, prevStatus) {
if (!prevStatus) return stackInfo;
// Copy stack-level fields
['lastChecked', 'updateAvailable', 'checking', 'checked'].forEach(function(k) {
if (typeof prevStatus[k] !== 'undefined') stackInfo[k] = prevStatus[k];
});
// Merge container-level update data
if (prevStatus.containers && stackInfo.containers) {
stackInfo.containers.forEach(function(c) {
var cName = c.name;
prevStatus.containers.forEach(function(pc) {
var prev = (typeof pc.name === 'string') ? pc : createContainerInfo(pc);
if (cName === prev.name) {
if (prev.hasUpdate && !c.hasUpdate) c.hasUpdate = prev.hasUpdate;
if (prev.updateStatus && !c.updateStatus) c.updateStatus = prev.updateStatus;
if (prev.localSha && !c.localSha) c.localSha = prev.localSha;
if (prev.remoteSha && !c.remoteSha) c.remoteSha = prev.remoteSha;
if (prev.isPinned !== undefined) c.isPinned = prev.isPinned;
}
});
});
// Recompute stack-level hasUpdate from merged containers
stackInfo.hasUpdate = stackInfo.containers.some(function(c) { return c.hasUpdate; });
}
return stackInfo;
}
// ═══════════════════════════════════════════════════════════════════
// Timers for async operations (plugin-specific to avoid collision with Unraid's global timers)
var composeTimers = {};
function showComposeSpinner() {
var $spinner = $('div.spinner.fixed');
if (!$spinner.length) {
return;
}
$spinner.css({'z-index': 100000});
$spinner.stop(true, true).show('slow');
}
function hideComposeSpinner() {
var $spinner = $('div.spinner.fixed');
if (!$spinner.length) {
return;
}
$spinner.stop(true, true).hide('slow');
}
// Load stack list asynchronously (namespaced to avoid conflict with Docker tab's loadlist)
function composeLoadlist() {
// Return a Promise so callers can reliably .then() / .catch() on completion
return new Promise(function(resolve, reject) {
composeTimers.load = setTimeout(function() {
showComposeSpinner('Loading stack list...');
}, 500);
$.get('/plugins/compose.manager/include/ComposeList.php')
.done(function(data) {
clearTimeout(composeTimers.load);
// Insert the loaded content
$('#compose_list').html(data);
// Signal load subscribers (e.g. dockerload cache) that the list changed
$(document).trigger('composeListRefreshed');
// Initialize UI components for the newly loaded content
initStackListUI();
// Debug: log initial per-stack rendered status icons (data-status attribute)
try {
var initialStatuses = [];
$('#compose_stacks tr.compose-sortable').each(function() {
var project = $(this).data('project');
var icon = $(this).find('.compose-status-icon').first();
var status = icon.attr('data-status') || icon.attr('class') || '';
initialStatuses.push({
project: project,
status: status
});
});
composeClientDebug('[composeLoadlist] initial-stack-statuses', {
stacks: initialStatuses
}, 'daemon', 'debug');
} catch (e) {}
// Normalize icons based on state text to ensure server-side render and
// client-side update logic agree (workaround for caching or older server HTML)
try {
$('#compose_stacks tr.compose-sortable').each(function() {
var $row = $(this);
var stateText = $row.find('.state').text().toLowerCase();
var $icon = $row.find('.compose-status-icon').first();
if (!$icon.length) return;
var desiredShape = null;
var desiredColor = 'grey-text';
if (stateText.indexOf('partial') !== -1) {
desiredShape = 'exclamation-circle';
desiredColor = 'orange-text';
} else if (stateText.indexOf('started') !== -1) {
desiredShape = 'play';
desiredColor = 'green-text';
} else if (stateText.indexOf('paused') !== -1) {
desiredShape = 'pause';
desiredColor = 'orange-text';
} else {
desiredShape = 'square';
desiredColor = 'grey-text';
}
// If icon already matches, skip
if (($icon.hasClass('fa-' + desiredShape) && $icon.hasClass(desiredColor))) return;
composeClientDebug('[composeLoadlist] normalize-icon', {
project: $row.data('project'),
stateText: stateText,
desiredShape: desiredShape,
desiredColor: desiredColor,
before: $icon.attr('class')
}, 'daemon', 'debug');
// Remove old fa-* classes, color classes and apply desired ones
$icon.removeClass(function(i, cls) {
return (cls.match(/fa-[^\s]+/g) || []).join(' ');
});
$icon.removeClass('green-text orange-text grey-text cyan-text');
$icon.addClass('fa fa-' + desiredShape + ' ' + desiredColor + ' compose-status-icon');
composeClientDebug('[composeLoadlist] normalize-icon-done', {
project: $row.data('project'),
after: $icon.attr('class')
}, 'daemon', 'debug');
});
} catch (e) {}
// Cleanup any temporary per-container spinners or leftover in-progress state
try {
$('#compose_list').find('.compose-container-spinner').each(function() {
var $sp = $(this);
var $wrap = $sp.closest('.hand');
$sp.remove();
$wrap.find('img').css('opacity', 1);
});
// Restore any state text preserved by setStackActionInProgress
$('#compose_stacks .state').each(function() {
var $s = $(this);
if ($s.data('orig-text')) {
$s.text($s.data('orig-text'));
$s.removeData('orig-text');
}
});
} catch (e) {}
// Hide compose spinner overlay
hideComposeSpinner();
// Show buttons now that content is loaded
$('input[type=button]').show();
// Notify other features (e.g. hide-from-docker) that compose list is ready
$(document).trigger('compose-list-loaded');
// Resolve the promise so callers know the list has been loaded
try { resolve(data); } catch (e) { resolve(); }
})
.fail(function(xhr, status, error) {
composeClientDebug('[composeLoadlist] failed', {
status: status,
error: error
}, 'daemon', 'error');
clearTimeout(composeTimers.load);
hideComposeSpinner();
$('#compose_list').html('<tr><td colspan="10" class="compose-status-danger" style="text-align:center;padding:20px;">Failed to load stack list. Please refresh the page.</td></tr>');
// Reject the promise so callers can handle the error
try { reject({xhr: xhr, status: status, error: error}); } catch (e) { reject(error); }
});
});
}
// Initialize UI components after stack list is loaded
function initStackListUI() {
// Initialize autostart switches - scope to compose_list to avoid conflict with Docker tab
// Avoid re-initializing switchButton on elements that may be re-rendered.
$('#compose_list .auto_start').each(function() {
var $el = $(this);
if ($el.data('switchbutton-initialized')) return;
$el.switchButton({
labels_placement: 'right',
on_label: "On",
off_label: "Off",
clear: false
});
$el.data('switchbutton-initialized', true);
});
// Ensure change handler is bound only once
$('#compose_list').off('change', '.auto_start').on('change', '.auto_start', function() {
var script = $(this).attr("data-scriptname");
var auto = $(this).prop('checked');
$.post(caURL, {
action: 'updateAutostart',
script: script,
autostart: auto
});
});
// Initialize context menus for stack icons
$('[id^="stack-"][data-stackid]').each(function() {
addComposeStackContext(this.id);
});
// Apply readmore to descriptions - scope to compose_stacks, exclude container detail rows
var $readmoreEls = $('#compose_stacks .docker_readmore').not('.stack-details-container .docker_readmore');
$readmoreEls.readmore('destroy');
$readmoreEls.readmore({
maxHeight: 32,
moreLink: "<a href='#' style='text-align:center'><i class='fa fa-chevron-down'></i></a>",
lessLink: "<a href='#' style='text-align:center'><i class='fa fa-chevron-up'></i></a>"
});
// Apply current view mode (advanced/basic) with centralized logic
applyListView(false);
// Seed expandedStacks from any rows rendered expanded server-side
$('.stack-details-row:visible').each(function() {
var stackId = this.id.replace('details-row-', '');
expandedStacks[stackId] = true;
});
// Load saved update status after list is loaded
loadSavedUpdateStatus();
}
// Load external stylesheets (non-critical styles — critical ones are inline above)
(function() {
var base = '<? autov("/plugins/compose.manager/sheets/ComboButton.css"); ?>';
var editor = '<? autov("/plugins/compose.manager/sheets/EditorModal.css"); ?>';
if (!$('link[href="' + base + '"]').length)
$('head').append($('<link rel="stylesheet" type="text/css" />').attr('href', base));
if (!$('link[href="' + editor + '"]').length)
$('head').append($('<link rel="stylesheet" type="text/css" />').attr('href', editor));
})();
function basename(path) {
return path.replace(/\\/g, '/').replace(/.*\//, '');
}
function dirname(path) {
return path.replace(/\\/g, '/').replace(/\/[^\/]*$/, '');
}
// Safely attempt to parse a JSON string; returns null on failure
function tryParseJson(str) {
if (!str || typeof str !== 'string') return null;
try { return JSON.parse(str); } catch (e) { return null; }
}
// Editor modal state
var editorModal = {
editors: {},
currentTab: 'compose',
originalContent: {},
modifiedTabs: new Set(),
currentProject: null,
validationTimeout: null,
// Settings state
originalSettings: {},
modifiedSettings: new Set(),
// Labels state
originalLabels: {},
modifiedLabels: new Set(),
labelsData: null // Stores the parsed compose and override data
};
// Debounce helper for validation
function debounceValidation(type, content) {
if (editorModal.validationTimeout) {
clearTimeout(editorModal.validationTimeout);
}
editorModal.validationTimeout = setTimeout(function() {
validateYaml(type, content);
}, 300);
}
// Calculate unRAID header offset dynamically
function updateModalOffset() {
var headerOffset = 0;
var header = document.getElementById('header');
var menu = document.getElementById('menu');
var tabs = document.querySelector('div.tabs');
if (header) {
headerOffset += header.offsetHeight;
}
if (menu) {
headerOffset += menu.offsetHeight;
}
if (tabs) {
headerOffset += tabs.offsetHeight;
}
// Add a small buffer
headerOffset += 10;
// Set CSS custom property
document.documentElement.style.setProperty('--unraid-header-offset', headerOffset + 'px');
var overlay = document.getElementById('editor-modal-overlay');
if (overlay) {
overlay.style.setProperty('--unraid-header-offset', headerOffset + 'px');
}
}
// Shared helpers for file-tree picker positioning and scroll tracking are now in common.js
// Please reference composePositionFileTreeForInput, composeTrackFileTreeForInput, composeBindFileTreeInputs from common.js
// Initialize editor modal
function initEditorModal() {
if (typeof ace === 'undefined') {
console.warn('Compose Manager: Ace editor not available. Editor will open without syntax highlighting.');
return;
}
// Initialize Ace editors for compose and env tabs only
['compose', 'env'].forEach(function(type) {
var editor = ace.edit('editor-' + type);
editor.setTheme(aceTheme);
editor.setShowPrintMargin(false);
editor.setOptions({
fontSize: '1.1rem',
tabSize: 2,
useSoftTabs: true,
wrap: true
});
// Disable workers to avoid loading worker-yaml.js / worker-sh.js —
// we already validate YAML client-side via js-yaml
editor.getSession().setUseWorker(false);
// Set mode based on type
if (type === 'env') {
editor.getSession().setMode('ace/mode/sh');
} else {
editor.getSession().setMode('ace/mode/yaml');
}
// Track modifications
editor.on('change', function() {
var currentContent = editor.getValue();
var originalContent = editorModal.originalContent[type] || '';
var tabEl = $('#editor-tab-' + type);
if (currentContent !== originalContent) {
editorModal.modifiedTabs.add(type);
tabEl.addClass('modified');
} else {
editorModal.modifiedTabs.delete(type);
tabEl.removeClass('modified');
}
updateSaveButtonState();
updateTabModifiedState();
debounceValidation(type, currentContent);
});
editorModal.editors[type] = editor;
});
// Initialize settings field change tracking
$('#settings-name, #settings-description, #settings-icon-url, #settings-webui-url, #settings-env-path, #settings-default-profile, #settings-external-compose-path').on('input change', function() {
var fieldId = this.id.replace('settings-', '');
var currentValue = $(this).val();
var originalValue = editorModal.originalSettings[fieldId] || '';
if (currentValue !== originalValue) {
editorModal.modifiedSettings.add(fieldId);
} else {
editorModal.modifiedSettings.delete(fieldId);
}
updateSaveButtonState();
updateTabModifiedState();
});
// Icon preview update with debounce
var settingsIconDebounce = null;
$('#settings-icon-url').on('input', function() {
var $input = $(this);
clearTimeout(settingsIconDebounce);
settingsIconDebounce = setTimeout(function() {
var url = $input.val().trim();
if (url && (url.startsWith('http://') || url.startsWith('https://'))) {
$('#settings-icon-preview-img').attr('src', url);
$('#settings-icon-preview').show();
} else {
$('#settings-icon-preview').hide();
}
}, 300);
});
// External compose path info toggle
$('#settings-external-compose-path').on('input', function() {
var path = $(this).val().trim();
if (path) {
$('#settings-external-compose-info').show();
} else {
$('#settings-external-compose-info').hide();
}
});
// Keyboard shortcuts - use namespaced event to avoid duplicates
$(document).off('keydown.editorModal').on('keydown.editorModal', function(e) {
if ($('#editor-modal-overlay').hasClass('active')) {
// Ctrl+S or Cmd+S to save current
if ((e.ctrlKey || e.metaKey) && e.key === 's') {
e.preventDefault();
saveCurrentTab();
}
// Escape to close
if (e.key === 'Escape') {
e.preventDefault();
closeEditorModal();
}
// Arrow key navigation for tabs
if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {
var $activeTab = $('.editor-tab.active');
if ($activeTab.is(':focus') || $activeTab.parent().find(':focus').length) {
e.preventDefault();
var tabs = ['compose', 'env', 'labels', 'settings'];
var currentIdx = tabs.indexOf(editorModal.currentTab);
var newIdx;
if (e.key === 'ArrowLeft') {
newIdx = currentIdx > 0 ? currentIdx - 1 : tabs.length - 1;
} else {
newIdx = currentIdx < tabs.length - 1 ? currentIdx + 1 : 0;
}
switchTab(tabs[newIdx]);
$('#editor-tab-' + tabs[newIdx]).focus();
}
}
// Focus trapping
if (e.key === 'Tab') {
var $modal = $('#editor-modal-overlay');
var $focusable = $modal.find('a, button, input, textarea, select, [tabindex]:not([tabindex="-1"])').filter(':visible:not(:disabled)');
if ($focusable.length === 0) return;
var first = $focusable[0];
var last = $focusable[$focusable.length - 1];
var activeElement = document.activeElement;
if (!$.contains($modal[0], activeElement)) {
e.preventDefault();
first.focus();
return;
}
if (!e.shiftKey && activeElement === last) {
e.preventDefault();
first.focus();
} else if (e.shiftKey && activeElement === first) {
e.preventDefault();
last.focus();
}
}
}
});
// Close modal when clicking on the overlay background (not the inner modal content)
$('#editor-modal-overlay').off('click.editorModal').on('click.editorModal', function(e) {
if (e.target === this) {
closeEditorModal();
}
});
}
// Switch between tabs (compose / env / labels / settings)
function switchTab(tabName) {
var validTabs = ['compose', 'env', 'labels', 'settings'];
if (validTabs.indexOf(tabName) === -1) {
console.error('Invalid tab name: ' + tabName);
return;
}
// Update tab buttons
$('.editor-tab').removeClass('active').attr('aria-selected', 'false');
$('#editor-tab-' + tabName).addClass('active').attr('aria-selected', 'true');
// Update panels and ensure inline display is correct (inline style may be persisted from tab host)
$('.editor-panel').each(function() {
var $panel = $(this);
if ($panel.attr('id') === 'editor-panel-' + tabName) {
$panel.addClass('active').css('display', 'flex');
} else {
$panel.removeClass('active').css('display', 'none');
}
});
editorModal.currentTab = tabName;
// Resize and focus editor if switching to compose or env tab
if ((tabName === 'compose' || tabName === 'env') && editorModal.editors[tabName]) {
try {
editorModal.editors[tabName].resize();
editorModal.editors[tabName].renderer.updateFull();
editorModal.editors[tabName].focus();
} catch (e) {
console.warn('Compose Manager: editor resize failed', e);
}
}
// Load labels data if switching to labels tab for the first time
if (tabName === 'labels' && !editorModal.labelsData) {
loadLabelsData();
}
}
function refreshEditorContents(type) {
if (!editorModal.editors[type]) return;
try {
editorModal.editors[type].resize();
editorModal.editors[type].renderer.updateFull();
} catch (e) {
console.warn('Compose Manager: refreshEditorContents failed for ' + type, e);
}
}
// Update the modified indicator on tabs
function updateTabModifiedState() {
// Compose tab
if (editorModal.modifiedTabs.has('compose')) {
$('#editor-tab-compose').addClass('modified');
} else {
$('#editor-tab-compose').removeClass('modified');
}
// Env tab
if (editorModal.modifiedTabs.has('env')) {
$('#editor-tab-env').addClass('modified');
} else {
$('#editor-tab-env').removeClass('modified');
}
// Labels tab
if (editorModal.modifiedLabels.size > 0) {
$('#editor-tab-labels').addClass('modified');
} else {
$('#editor-tab-labels').removeClass('modified');
}
// Settings tab
if (editorModal.modifiedSettings.size > 0) {
$('#editor-tab-settings').addClass('modified');
} else {
$('#editor-tab-settings').removeClass('modified');
}
}
// composeEscapeHtml / composeEscapeAttr are provided by common.js
// Update status cache per stack
var stackUpdateStatus = {};
// Load saved update status from server (called on page load)
// If auto-check is enabled and interval has elapsed, trigger a fresh check
// Also checks for pending rechecks from recent update operations
function loadSavedUpdateStatus() {
$.post(caURL, {
action: 'getSavedUpdateStatus'
}, function(data) {
if (data) {
try {
var response = JSON.parse(data);
if (response.result === 'success' && response.stacks) {
stackUpdateStatus = response.stacks;
// Update the UI for each stack with saved status
for (var stackName in response.stacks) {
var stackInfo = response.stacks[stackName];
updateStackUpdateUI(stackName, stackInfo);