mirror of
https://github.com/ChuckBuilds/LEDMatrix.git
synced 2026-10-05 06:45:09 +00:00
feat(web): Rotation, Operation History, Config Editor and Backup & Restore become ES-module pages (stage 2) (#727)
Rotation, Operation History, Config Editor and Backup & Restore become ES-module pages (stage 2): no inline scripts or onclick in the four partials, delegated data-action listeners, reads cancelled on swap-out, old globals kept as deprecated aliases through window.LEDMatrix, and four new DOM suites. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,5 +1,9 @@
|
||||
{% import 'v3/partials/_macros.html' as ui %}
|
||||
<div class="space-y-6" id="backup-restore-root">
|
||||
{# No inline script: static/v3/js/pages/backup-restore.js runs this page. Its
|
||||
buttons name an action (data-action) for one delegated listener. The page
|
||||
registry (static/v3/js/core/registry.js) starts it when this root appears
|
||||
and stops it when the partial is swapped away. #}
|
||||
<div class="space-y-6" id="backup-restore-root" data-page="backup-restore">
|
||||
|
||||
<!-- Security warning -->
|
||||
<div class="bg-red-50 border border-red-200 rounded-lg p-4">
|
||||
@@ -28,7 +32,7 @@
|
||||
Download a single ZIP with all of your settings so you can restore it later.
|
||||
</p>
|
||||
</div>
|
||||
<button onclick="exportBackup()" id="export-backup-btn"
|
||||
<button type="button" data-action="export" id="export-backup-btn"
|
||||
class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700">
|
||||
<i class="fas fa-download mr-2"></i>
|
||||
Download backup
|
||||
@@ -58,7 +62,7 @@
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<button onclick="validateRestoreFile()" id="validate-restore-btn"
|
||||
<button type="button" data-action="inspect" id="validate-restore-btn"
|
||||
class="inline-flex items-center px-3 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
|
||||
<i class="fas fa-check-circle mr-2"></i>
|
||||
Inspect file
|
||||
@@ -80,12 +84,12 @@
|
||||
</div>
|
||||
|
||||
<div class="mt-4 flex gap-2">
|
||||
<button onclick="runRestore()" id="run-restore-btn"
|
||||
<button type="button" data-action="restore" id="run-restore-btn"
|
||||
class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-green-600 hover:bg-green-700">
|
||||
<i class="fas fa-upload mr-2"></i>
|
||||
Restore now
|
||||
</button>
|
||||
<button onclick="clearRestore()"
|
||||
<button type="button" data-action="cancel"
|
||||
class="inline-flex items-center px-3 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
|
||||
Cancel
|
||||
</button>
|
||||
@@ -104,7 +108,7 @@
|
||||
<h2 class="text-lg font-semibold text-gray-900">Backup history</h2>
|
||||
<p class="mt-1 text-sm text-gray-600">Previously exported backups stored on this device.</p>
|
||||
</div>
|
||||
<button onclick="loadBackupList()"
|
||||
<button type="button" data-action="refresh"
|
||||
class="inline-flex items-center px-3 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
|
||||
<i class="fas fa-sync-alt mr-2"></i>
|
||||
Refresh
|
||||
@@ -115,237 +119,3 @@
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<script>
|
||||
(function () {
|
||||
let inspectedFile = null;
|
||||
|
||||
function notify(message, kind) {
|
||||
showNotification(message, kind || 'info');
|
||||
}
|
||||
|
||||
function formatSize(bytes) {
|
||||
if (!bytes) return '0 B';
|
||||
const units = ['B', 'KB', 'MB', 'GB'];
|
||||
let i = 0, size = bytes;
|
||||
while (size >= 1024 && i < units.length - 1) { size /= 1024; i++; }
|
||||
return size.toFixed(i === 0 ? 0 : 1) + ' ' + units[i];
|
||||
}
|
||||
|
||||
function escapeHtml(value) { return window.LEDEscape.html(value); }
|
||||
|
||||
async function loadPreview() {
|
||||
const el = document.getElementById('export-preview');
|
||||
try {
|
||||
const res = await fetch('/api/v3/backup/preview');
|
||||
const payload = await res.json();
|
||||
if (payload.status !== 'success') throw new Error(payload.message || 'Preview failed');
|
||||
const d = payload.data || {};
|
||||
el.innerHTML = `
|
||||
<ul class="list-disc pl-5 space-y-1">
|
||||
<li>Main config: <strong>${d.has_config ? 'yes' : 'no'}</strong></li>
|
||||
<li>Secrets: <strong>${d.has_secrets ? 'yes' : 'no'}</strong></li>
|
||||
<li>WiFi config: <strong>${d.has_wifi ? 'yes' : 'no'}</strong></li>
|
||||
<li>User fonts: <strong>${(d.user_fonts || []).length}</strong> ${d.user_fonts && d.user_fonts.length ? '(' + d.user_fonts.map(escapeHtml).join(', ') + ')' : ''}</li>
|
||||
<li>Plugin image uploads: <strong>${d.plugin_uploads || 0}</strong> file(s)</li>
|
||||
<li>Installed plugins: <strong>${(d.plugins || []).length}</strong></li>
|
||||
</ul>`;
|
||||
} catch (err) {
|
||||
el.textContent = 'Could not load preview: ' + err.message;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadBackupList() {
|
||||
const el = document.getElementById('backup-history');
|
||||
el.textContent = 'Loading…';
|
||||
try {
|
||||
const res = await fetch('/api/v3/backup/list');
|
||||
const payload = await res.json();
|
||||
if (payload.status !== 'success') throw new Error(payload.message || 'List failed');
|
||||
const entries = payload.data || [];
|
||||
if (!entries.length) {
|
||||
el.innerHTML = '<p>No backups have been created yet.</p>';
|
||||
return;
|
||||
}
|
||||
el.innerHTML = `
|
||||
<table class="min-w-full divide-y divide-gray-200">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="text-left py-2">Filename</th>
|
||||
<th class="text-left py-2">Size</th>
|
||||
<th class="text-left py-2">Created</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="divide-y divide-gray-100">
|
||||
${entries.map(e => `
|
||||
<tr>
|
||||
<td class="py-2 font-mono text-xs">${escapeHtml(e.filename)}</td>
|
||||
<td class="py-2">${formatSize(e.size)}</td>
|
||||
<td class="py-2">${escapeHtml(e.created_at)}</td>
|
||||
<td class="py-2 text-right space-x-2">
|
||||
<a href="/api/v3/backup/download/${encodeURIComponent(e.filename)}"
|
||||
class="text-blue-600 hover:underline">Download</a>
|
||||
<button data-filename="${escapeHtml(e.filename)}"
|
||||
class="text-red-600 hover:underline backup-delete-btn">Delete</button>
|
||||
</td>
|
||||
</tr>
|
||||
`).join('')}
|
||||
</tbody>
|
||||
</table>`;
|
||||
el.querySelectorAll('.backup-delete-btn').forEach(btn => {
|
||||
btn.addEventListener('click', () => deleteBackup(btn.dataset.filename));
|
||||
});
|
||||
} catch (err) {
|
||||
el.textContent = 'Could not load backups: ' + err.message;
|
||||
}
|
||||
}
|
||||
|
||||
async function exportBackup() {
|
||||
const btn = document.getElementById('export-backup-btn');
|
||||
btn.disabled = true;
|
||||
btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Creating…';
|
||||
try {
|
||||
const res = await fetch('/api/v3/backup/export', { method: 'POST' });
|
||||
const payload = await res.json();
|
||||
if (payload.status !== 'success') throw new Error(payload.message || 'Export failed');
|
||||
notify('Backup created: ' + payload.filename, 'success');
|
||||
// Trigger browser download immediately.
|
||||
window.location.href = '/api/v3/backup/download/' + encodeURIComponent(payload.filename);
|
||||
await loadBackupList();
|
||||
} catch (err) {
|
||||
notify('Export failed: ' + err.message, 'error');
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.innerHTML = '<i class="fas fa-download mr-2"></i>Download backup';
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteBackup(filename) {
|
||||
if (!confirm('Delete ' + filename + '?')) return;
|
||||
try {
|
||||
const res = await fetch('/api/v3/backup/' + encodeURIComponent(filename), { method: 'DELETE' });
|
||||
const payload = await res.json();
|
||||
if (payload.status !== 'success') throw new Error(payload.message || 'Delete failed');
|
||||
notify('Backup deleted', 'success');
|
||||
await loadBackupList();
|
||||
} catch (err) {
|
||||
notify('Delete failed: ' + err.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async function validateRestoreFile() {
|
||||
const input = document.getElementById('restore-file-input');
|
||||
if (!input.files || !input.files[0]) {
|
||||
notify('Choose a backup file first', 'error');
|
||||
return;
|
||||
}
|
||||
const file = input.files[0];
|
||||
const fd = new FormData();
|
||||
fd.append('backup_file', file);
|
||||
try {
|
||||
const res = await fetch('/api/v3/backup/validate', { method: 'POST', body: fd });
|
||||
const payload = await res.json();
|
||||
if (payload.status !== 'success') throw new Error(payload.message || 'Validation failed');
|
||||
inspectedFile = file;
|
||||
renderRestorePreview(payload.data);
|
||||
} catch (err) {
|
||||
notify('Invalid backup: ' + err.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
function renderRestorePreview(manifest) {
|
||||
const wrap = document.getElementById('restore-preview');
|
||||
const body = document.getElementById('restore-preview-body');
|
||||
const detected = manifest.detected_contents || [];
|
||||
const plugins = manifest.plugins || [];
|
||||
body.innerHTML = `
|
||||
<div><strong>Created:</strong> ${escapeHtml(manifest.created_at || 'unknown')}</div>
|
||||
<div><strong>Source host:</strong> ${escapeHtml(manifest.hostname || 'unknown')}</div>
|
||||
<div><strong>LEDMatrix version:</strong> ${escapeHtml(manifest.ledmatrix_version || 'unknown')}</div>
|
||||
<div><strong>Includes:</strong> ${detected.length ? detected.map(escapeHtml).join(', ') : '(nothing detected)'}</div>
|
||||
<div><strong>Plugins referenced:</strong> ${plugins.length ? plugins.map(p => escapeHtml(p.plugin_id)).join(', ') : 'none'}</div>
|
||||
`;
|
||||
wrap.classList.remove('hidden');
|
||||
}
|
||||
|
||||
function clearRestore() {
|
||||
inspectedFile = null;
|
||||
document.getElementById('restore-preview').classList.add('hidden');
|
||||
document.getElementById('restore-result').classList.add('hidden');
|
||||
document.getElementById('restore-file-input').value = '';
|
||||
}
|
||||
|
||||
async function runRestore() {
|
||||
if (!inspectedFile) {
|
||||
notify('Inspect the file before restoring', 'error');
|
||||
return;
|
||||
}
|
||||
if (!confirm('Restore from this backup? Current configuration will be overwritten.')) return;
|
||||
|
||||
const options = {
|
||||
restore_config: document.getElementById('opt-config').checked,
|
||||
restore_secrets: document.getElementById('opt-secrets').checked,
|
||||
restore_wifi: document.getElementById('opt-wifi').checked,
|
||||
restore_fonts: document.getElementById('opt-fonts').checked,
|
||||
restore_plugin_uploads: document.getElementById('opt-plugin-uploads').checked,
|
||||
reinstall_plugins: document.getElementById('opt-reinstall').checked,
|
||||
};
|
||||
const fd = new FormData();
|
||||
fd.append('backup_file', inspectedFile);
|
||||
fd.append('options', JSON.stringify(options));
|
||||
|
||||
const btn = document.getElementById('run-restore-btn');
|
||||
btn.disabled = true;
|
||||
btn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>Restoring…';
|
||||
try {
|
||||
const res = await fetch('/api/v3/backup/restore', { method: 'POST', body: fd });
|
||||
const payload = await res.json();
|
||||
if (payload.status !== 'success') {
|
||||
const msgs = (payload.data?.errors || []).join('; ');
|
||||
throw new Error(payload.message || msgs || 'Restore had errors');
|
||||
}
|
||||
const data = payload.data || {};
|
||||
const hasPartial = (data.plugins_failed || []).length > 0 || (data.errors || []).length > 0;
|
||||
const result = document.getElementById('restore-result');
|
||||
result.className = (hasPartial
|
||||
? 'bg-yellow-50 border-yellow-200 text-yellow-800'
|
||||
: 'bg-green-50 border-green-200 text-green-800') + ' border rounded-md p-4';
|
||||
result.classList.remove('hidden');
|
||||
result.innerHTML = `
|
||||
<h3 class="font-medium mb-2">${hasPartial ? 'Restore complete with warnings' : 'Restore complete'}</h3>
|
||||
<div><strong>Restored:</strong> ${(data.restored || []).map(escapeHtml).join(', ') || 'none'}</div>
|
||||
<div><strong>Skipped:</strong> ${(data.skipped || []).map(escapeHtml).join(', ') || 'none'}</div>
|
||||
<div><strong>Plugins installed:</strong> ${(data.plugins_installed || []).map(escapeHtml).join(', ') || 'none'}</div>
|
||||
<div><strong>Plugins failed:</strong> ${(data.plugins_failed || []).map(p => escapeHtml(p.plugin_id + ' (' + p.error + ')')).join(', ') || 'none'}</div>
|
||||
<div><strong>Errors:</strong> ${(data.errors || []).map(escapeHtml).join('; ') || 'none'}</div>
|
||||
${((data.restored || []).length || (data.plugins_installed || []).length) ? '<p class="mt-2">Restart the display service to apply all changes.</p>' : ''}
|
||||
`;
|
||||
notify(hasPartial ? 'Restore complete with warnings' : 'Restore complete', hasPartial ? 'warning' : 'success');
|
||||
} catch (err) {
|
||||
notify('Restore failed: ' + err.message, 'error');
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
btn.innerHTML = '<i class="fas fa-upload mr-2"></i>Restore now';
|
||||
}
|
||||
}
|
||||
|
||||
// Expose handlers to inline onclick attributes.
|
||||
window.exportBackup = exportBackup;
|
||||
window.loadBackupList = loadBackupList;
|
||||
window.validateRestoreFile = validateRestoreFile;
|
||||
window.clearRestore = clearRestore;
|
||||
window.runRestore = runRestore;
|
||||
|
||||
// Clear inspection state whenever the user picks a new file.
|
||||
document.getElementById('restore-file-input').addEventListener('change', function () {
|
||||
inspectedFile = null;
|
||||
document.getElementById('restore-preview').classList.add('hidden');
|
||||
document.getElementById('restore-result').classList.add('hidden');
|
||||
});
|
||||
|
||||
// Initial load.
|
||||
loadPreview();
|
||||
loadBackupList();
|
||||
})();
|
||||
</script>
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
{% import 'v3/partials/_macros.html' as ui %}
|
||||
<div class="bg-white rounded-lg shadow p-6">
|
||||
{# No inline script: static/v3/js/pages/durations.js starts the rotation-order
|
||||
list. The page registry (static/v3/js/core/registry.js) starts it when this
|
||||
root appears and stops it when the partial is swapped away. #}
|
||||
<div class="bg-white rounded-lg shadow p-6" data-page="durations">
|
||||
<div class="border-b border-gray-200 pb-4 mb-6">
|
||||
<h2 class="text-lg font-semibold text-gray-900">Rotation & Durations</h2>
|
||||
<p class="mt-1 text-sm text-gray-600">Set the order plugins rotate on the display and how long each screen is shown. Durations are in seconds.</p>
|
||||
@@ -77,34 +80,3 @@
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
(function () {
|
||||
// Shared drag-and-drop plugin list (static/v3/js/widgets/plugin-order-list.js,
|
||||
// same module the Vegas Scroll section uses).
|
||||
function initRotationOrderList(attempt) {
|
||||
const container = document.getElementById('rotation_plugin_order');
|
||||
if (!container) return;
|
||||
if (!window.PluginOrderList) {
|
||||
// Widget script is deferred; retry briefly, then surface a real
|
||||
// error instead of showing "Loading…" forever.
|
||||
if ((attempt || 0) < 50) {
|
||||
setTimeout(function() { initRotationOrderList((attempt || 0) + 1); }, 100);
|
||||
} else {
|
||||
container.textContent = 'Could not load the reorder widget — reload the page to try again.';
|
||||
container.className = 'text-sm text-red-500';
|
||||
}
|
||||
return;
|
||||
}
|
||||
window.PluginOrderList.init({
|
||||
containerId: 'rotation_plugin_order',
|
||||
orderInputId: 'rotation_plugin_order_value'
|
||||
});
|
||||
}
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', initRotationOrderList);
|
||||
} else {
|
||||
initRotationOrderList();
|
||||
}
|
||||
}());
|
||||
</script>
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
<div class="bg-white rounded-lg shadow p-6">
|
||||
{# No inline script: static/v3/js/pages/operation-history.js runs this page.
|
||||
The page registry (static/v3/js/core/registry.js) starts it when this root
|
||||
appears and stops it when the partial is swapped away. #}
|
||||
<div class="bg-white rounded-lg shadow p-6" data-page="operation-history">
|
||||
<div class="border-b border-gray-200 pb-4 mb-6">
|
||||
<h2 class="text-lg font-semibold text-gray-900">Operation History</h2>
|
||||
<p class="mt-1 text-sm text-gray-600">View history of plugin operations and configuration changes for debugging and auditing.</p>
|
||||
@@ -39,12 +42,12 @@
|
||||
|
||||
<div class="flex items-center space-x-2">
|
||||
<!-- Refresh -->
|
||||
<button id="refresh-history-btn" class="btn bg-blue-600 hover:bg-blue-700 text-white px-3 py-1 rounded text-sm">
|
||||
<button type="button" id="refresh-history-btn" class="btn bg-blue-600 hover:bg-blue-700 text-white px-3 py-1 rounded text-sm">
|
||||
<i class="fas fa-sync-alt mr-1"></i>Refresh
|
||||
</button>
|
||||
|
||||
<!-- Clear History -->
|
||||
<button id="clear-history-btn" class="btn bg-red-600 hover:bg-red-700 text-white px-3 py-1 rounded text-sm">
|
||||
<button type="button" id="clear-history-btn" class="btn bg-red-600 hover:bg-red-700 text-white px-3 py-1 rounded text-sm">
|
||||
<i class="fas fa-trash mr-1"></i>Clear
|
||||
</button>
|
||||
</div>
|
||||
@@ -81,307 +84,12 @@
|
||||
Showing <span id="history-start">0</span> to <span id="history-end">0</span> of <span id="history-total">0</span> operations
|
||||
</div>
|
||||
<div class="flex space-x-2">
|
||||
<button id="history-prev-btn" class="btn bg-gray-600 hover:bg-gray-700 text-white px-3 py-1 rounded text-sm disabled:opacity-50" disabled>
|
||||
<button type="button" id="history-prev-btn" class="btn bg-gray-600 hover:bg-gray-700 text-white px-3 py-1 rounded text-sm disabled:opacity-50" disabled>
|
||||
<i class="fas fa-chevron-left mr-1"></i>Previous
|
||||
</button>
|
||||
<button id="history-next-btn" class="btn bg-gray-600 hover:bg-gray-700 text-white px-3 py-1 rounded text-sm disabled:opacity-50" disabled>
|
||||
<button type="button" id="history-next-btn" class="btn bg-gray-600 hover:bg-gray-700 text-white px-3 py-1 rounded text-sm disabled:opacity-50" disabled>
|
||||
Next<i class="fas fa-chevron-right ml-1"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
(function() {
|
||||
let currentPage = 1;
|
||||
const pageSize = 50;
|
||||
let allHistory = [];
|
||||
let filteredHistory = [];
|
||||
|
||||
// Normalize status values so both server-side conventions match filter values.
|
||||
// The server may return "completed" or "success" for successful operations,
|
||||
// and "error" or "failed" for failures.
|
||||
function normalizeStatus(status) {
|
||||
const s = (status || '').toLowerCase();
|
||||
if (s === 'completed' || s === 'success') return 'success';
|
||||
if (s === 'error' || s === 'failed') return 'failed';
|
||||
return s;
|
||||
}
|
||||
|
||||
// Load operation history
|
||||
async function loadHistory() {
|
||||
try {
|
||||
const response = await fetch('/api/v3/plugins/operation/history?limit=1000');
|
||||
const data = await response.json();
|
||||
|
||||
if (data.status === 'success') {
|
||||
allHistory = data.data || [];
|
||||
applyFilters();
|
||||
} else {
|
||||
console.error('Failed to load history:', data.message);
|
||||
showError('Failed to load operation history');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error loading history:', error);
|
||||
showError('Error loading operation history');
|
||||
}
|
||||
}
|
||||
|
||||
// Apply filters
|
||||
function applyFilters() {
|
||||
const pluginFilter = document.getElementById('history-plugin-filter')?.value || '';
|
||||
const typeFilter = document.getElementById('history-type-filter')?.value || '';
|
||||
const statusFilter = document.getElementById('history-status-filter')?.value || '';
|
||||
const searchTerm = (document.getElementById('history-search')?.value || '').toLowerCase();
|
||||
|
||||
filteredHistory = allHistory.filter(record => {
|
||||
if (pluginFilter && record.plugin_id !== pluginFilter) return false;
|
||||
if (typeFilter && record.operation_type !== typeFilter) return false;
|
||||
if (statusFilter && normalizeStatus(record.status) !== statusFilter) return false;
|
||||
if (searchTerm) {
|
||||
const searchable = [
|
||||
record.operation_type,
|
||||
record.plugin_id,
|
||||
record.status,
|
||||
record.user,
|
||||
record.error,
|
||||
JSON.stringify(record.details || {})
|
||||
].join(' ').toLowerCase();
|
||||
if (!searchable.includes(searchTerm)) return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
renderHistory();
|
||||
}
|
||||
|
||||
// Render history table
|
||||
function renderHistory() {
|
||||
const tbody = document.getElementById('history-table-body');
|
||||
if (!tbody) return;
|
||||
|
||||
const start = (currentPage - 1) * pageSize;
|
||||
const end = Math.min(start + pageSize, filteredHistory.length);
|
||||
const pageData = filteredHistory.slice(start, end);
|
||||
|
||||
if (pageData.length === 0) {
|
||||
tbody.innerHTML = `
|
||||
<tr>
|
||||
<td colspan="6" class="px-6 py-4 text-center text-gray-500">
|
||||
No operations found
|
||||
</td>
|
||||
</tr>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
tbody.innerHTML = pageData.map(record => {
|
||||
const timestamp = new Date(record.timestamp || record.created_at || Date.now());
|
||||
const timeStr = timestamp.toLocaleString();
|
||||
const normalized = normalizeStatus(record.status);
|
||||
const statusClass = getStatusClass(normalized);
|
||||
const operationType = record.operation_type || 'unknown';
|
||||
const pluginId = record.plugin_id || '-';
|
||||
const user = record.user || '-';
|
||||
const error = record.error ? `<div class="text-red-600 text-xs mt-1">${escapeHtml(record.error)}</div>` : '';
|
||||
|
||||
// Build a concise details summary
|
||||
let detailsSummary = '';
|
||||
const d = record.details;
|
||||
if (d) {
|
||||
const parts = [];
|
||||
if (d.version) parts.push(`v${d.version}`);
|
||||
if (d.branch) parts.push(`branch: ${d.branch}`);
|
||||
if (d.commit) parts.push(`commit: ${String(d.commit).substring(0, 7)}`);
|
||||
if (d.previous_commit && d.commit && d.previous_commit !== d.commit) {
|
||||
parts.push(`from: ${String(d.previous_commit).substring(0, 7)}`);
|
||||
}
|
||||
if (d.preserve_config !== undefined) parts.push(d.preserve_config ? 'config preserved' : 'config removed');
|
||||
detailsSummary = parts.length > 0 ? `<span class="text-xs text-gray-500">${escapeHtml(parts.join(' | '))}</span>` : '';
|
||||
}
|
||||
|
||||
return `
|
||||
<tr class="hover:bg-gray-50">
|
||||
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${escapeHtml(timeStr)}</td>
|
||||
<td class="px-6 py-4 whitespace-nowrap text-sm">
|
||||
<span class="px-2 py-1 text-xs font-medium rounded ${getOperationTypeClass(operationType)}">
|
||||
${escapeHtml(operationType)}
|
||||
</span>
|
||||
</td>
|
||||
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">${escapeHtml(pluginId)}</td>
|
||||
<td class="px-6 py-4 whitespace-nowrap text-sm">
|
||||
<span class="px-2 py-1 text-xs font-medium rounded ${statusClass}">
|
||||
${escapeHtml(normalized)}
|
||||
</span>
|
||||
</td>
|
||||
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${escapeHtml(user)}</td>
|
||||
<td class="px-6 py-4 text-sm text-gray-500">
|
||||
${detailsSummary || '-'}
|
||||
${error}
|
||||
</td>
|
||||
</tr>
|
||||
`;
|
||||
}).join('');
|
||||
|
||||
// Update pagination
|
||||
document.getElementById('history-start').textContent = filteredHistory.length > 0 ? start + 1 : 0;
|
||||
document.getElementById('history-end').textContent = end;
|
||||
document.getElementById('history-total').textContent = filteredHistory.length;
|
||||
|
||||
// Update pagination buttons
|
||||
const prevBtn = document.getElementById('history-prev-btn');
|
||||
const nextBtn = document.getElementById('history-next-btn');
|
||||
if (prevBtn) prevBtn.disabled = currentPage === 1;
|
||||
if (nextBtn) nextBtn.disabled = end >= filteredHistory.length;
|
||||
}
|
||||
|
||||
// Helper functions
|
||||
function getStatusClass(status) {
|
||||
if (status === 'success') return 'bg-green-100 text-green-800';
|
||||
if (status === 'failed') return 'bg-red-100 text-red-800';
|
||||
return 'bg-gray-100 text-gray-800';
|
||||
}
|
||||
|
||||
function getOperationTypeClass(type) {
|
||||
const typeLower = (type || '').toLowerCase();
|
||||
if (typeLower === 'install') {
|
||||
return 'bg-blue-100 text-blue-800';
|
||||
} else if (typeLower === 'update') {
|
||||
return 'bg-purple-100 text-purple-800';
|
||||
} else if (typeLower === 'uninstall') {
|
||||
return 'bg-red-100 text-red-800';
|
||||
} else if (typeLower === 'enable') {
|
||||
return 'bg-green-100 text-green-800';
|
||||
} else if (typeLower === 'disable') {
|
||||
return 'bg-yellow-100 text-yellow-800';
|
||||
} else if (typeLower === 'configure') {
|
||||
return 'bg-teal-100 text-teal-800';
|
||||
}
|
||||
return 'bg-gray-100 text-gray-800';
|
||||
}
|
||||
|
||||
function escapeHtml(text) { return window.LEDEscape.html(text); }
|
||||
|
||||
function showError(message) {
|
||||
showNotification(message, 'error');
|
||||
}
|
||||
|
||||
// Populate plugin filter
|
||||
async function populatePluginFilter() {
|
||||
try {
|
||||
// Use PluginAPI if available, otherwise fall back to direct fetch
|
||||
let data;
|
||||
if (window.PluginAPI && window.PluginAPI.getInstalledPlugins) {
|
||||
const plugins = await window.PluginAPI.getInstalledPlugins();
|
||||
data = { status: 'success', data: { plugins: plugins } };
|
||||
} else {
|
||||
const response = await fetch('/api/v3/plugins/installed');
|
||||
data = await response.json();
|
||||
}
|
||||
|
||||
if (data.status === 'success' && data.data) {
|
||||
const select = document.getElementById('history-plugin-filter');
|
||||
if (select) {
|
||||
const plugins = (data.data.plugins || []).map(p => p.id).filter(Boolean);
|
||||
plugins.forEach(pluginId => {
|
||||
const option = document.createElement('option');
|
||||
option.value = pluginId;
|
||||
option.textContent = pluginId;
|
||||
select.appendChild(option);
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error loading plugins for filter:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Event listeners
|
||||
function setupEventListeners() {
|
||||
const refreshBtn = document.getElementById('refresh-history-btn');
|
||||
if (refreshBtn) {
|
||||
refreshBtn.addEventListener('click', () => {
|
||||
loadHistory();
|
||||
});
|
||||
}
|
||||
|
||||
const clearBtn = document.getElementById('clear-history-btn');
|
||||
if (clearBtn) {
|
||||
clearBtn.addEventListener('click', async () => {
|
||||
if (confirm('Are you sure you want to clear the operation history? This cannot be undone.')) {
|
||||
try {
|
||||
const response = await fetch('/api/v3/plugins/operation/history', { method: 'DELETE' });
|
||||
const data = await response.json();
|
||||
if (data.status === 'success') {
|
||||
allHistory = [];
|
||||
applyFilters();
|
||||
} else {
|
||||
showError(data.message || 'Failed to clear history');
|
||||
}
|
||||
} catch (error) {
|
||||
showError('Error clearing history');
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const prevBtn = document.getElementById('history-prev-btn');
|
||||
if (prevBtn) {
|
||||
prevBtn.addEventListener('click', () => {
|
||||
if (currentPage > 1) {
|
||||
currentPage--;
|
||||
renderHistory();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const nextBtn = document.getElementById('history-next-btn');
|
||||
if (nextBtn) {
|
||||
nextBtn.addEventListener('click', () => {
|
||||
const start = (currentPage - 1) * pageSize;
|
||||
const end = Math.min(start + pageSize, filteredHistory.length);
|
||||
if (end < filteredHistory.length) {
|
||||
currentPage++;
|
||||
renderHistory();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Filter change listeners
|
||||
['history-plugin-filter', 'history-type-filter', 'history-status-filter'].forEach(id => {
|
||||
const element = document.getElementById(id);
|
||||
if (element) {
|
||||
element.addEventListener('change', () => {
|
||||
currentPage = 1;
|
||||
applyFilters();
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const searchInput = document.getElementById('history-search');
|
||||
if (searchInput) {
|
||||
let searchTimeout;
|
||||
searchInput.addEventListener('input', () => {
|
||||
clearTimeout(searchTimeout);
|
||||
searchTimeout = setTimeout(() => {
|
||||
currentPage = 1;
|
||||
applyFilters();
|
||||
}, 300);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
setupEventListeners();
|
||||
populatePluginFilter();
|
||||
loadHistory();
|
||||
});
|
||||
} else {
|
||||
setupEventListeners();
|
||||
populatePluginFilter();
|
||||
loadHistory();
|
||||
}
|
||||
})();
|
||||
</script>
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
<div class="space-y-6">
|
||||
{# No inline script: static/v3/js/pages/raw-json.js runs this page. Its buttons
|
||||
name an action and an editor (data-action, data-editor) for one delegated
|
||||
listener. The page registry (static/v3/js/core/registry.js) starts it when
|
||||
this root appears and stops it when the partial is swapped away. #}
|
||||
<div class="space-y-6" data-page="raw-json">
|
||||
<!-- Config.json Editor -->
|
||||
<div class="bg-white rounded-lg shadow p-6">
|
||||
<div class="border-b border-gray-200 pb-4 mb-6">
|
||||
@@ -8,17 +12,17 @@
|
||||
<p class="mt-1 text-sm text-gray-600">{{ main_config_path }}</p>
|
||||
</div>
|
||||
<div class="flex gap-2">
|
||||
<button onclick="formatJson('main-config-editor', 'main-config-validation')"
|
||||
<button type="button" data-action="format" data-editor="main"
|
||||
class="inline-flex items-center px-3 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
|
||||
<i class="fas fa-align-left mr-2"></i>
|
||||
Format JSON
|
||||
</button>
|
||||
<button onclick="manualValidateJson('main-config-editor', 'main-config-validation')"
|
||||
<button type="button" data-action="validate" data-editor="main"
|
||||
class="inline-flex items-center px-3 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-yellow-600 hover:bg-yellow-700">
|
||||
<i class="fas fa-check-circle mr-2"></i>
|
||||
Validate JSON
|
||||
</button>
|
||||
<button onclick="saveMainConfig()"
|
||||
<button type="button" data-action="save" data-editor="main"
|
||||
class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700">
|
||||
<i class="fas fa-save mr-2"></i>
|
||||
Save
|
||||
@@ -59,17 +63,17 @@
|
||||
<p class="mt-1 text-sm text-gray-600">{{ secrets_config_path }}</p>
|
||||
</div>
|
||||
<div class="flex gap-2">
|
||||
<button onclick="formatJson('secrets-config-editor', 'secrets-config-validation')"
|
||||
<button type="button" data-action="format" data-editor="secrets"
|
||||
class="inline-flex items-center px-3 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">
|
||||
<i class="fas fa-align-left mr-2"></i>
|
||||
Format JSON
|
||||
</button>
|
||||
<button onclick="manualValidateJson('secrets-config-editor', 'secrets-config-validation')"
|
||||
<button type="button" data-action="validate" data-editor="secrets"
|
||||
class="inline-flex items-center px-3 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-yellow-600 hover:bg-yellow-700">
|
||||
<i class="fas fa-check-circle mr-2"></i>
|
||||
Validate JSON
|
||||
</button>
|
||||
<button onclick="saveSecretsConfig()"
|
||||
<button type="button" data-action="save" data-editor="secrets"
|
||||
class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700">
|
||||
<i class="fas fa-save mr-2"></i>
|
||||
Save
|
||||
@@ -101,218 +105,3 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Format JSON with proper indentation
|
||||
function formatJson(editorId, validationDivId) {
|
||||
const textarea = document.getElementById(editorId);
|
||||
const jsonText = textarea.value;
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(jsonText);
|
||||
const formatted = JSON.stringify(parsed, null, 4);
|
||||
textarea.value = formatted;
|
||||
|
||||
// Auto-validate after formatting
|
||||
validateJSON(editorId, validationDivId);
|
||||
showNotification('JSON formatted successfully!', 'success');
|
||||
} catch (error) {
|
||||
showNotification('Cannot format invalid JSON: ' + error.message, 'error');
|
||||
validateJSON(editorId, validationDivId);
|
||||
}
|
||||
}
|
||||
|
||||
// Manual validation with detailed feedback
|
||||
function manualValidateJson(editorId, validationDivId) {
|
||||
const textarea = document.getElementById(editorId);
|
||||
const validation = document.getElementById(validationDivId);
|
||||
const jsonText = textarea.value;
|
||||
|
||||
if (!textarea || !validation) return;
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(jsonText);
|
||||
validation.innerHTML = `
|
||||
<div class="p-3 bg-green-50 border border-green-200 rounded-md">
|
||||
<div class="flex items-start">
|
||||
<i class="fas fa-check-circle text-green-600 text-xl mr-3 mt-1"></i>
|
||||
<div>
|
||||
<div class="font-semibold text-green-800">✓ JSON is valid!</div>
|
||||
<div class="text-sm text-green-700 mt-1">
|
||||
✓ Valid JSON syntax<br>
|
||||
✓ Proper structure<br>
|
||||
✓ No syntax errors detected
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
showNotification('JSON validation successful!', 'success');
|
||||
} catch (e) {
|
||||
validation.innerHTML = `
|
||||
<div class="p-3 bg-red-50 border border-red-200 rounded-md">
|
||||
<div class="flex items-start">
|
||||
<i class="fas fa-times-circle text-red-600 text-xl mr-3 mt-1"></i>
|
||||
<div>
|
||||
<div class="font-semibold text-red-800">✗ Invalid JSON syntax</div>
|
||||
<div class="text-sm text-red-700 mt-1">
|
||||
<strong>Error:</strong> ${window.LEDEscape.html(e.message)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
showNotification('JSON validation failed: ' + e.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-validate JSON as user types (simple version)
|
||||
function validateJSON(editor, validationDiv) {
|
||||
const textarea = document.getElementById(editor);
|
||||
const validation = document.getElementById(validationDiv);
|
||||
|
||||
if (!textarea || !validation) return true;
|
||||
|
||||
try {
|
||||
JSON.parse(textarea.value);
|
||||
validation.innerHTML = '<span class="text-green-600"><i class="fas fa-check-circle mr-1"></i>Valid JSON</span>';
|
||||
return true;
|
||||
} catch (e) {
|
||||
validation.innerHTML = '<span class="text-red-600"><i class="fas fa-times-circle mr-1"></i>Invalid JSON: ' + e.message + '</span>';
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-validate on input
|
||||
document.getElementById('main-config-editor')?.addEventListener('input', function() {
|
||||
validateJSON('main-config-editor', 'main-config-validation');
|
||||
});
|
||||
|
||||
document.getElementById('secrets-config-editor')?.addEventListener('input', function() {
|
||||
validateJSON('secrets-config-editor', 'secrets-config-validation');
|
||||
});
|
||||
|
||||
// Initial validation
|
||||
setTimeout(() => {
|
||||
validateJSON('main-config-editor', 'main-config-validation');
|
||||
validateJSON('secrets-config-editor', 'secrets-config-validation');
|
||||
}, 100);
|
||||
|
||||
function saveMainConfig() {
|
||||
const textarea = document.getElementById('main-config-editor');
|
||||
|
||||
// Validate JSON first
|
||||
if (!validateJSON('main-config-editor', 'main-config-validation')) {
|
||||
showNotification('Invalid JSON! Please fix errors before saving.', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const config = JSON.parse(textarea.value);
|
||||
|
||||
// Save via API
|
||||
fetch('/api/v3/config/raw/main', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify(config)
|
||||
})
|
||||
.then(async response => {
|
||||
// Store status and statusText before parsing
|
||||
const status = response.status;
|
||||
const statusText = response.statusText;
|
||||
|
||||
// Try to parse JSON response
|
||||
let data;
|
||||
try {
|
||||
data = await response.json();
|
||||
} catch (parseError) {
|
||||
// If JSON parsing fails, throw generic HTTP error
|
||||
throw new Error(`HTTP ${status}: ${statusText}`);
|
||||
}
|
||||
|
||||
// Handle non-OK responses
|
||||
if (!response.ok) {
|
||||
// Extract specific error message from API response if available
|
||||
const errorMessage = data.message || data.status || statusText;
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
// Handle successful responses
|
||||
if (data.status === 'success') {
|
||||
showNotification('config.json saved successfully!', 'success');
|
||||
} else {
|
||||
showNotification('Error saving config.json: ' + (data.message || 'Unknown error'), 'error');
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
// Preserve the error message that was intentionally thrown
|
||||
showNotification('Error saving config.json: ' + (error.message || 'An error occurred'), 'error');
|
||||
});
|
||||
} catch (e) {
|
||||
showNotification('Invalid JSON: ' + e.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
function saveSecretsConfig() {
|
||||
const textarea = document.getElementById('secrets-config-editor');
|
||||
|
||||
// Validate JSON first
|
||||
if (!validateJSON('secrets-config-editor', 'secrets-config-validation')) {
|
||||
showNotification('Invalid JSON! Please fix errors before saving.', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const config = JSON.parse(textarea.value);
|
||||
|
||||
// Save via API
|
||||
fetch('/api/v3/config/raw/secrets', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify(config)
|
||||
})
|
||||
.then(async response => {
|
||||
// Store status and statusText before parsing
|
||||
const status = response.status;
|
||||
const statusText = response.statusText;
|
||||
|
||||
// Try to parse JSON response
|
||||
let data;
|
||||
try {
|
||||
data = await response.json();
|
||||
} catch (parseError) {
|
||||
// If JSON parsing fails, throw generic HTTP error
|
||||
throw new Error(`HTTP ${status}: ${statusText}`);
|
||||
}
|
||||
|
||||
// Handle non-OK responses
|
||||
if (!response.ok) {
|
||||
// Extract specific error message from API response if available
|
||||
const errorMessage = data.message || data.status || statusText;
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
|
||||
// Handle successful responses
|
||||
if (data.status === 'success') {
|
||||
showNotification('config_secrets.json saved successfully!', 'success');
|
||||
} else {
|
||||
showNotification('Error saving config_secrets.json: ' + (data.message || 'Unknown error'), 'error');
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
// Preserve the error message that was intentionally thrown
|
||||
showNotification('Error saving config_secrets.json: ' + (error.message || 'An error occurred'), 'error');
|
||||
});
|
||||
} catch (e) {
|
||||
showNotification('Invalid JSON: ' + e.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
// showNotification is provided by the notification widget (notification.js)
|
||||
// No local definition needed - uses window.showNotification from the widget
|
||||
</script>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user