mirror of
https://github.com/ChuckBuilds/LEDMatrix.git
synced 2026-10-04 22:35:08 +00:00
* refactor(web): drop validators nothing calls escape_html, validate_image_url, validate_font_awesome_class, validate_mime_type, validate_numeric_range, validate_string_length and sanitize_plugin_config had no callers outside their own tests. Only validate_file_upload (fonts upload) is imported by the web interface. dedup_unique_arrays is kept: its one caller in save_plugin_config was removed by the unrelated sync PR (#330), which looks accidental. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(api): remove the music-auth and of-the-day JSON routes POST /plugins/authenticate/spotify and /plugins/authenticate/ytm had no caller but their tests: the music plugin authenticates through its web_ui_actions (authenticate_spotify.py / authenticate_ytm.py) via /plugins/action. POST /plugins/of-the-day/json/upload and /json/delete looked the plugin up by the id ledmatrix-of-the-day (its manifest id is of-the-day), were reachable only from a file_type "json" upload field that no schema declares, and put the plugin directory on sys.path per request to import scripts.update_config. of-the-day manages its files through plugin-file-manager and its own web_ui_actions. The of-the-day branch of GET /plugins/config stays: it matches the real manifest id and still merges the on-disk category files into the form. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(api): read managers only from the blueprints api_v3/__init__.py and pages_v3.py declared module globals (plugin_store_manager, saved_repositories_manager, schema_manager, operation_queue, plugin_state_manager, operation_history, sync_manager, config_manager, plugin_manager) that nothing assigns: app.py sets the managers as attributes on the Blueprint objects, and every route reads them there. The one reader, backup restore's fallback to the module plugin_store_manager, could only ever fall back to None. _ensure_cache_manager() built a second CacheManager in the web process instead of using the one app.py puts on api_v3. The display routes now read api_v3.cache_manager, creating it on the blueprint only when nothing set it (the same None handling as the /cache routes). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(web): drop run.sh and the unused log_config_change web_interface/run.sh was referenced only by web_interface/README.md; the service starts the UI through scripts/utils/start_web_conditionally.py and the README already documents `python3 web_interface/start.py`. log_config_change() in web_interface/logging_config.py was never called. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(web): delete unreferenced store_manager.js, diff_viewer.js, htmx-sse.js - js/plugins/store_manager.js (window.PluginStoreManager) and js/config/diff_viewer.js (window.ConfigDiffViewer) were loaded on every page but nothing reads either global. - htmx-sse.js (plus its CDN fallback) was loaded after HTMX, but no template or plugin page uses sse-connect / hx-ext="sse": the live streams run through LEDStreams in app-shell.js. js/plugins/state_manager.js stays: install_manager.js's updateAll() reads and refreshes window.PluginStateManager. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(web): remove app.js helpers nothing calls - hexToRgb, rgbToHex, validateForm, uploadFont and switchTab (whose 'switch-tab' event had no listener) have no caller in the templates, static JS or the plugin monorepo. - installPlugin: plugins_manager.js (loaded last) assigns window.installPlugin, and its own store cards are the only callers. - The showNotification fallback could never install: app-shell.js is deferred ahead of app.js and defines the same fallback at top level. - performanceMonitor only logged with ?debug=perf and read an unset this.measures; the marks it took on every load had no reader. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(web): drop app-shell.js refreshPlugin A top-level function in app-shell.js, so a window global, but nothing calls it (no inline handler, no window lookup, no string-built name). The other plugin actions in that block stay. updatePlugin is the live window.updatePlugin: plugins_manager.js only installs its own copy when none exists. uninstallPlugin/pollUninstallOperation, updateAllPlugins, executePluginAction and toggleNestedSection are replaced by later deferred scripts, but a click that lands while those scripts are still downloading reaches the app-shell copies, so removing them is not a pure no-op. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(web): remove definitions plugins_manager.js always overrides All of these are replaced before anything can call them, checked against the load order in base.html and the live window.* values: - openOnDemandModal/requestOnDemandStop stubs: the IIFE later in the same script assigns the real functions synchronously. - updatePlugin and uninstallPlugin stubs (`window.X || stub`): app-shell.js already defined both, so the fallback never installed. Same for the later updatePlugin override, gated on the live function containing '[UPDATE]', which app-shell.js's never does. - The first addArrayObjectItem/removeArrayObjectItem: reassigned by the top-level copies after the IIFE. - The first `function formatDate` in the IIFE: a later declaration of the same name in the same scope wins. - deleteUploadedImage, getCurrentImages, showUploadProgress, formatFileSize and getScheduleSummary: character-for-character copies of js/widgets/file-upload.js, which stays the owner. - `typeof X === 'undefined'` fallbacks and `typeof X !== 'undefined'` re-exports after the IIFE: always false, or a self-assignment. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(web): render the shell directly and delete index.html index.html extended base.html with {% block content %}, but base.html defines no blocks, so none of index.html ever rendered: rendering both with jinja2 gives byte-identical output. index() still loaded the config, read config.json and config_secrets.json raw and json.dumps'd them on every page load for variables base.html never reads, and flashed errors that base.html never shows. It now renders base.html with no context. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(web): stop htmx-config.js replacing console.error and console.warn It swapped both globals for filters that dropped any error mentioning insertBefore / "Cannot read properties of null" when "htmx" appeared in the message or stack, and a list of Permissions-Policy warnings. That hid real errors from every script on the page, and made every logged error and warning report htmx-config.js as its source. The beforeSwap target validation above it, which prevents the insertBefore errors in the first place, stays. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(web): quiet the widget load announcements and debug logs About 30 lines hit the console on every page load: one "... widget registered" per widget file, one "[WidgetRegistry] Registered widget: X" per registration, plus the registry, base widget and plugin loader announcing themselves. The load-time announcements are removed; the per-call ones (registry register, plugin widget loads, "Render called") now go through the page's debugLog switch (localStorage.pluginDebug), guarded because the widgets also load in node tests without it. fonts.html and wifi.html debug logging goes through debugLog as well. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(api): drop the removed music-auth and of-the-day JSON routes Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
374 lines
15 KiB
JavaScript
374 lines
15 KiB
JavaScript
/* global showNotification */
|
|
// LED Matrix v3 JavaScript
|
|
// Additional helpers for HTMX and Alpine.js integration
|
|
|
|
// HTMX response handlers
|
|
document.body.addEventListener('htmx:beforeRequest', function(event) {
|
|
// Show loading states for buttons
|
|
const btn = event.target.closest('button, .btn');
|
|
if (btn) {
|
|
btn.classList.add('loading');
|
|
const textEl = btn.querySelector('.btn-text');
|
|
if (textEl) textEl.style.opacity = '0.5';
|
|
}
|
|
});
|
|
|
|
document.body.addEventListener('htmx:afterRequest', function(event) {
|
|
// Remove loading states
|
|
const btn = event.target.closest('button, .btn');
|
|
if (btn) {
|
|
btn.classList.remove('loading');
|
|
const textEl = btn.querySelector('.btn-text');
|
|
if (textEl) textEl.style.opacity = '1';
|
|
}
|
|
|
|
// Handle response notifications
|
|
const response = event.detail.xhr;
|
|
if (response && response.responseText) {
|
|
try {
|
|
const data = JSON.parse(response.responseText);
|
|
if (data.message) {
|
|
showNotification(data.message, data.status || 'info');
|
|
}
|
|
} catch {
|
|
// Not JSON, ignore
|
|
}
|
|
}
|
|
|
|
// Main-config saves (display hardware, rotation/durations, general) only
|
|
// take effect after a display-service restart — surface the reminder
|
|
// banner. Plugin config saves apply live and are deliberately excluded.
|
|
try {
|
|
const cfg = event.detail.requestConfig;
|
|
if (cfg && cfg.verb === 'post' &&
|
|
(cfg.path || '').includes('/api/v3/config/main') &&
|
|
response && response.status >= 200 && response.status < 300) {
|
|
window.showRestartPending();
|
|
}
|
|
} catch { /* banner is best-effort */ }
|
|
});
|
|
|
|
// ===== Unsaved-changes guard =====
|
|
// Plugin config panels are Alpine x-if templates: navigating away DESTROYS
|
|
// the panel and revisiting re-fetches it, silently discarding any edits.
|
|
// (System tabs use x-show + data-loaded and persist, so they're exempt.)
|
|
// Track dirty forms and confirm before a lossy navigation.
|
|
(function() {
|
|
function markDirty(e) {
|
|
const form = e.target && e.target.closest ? e.target.closest('form') : null;
|
|
if (form) form.setAttribute('data-dirty', '');
|
|
}
|
|
document.body.addEventListener('input', markDirty);
|
|
document.body.addEventListener('change', markDirty);
|
|
|
|
// A successful submit makes the form clean again
|
|
document.body.addEventListener('htmx:afterRequest', function(event) {
|
|
const xhr = event.detail.xhr;
|
|
const form = event.detail.elt && event.detail.elt.closest ? event.detail.elt.closest('form') : null;
|
|
if (form && xhr && xhr.status >= 200 && xhr.status < 300) {
|
|
form.removeAttribute('data-dirty');
|
|
}
|
|
});
|
|
|
|
// Capture phase so this runs before Alpine's bubbling @click switches tabs
|
|
document.addEventListener('click', function(e) {
|
|
const tabBtn = e.target && e.target.closest ? e.target.closest('.nav-tab') : null;
|
|
if (!tabBtn) return;
|
|
const lossy = Array.prototype.filter.call(
|
|
document.querySelectorAll('.plugin-config-tab form[data-dirty]'),
|
|
function(f) { return f.offsetParent !== null; }
|
|
);
|
|
if (lossy.length === 0) return;
|
|
if (!window.confirm('You have unsaved plugin settings — leaving this page will discard them. Leave anyway?')) {
|
|
e.stopPropagation();
|
|
e.preventDefault();
|
|
}
|
|
}, true);
|
|
|
|
// Full page unload loses every panel's edits
|
|
window.addEventListener('beforeunload', function(e) {
|
|
const dirty = Array.prototype.some.call(
|
|
document.querySelectorAll('form[data-dirty]'),
|
|
function(f) { return f.offsetParent !== null; }
|
|
);
|
|
if (dirty) {
|
|
e.preventDefault();
|
|
e.returnValue = '';
|
|
}
|
|
});
|
|
})();
|
|
|
|
// ===== Restart-pending banner =====
|
|
// Shown after restart-requiring saves; persists across tab switches (and
|
|
// reloads, via sessionStorage) until the display restarts or it's dismissed.
|
|
window.showRestartPending = function(message) {
|
|
try {
|
|
sessionStorage.setItem('ledmatrix-restart-pending', '1');
|
|
// Persisted alongside the flag: a code update and a config save want
|
|
// different wording, and the banner outlives the page that raised it.
|
|
if (message) sessionStorage.setItem('ledmatrix-restart-pending-text', message);
|
|
else sessionStorage.removeItem('ledmatrix-restart-pending-text');
|
|
} catch { /* private browsing */ }
|
|
const banner = document.getElementById('restart-pending-banner');
|
|
const text = document.getElementById('restart-pending-text');
|
|
if (text) {
|
|
// Without the else-branch a config save inherited whatever wording the
|
|
// previous update left in the DOM: showRestartPending() clears the
|
|
// stored text but used to leave the element itself alone. The default
|
|
// is read back from the server-rendered copy rather than duplicated
|
|
// here, so the template stays the one place that owns the string.
|
|
if (text.dataset.defaultText === undefined) {
|
|
text.dataset.defaultText = text.textContent.trim();
|
|
}
|
|
text.textContent = message || text.dataset.defaultText;
|
|
}
|
|
if (banner) banner.style.display = 'block';
|
|
};
|
|
|
|
window.dismissRestartPending = function() {
|
|
try {
|
|
sessionStorage.removeItem('ledmatrix-restart-pending');
|
|
sessionStorage.removeItem('ledmatrix-restart-pending-text');
|
|
} catch { /* no-op */ }
|
|
const banner = document.getElementById('restart-pending-banner');
|
|
if (banner) banner.style.display = 'none';
|
|
};
|
|
|
|
window.restartPendingNow = function() {
|
|
const btn = document.getElementById('restart-pending-btn');
|
|
if (btn) btn.disabled = true;
|
|
fetch('/api/v3/system/action', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ action: 'restart_display_service' })
|
|
})
|
|
.then(r => r.json())
|
|
.then(data => {
|
|
showNotification(data.message || 'Display restarting…', data.status || 'success');
|
|
window.dismissRestartPending();
|
|
})
|
|
.catch(err => {
|
|
showNotification('Error restarting display: ' + err.message, 'error');
|
|
})
|
|
.finally(() => { if (btn) btn.disabled = false; });
|
|
};
|
|
|
|
document.addEventListener('DOMContentLoaded', function() {
|
|
try {
|
|
if (sessionStorage.getItem('ledmatrix-restart-pending') === '1') {
|
|
const banner = document.getElementById('restart-pending-banner');
|
|
const saved = sessionStorage.getItem('ledmatrix-restart-pending-text');
|
|
const text = document.getElementById('restart-pending-text');
|
|
if (text && saved) text.textContent = saved;
|
|
if (banner) banner.style.display = 'block';
|
|
}
|
|
} catch { /* no-op */ }
|
|
});
|
|
|
|
// SSE streams (and window.reconnectSSE) are owned by window.LEDStreams in
|
|
// js/app-shell.js — do not open EventSources for stats/display here.
|
|
|
|
// Auto-resize textareas
|
|
document.addEventListener('DOMContentLoaded', function() {
|
|
const textareas = document.querySelectorAll('textarea');
|
|
textareas.forEach(textarea => {
|
|
textarea.addEventListener('input', function() {
|
|
this.style.height = 'auto';
|
|
this.style.height = this.scrollHeight + 'px';
|
|
});
|
|
});
|
|
});
|
|
|
|
// Keyboard shortcuts
|
|
document.addEventListener('keydown', function(e) {
|
|
// Ctrl/Cmd + R to refresh
|
|
if ((e.ctrlKey || e.metaKey) && e.key === 'r') {
|
|
e.preventDefault();
|
|
location.reload();
|
|
}
|
|
|
|
// Ctrl/Cmd + S to save current form
|
|
if ((e.ctrlKey || e.metaKey) && e.key === 's') {
|
|
e.preventDefault();
|
|
const form = document.querySelector('form');
|
|
if (form) {
|
|
form.dispatchEvent(new Event('submit'));
|
|
}
|
|
}
|
|
});
|
|
|
|
// Error handling for unhandled promise rejections
|
|
window.addEventListener('unhandledrejection', function(event) {
|
|
console.error('Unhandled promise rejection:', event.reason);
|
|
showNotification('An unexpected error occurred', 'error');
|
|
});
|
|
|
|
// ===== Floating live preview =====
|
|
// A mini preview of the display, available on every tab except Overview
|
|
// (which has the full-size one). Open/closed state persists per browser;
|
|
// frames arrive via the existing SSE stream (updateDisplayPreview in
|
|
// app-shell.js feeds #floating-preview-img).
|
|
window.toggleFloatingPreview = function(open) {
|
|
try { localStorage.setItem('ledmatrix-floating-preview', open ? '1' : '0'); } catch { /* no-op */ }
|
|
window.updateFloatingPreviewVisibility();
|
|
};
|
|
|
|
// Preset widths the size button cycles through (px). Desktop users can also
|
|
// drag the panel's native resize handle (CSS resize: both).
|
|
const FLOATING_PREVIEW_SIZES = [192, 256, 384, 512];
|
|
|
|
window.applyFloatingPreviewSize = function() {
|
|
const panel = document.getElementById('floating-preview');
|
|
if (!panel) return;
|
|
let size = 256;
|
|
try { size = parseInt(localStorage.getItem('ledmatrix-floating-preview-size'), 10) || 256; } catch { /* no-op */ }
|
|
panel.style.width = size + 'px';
|
|
// Clear any manual drag-resize height so the image's aspect ratio rules
|
|
panel.style.height = '';
|
|
};
|
|
|
|
window.cycleFloatingPreviewSize = function() {
|
|
let size = 256;
|
|
try { size = parseInt(localStorage.getItem('ledmatrix-floating-preview-size'), 10) || 256; } catch { /* no-op */ }
|
|
const idx = FLOATING_PREVIEW_SIZES.indexOf(size);
|
|
const next = FLOATING_PREVIEW_SIZES[(idx + 1) % FLOATING_PREVIEW_SIZES.length];
|
|
try { localStorage.setItem('ledmatrix-floating-preview-size', String(next)); } catch { /* no-op */ }
|
|
window.applyFloatingPreviewSize();
|
|
};
|
|
|
|
window.updateFloatingPreviewVisibility = function(tab) {
|
|
const panel = document.getElementById('floating-preview');
|
|
const toggle = document.getElementById('floating-preview-toggle');
|
|
if (!panel || !toggle) return;
|
|
let active = tab;
|
|
if (!active) {
|
|
const el = document.querySelector('[x-data="app()"]') || document.querySelector('[x-data]');
|
|
const data = el && el._x_dataStack && el._x_dataStack[0];
|
|
active = data && data.activeTab;
|
|
}
|
|
const onOverview = active === 'overview';
|
|
let open = false;
|
|
try { open = localStorage.getItem('ledmatrix-floating-preview') === '1'; } catch { /* no-op */ }
|
|
const showPanel = !onOverview && open;
|
|
panel.style.display = showPanel ? 'block' : 'none';
|
|
toggle.style.display = (!onOverview && !open) ? 'flex' : 'none';
|
|
if (showPanel) {
|
|
window.applyFloatingPreviewSize();
|
|
// Show the last cached frame immediately — SSE only pushes on
|
|
// display changes, so a freshly opened panel would otherwise stay
|
|
// empty until the next change.
|
|
const img = document.getElementById('floating-preview-img');
|
|
if (img && !img.src && window._lastPreviewFrame) {
|
|
img.src = 'data:image/png;base64,' + window._lastPreviewFrame;
|
|
}
|
|
}
|
|
// The display SSE stream is only open while a preview is on screen
|
|
if (window.LEDStreams) window.LEDStreams.refresh();
|
|
};
|
|
|
|
document.addEventListener('DOMContentLoaded', function() {
|
|
window.updateFloatingPreviewVisibility();
|
|
});
|
|
|
|
// Run a plugin on the real display for 60s via the existing on-demand API
|
|
// and open the floating preview so the effect is visible while configuring.
|
|
window.previewPluginNow = function(pluginId) {
|
|
fetch('/api/v3/display/on-demand/start', {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ plugin_id: pluginId, duration: 60 })
|
|
})
|
|
.then(r => r.json())
|
|
.then(data => {
|
|
showNotification(data.message || ('Previewing ' + pluginId + ' for 60 seconds'),
|
|
data.status || 'success');
|
|
if (data.status === 'success') window.toggleFloatingPreview(true);
|
|
})
|
|
.catch(err => {
|
|
showNotification('Preview failed: ' + err.message, 'error');
|
|
});
|
|
};
|
|
|
|
// ===== Nav accessibility =====
|
|
// aria-current tracks the active tab. Buttons are matched by their Alpine
|
|
// @click expression ("activeTab = '<tab>'"), which works for both the static
|
|
// system tabs and the dynamically injected plugin tabs.
|
|
window.updateNavAriaCurrent = function(tab) {
|
|
document.querySelectorAll('.nav-tab').forEach(function(btn) {
|
|
const expr = btn.getAttribute('@click') || btn.getAttribute('x-on:click') || '';
|
|
const isCurrent = expr.indexOf("activeTab = '" + tab + "'") !== -1;
|
|
if (isCurrent) {
|
|
btn.setAttribute('aria-current', 'page');
|
|
} else {
|
|
btn.removeAttribute('aria-current');
|
|
}
|
|
});
|
|
};
|
|
|
|
// Escape closes the mobile nav drawer and returns focus to the hamburger;
|
|
// opening the drawer moves focus to its first tab.
|
|
(function() {
|
|
function appData() {
|
|
const el = document.querySelector('[x-data="app()"]') || document.querySelector('[x-data]');
|
|
return el && el._x_dataStack && el._x_dataStack[0];
|
|
}
|
|
document.addEventListener('keydown', function(e) {
|
|
if (e.key !== 'Escape') return;
|
|
const data = appData();
|
|
if (data && data.mobileNavOpen) {
|
|
data.mobileNavOpen = false;
|
|
const burger = document.querySelector('[aria-controls="site-nav"]');
|
|
if (burger) burger.focus();
|
|
}
|
|
});
|
|
document.addEventListener('click', function(e) {
|
|
const burger = e.target && e.target.closest
|
|
? e.target.closest('[aria-controls="site-nav"]') : null;
|
|
if (!burger) return;
|
|
// The click handler toggles mobileNavOpen; focus the first tab once
|
|
// the drawer has slid in (matches the CSS transition timing).
|
|
setTimeout(function() {
|
|
const data = appData();
|
|
if (data && data.mobileNavOpen) {
|
|
const first = document.querySelector('#site-nav .nav-tab');
|
|
if (first) first.focus();
|
|
}
|
|
}, 120);
|
|
});
|
|
})();
|
|
|
|
// ===== Mobile nav: header-widget relocation =====
|
|
// Below the md breakpoint the settings-search box and system-stats block are
|
|
// MOVED (same DOM nodes, listeners intact) from the header into the nav
|
|
// drawer's #drawer-widgets slot; at md and up they move back. Single-instance
|
|
// constraint: settings-search.js and the SSE stats updater both look these
|
|
// elements up by id, so they must never be duplicated.
|
|
window.placeHeaderWidgets = function() {
|
|
const drawer = document.getElementById('drawer-widgets');
|
|
const header = document.getElementById('header-widgets');
|
|
const search = document.getElementById('settings-search-wrap');
|
|
const stats = document.getElementById('system-stats');
|
|
if (!drawer || !header) return;
|
|
|
|
const desktop = window.matchMedia('(min-width: 768px)').matches;
|
|
if (desktop) {
|
|
// Restore original header order: search before the theme toggle,
|
|
// stats as the last item.
|
|
const themeToggle = document.getElementById('theme-toggle');
|
|
if (search && search.parentElement !== header) {
|
|
header.insertBefore(search, themeToggle || null);
|
|
}
|
|
if (stats && stats.parentElement !== header) {
|
|
header.appendChild(stats);
|
|
}
|
|
} else {
|
|
if (search && search.parentElement !== drawer) drawer.appendChild(search);
|
|
if (stats && stats.parentElement !== drawer) drawer.appendChild(stats);
|
|
}
|
|
};
|
|
|
|
document.addEventListener('DOMContentLoaded', function() {
|
|
window.placeHeaderWidgets();
|
|
window.matchMedia('(min-width: 768px)').addEventListener('change', window.placeHeaderWidgets);
|
|
});
|