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>
870 lines
46 KiB
JavaScript
870 lines
46 KiB
JavaScript
/**
|
||
* Plugin File Manager Widget
|
||
*
|
||
* Reusable inline file manager for plugins that manage files via the
|
||
* web_ui_actions system. Driven entirely by x-widget-config in the schema —
|
||
* no external HTML file or iframe needed.
|
||
*
|
||
* Any plugin can adopt this widget by:
|
||
* 1. Defining web_ui_actions in manifest.json (list, get, save, upload,
|
||
* delete, create, toggle) with ui_hidden: true
|
||
* 2. Adding x-widget: "plugin-file-manager" to a field in config_schema.json
|
||
* with x-widget-config mapping the action IDs
|
||
*
|
||
* Schema example:
|
||
* {
|
||
* "file_manager": {
|
||
* "type": "null",
|
||
* "title": "Data Files",
|
||
* "x-widget": "plugin-file-manager",
|
||
* "x-widget-config": {
|
||
* "actions": {
|
||
* "list": "list-files",
|
||
* "get": "get-file",
|
||
* "save": "save-file",
|
||
* "upload": "upload-file",
|
||
* "delete": "delete-file",
|
||
* "create": "create-file",
|
||
* "toggle": "toggle-category"
|
||
* },
|
||
* "upload_hint": "JSON files with day numbers 1–365 as keys",
|
||
* "directory_label": "of_the_day/",
|
||
* "create_fields": [
|
||
* { "key": "category_name", "label": "Category Name",
|
||
* "placeholder": "e.g., my_words", "pattern": "^[a-z0-9_]+$",
|
||
* "hint": "Lowercase letters, numbers, underscores" },
|
||
* { "key": "display_name", "label": "Display Name",
|
||
* "placeholder": "e.g., My Words", "hint": "Optional — auto-generated if blank" }
|
||
* ]
|
||
* }
|
||
* }
|
||
* }
|
||
*
|
||
* @module PluginFileManagerWidget
|
||
*/
|
||
|
||
(function () {
|
||
'use strict';
|
||
|
||
if (typeof window.LEDMatrixWidgets === 'undefined') {
|
||
console.error('[PluginFileManager] LEDMatrixWidgets registry not found.');
|
||
return;
|
||
}
|
||
|
||
// ─── Inject widget-scoped styles once ────────────────────────────────────
|
||
|
||
if (!document.getElementById('pfm-styles')) {
|
||
const style = document.createElement('style');
|
||
style.id = 'pfm-styles';
|
||
// Colors come from the app theme tokens (app.css :root / [data-theme="dark"]),
|
||
// with the original light values as fallbacks for pages without app.css.
|
||
// The few shades the tokens don't cover are widget-local variables with
|
||
// a dark-theme override.
|
||
style.textContent = `
|
||
.pfm-root, .pfm-overlay {
|
||
--pfm-border-strong:#d1d5db; --pfm-subtle:#f3f4f6; --pfm-subtle-hover:#e5e7eb;
|
||
--pfm-danger-border:#fecaca; --pfm-danger-text:#991b1b; --pfm-today:#fef9c3;
|
||
--pfm-text-muted:#6b7280;
|
||
}
|
||
[data-theme="dark"] .pfm-root, [data-theme="dark"] .pfm-overlay {
|
||
--pfm-border-strong:#4b5563; --pfm-subtle:#374151; --pfm-subtle-hover:#4b5563;
|
||
--pfm-danger-border:#991b1b; --pfm-danger-text:#fecaca; --pfm-today:#422006;
|
||
--pfm-text-muted:#9ca3af;
|
||
}
|
||
.pfm-root { font-family: inherit; color:var(--color-text-primary,#111827); }
|
||
.pfm-header { display:flex; align-items:center; justify-content:space-between;
|
||
margin-bottom:.75rem; }
|
||
.pfm-title { font-size:1rem; font-weight:600; color:var(--color-text-primary,#111827); }
|
||
.pfm-dir { font-size:.75rem; color:var(--pfm-text-muted); margin-top:.125rem; }
|
||
.pfm-upload { border:2px dashed var(--pfm-border-strong); border-radius:.5rem; padding:1.25rem;
|
||
text-align:center; cursor:pointer; transition:border-color .15s,background .15s; }
|
||
.pfm-upload:hover,.pfm-upload.dragover { border-color:var(--color-primary,#3b82f6); background:var(--color-info-bg,#eff6ff); }
|
||
.pfm-upload p { font-size:.875rem; color:var(--color-text-tertiary,#4b5563); margin:.25rem 0 0; }
|
||
.pfm-upload small { font-size:.75rem; color:var(--pfm-text-muted); }
|
||
.pfm-upload-icon { font-size:1.5rem; color:var(--pfm-text-muted); }
|
||
.pfm-grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(260px,1fr));
|
||
gap:.75rem; margin-top:.75rem; }
|
||
.pfm-card { border:1px solid var(--color-border,#e5e7eb); border-radius:.5rem; padding:.875rem;
|
||
background:var(--color-surface,#fff); transition:box-shadow .15s; }
|
||
.pfm-card:hover { box-shadow:var(--shadow-md,0 1px 4px rgba(0,0,0,.1)); }
|
||
.pfm-card.disabled { opacity:.55; }
|
||
.pfm-card-top { display:flex; align-items:center; justify-content:space-between;
|
||
margin-bottom:.5rem; }
|
||
.pfm-card-icon { width:2rem; height:2rem; background:var(--pfm-subtle); border-radius:.375rem;
|
||
display:flex; align-items:center; justify-content:center;
|
||
color:var(--pfm-text-muted); font-size:1rem; }
|
||
.pfm-card-name { font-weight:600; color:var(--color-text-primary,#111827); font-size:.875rem; margin:.375rem 0 .125rem; }
|
||
.pfm-card-meta { font-size:.75rem; color:var(--pfm-text-muted); line-height:1.5; }
|
||
.pfm-card-actions { display:flex; gap:.375rem; margin-top:.625rem; }
|
||
.pfm-btn { display:inline-flex; align-items:center; gap:.25rem; padding:.375rem .75rem;
|
||
border-radius:.375rem; font-size:.8125rem; font-weight:500;
|
||
border:none; cursor:pointer; transition:background .15s; }
|
||
.pfm-btn:focus-visible { outline:2px solid var(--color-primary,#2563eb); outline-offset:2px; }
|
||
.pfm-btn:disabled { opacity:.5; cursor:not-allowed; }
|
||
.pfm-btn-primary { background:var(--color-primary,#2563eb); color:#fff; flex:1; justify-content:center; }
|
||
.pfm-btn-primary:hover { background:var(--color-primary-hover,#1d4ed8); }
|
||
/* Solid fills with white text: fixed shades read well on both themes. */
|
||
.pfm-btn-danger { background:#dc2626; color:#fff; }
|
||
.pfm-btn-danger:hover { background:#b91c1c; }
|
||
.pfm-btn-secondary { background:var(--pfm-subtle); color:var(--color-text-secondary,#374151); border:1px solid var(--pfm-border-strong); }
|
||
.pfm-btn-secondary:hover { background:var(--pfm-subtle-hover); }
|
||
.pfm-btn-sm { padding:.25rem .5rem; font-size:.75rem; }
|
||
.pfm-btn-create { background:#059669; color:#fff; }
|
||
.pfm-btn-create:hover { background:#047857; }
|
||
.pfm-toggle-wrap { display:flex; align-items:center; gap:.375rem; }
|
||
.pfm-toggle-label { font-size:.75rem; color:var(--pfm-text-muted); }
|
||
.pfm-toggle-cb { position:relative; display:inline-block; width:2rem; height:1.125rem; }
|
||
.pfm-toggle-cb input { opacity:0; width:0; height:0; }
|
||
.pfm-toggle-slider { position:absolute; inset:0; background:var(--pfm-border-strong); border-radius:9999px;
|
||
cursor:pointer; transition:background .2s; }
|
||
.pfm-toggle-slider:before { content:''; position:absolute; height:.75rem; width:.75rem;
|
||
left:.1875rem; bottom:.1875rem; background:#fff;
|
||
border-radius:50%; transition:transform .2s; }
|
||
.pfm-toggle-cb input:checked + .pfm-toggle-slider { background:#10b981; }
|
||
.pfm-toggle-cb input:checked + .pfm-toggle-slider:before { transform:translateX(.875rem); }
|
||
.pfm-toggle-cb input:focus-visible + .pfm-toggle-slider { outline:2px solid var(--color-primary,#2563eb); outline-offset:2px; }
|
||
.pfm-empty { text-align:center; padding:2rem; color:var(--pfm-text-muted); }
|
||
.pfm-empty i { font-size:2rem; margin-bottom:.5rem; display:block; }
|
||
.pfm-error-text { color:var(--color-error,#dc2626); }
|
||
|
||
/* Modal */
|
||
.pfm-overlay { position:fixed; inset:0; background:rgba(0,0,0,.5);
|
||
display:flex; align-items:flex-start; justify-content:center;
|
||
z-index:9999; padding:2rem 1rem; overflow-y:auto; }
|
||
.pfm-modal { background:var(--color-surface,#fff); color:var(--color-text-primary,#111827);
|
||
border-radius:.75rem; width:100%; max-width:56rem;
|
||
box-shadow:0 20px 50px rgba(0,0,0,.3); margin:auto; }
|
||
.pfm-modal:focus { outline:none; }
|
||
.pfm-modal-header { display:flex; align-items:center; justify-content:space-between;
|
||
padding:1rem 1.25rem; border-bottom:1px solid var(--color-border,#e5e7eb); }
|
||
.pfm-modal-title { font-size:1rem; font-weight:600; color:var(--color-text-primary,#111827); }
|
||
.pfm-modal-body { padding:1.25rem; overflow-y:auto; max-height:70vh; }
|
||
.pfm-modal-footer { display:flex; justify-content:flex-end; gap:.5rem;
|
||
padding:.875rem 1.25rem; border-top:1px solid var(--color-border,#e5e7eb);
|
||
background:var(--color-background,#f9fafb); border-radius:0 0 .75rem .75rem; }
|
||
|
||
/* Entry table */
|
||
.pfm-table-wrap { overflow-x:auto; }
|
||
.pfm-table { width:100%; border-collapse:collapse; font-size:.8125rem; }
|
||
.pfm-table th { background:var(--color-background,#f9fafb); text-align:left; padding:.5rem .625rem;
|
||
font-weight:600; color:var(--color-text-secondary,#374151); border-bottom:1px solid var(--color-border,#e5e7eb);
|
||
white-space:nowrap; position:sticky; top:0; }
|
||
.pfm-table td { padding:.375rem .625rem; border-bottom:1px solid var(--color-border-light,#f3f4f6);
|
||
vertical-align:top; }
|
||
.pfm-table tr.today-row td { background:var(--pfm-today); }
|
||
.pfm-table td input, .pfm-table td textarea {
|
||
width:100%; border:1px solid var(--pfm-border-strong); border-radius:.25rem;
|
||
padding:.25rem .375rem; font-size:.8125rem; font-family:inherit;
|
||
resize:vertical; background:var(--color-surface,#fff); color:var(--color-text-primary,#111827); }
|
||
.pfm-table td input:focus, .pfm-table td textarea:focus {
|
||
outline:none; border-color:var(--color-primary,#3b82f6); box-shadow:0 0 0 2px var(--color-primary,#3b82f6); }
|
||
.pfm-day-col { width:3rem; text-align:center; font-weight:600;
|
||
color:var(--pfm-text-muted); white-space:nowrap; }
|
||
.pfm-table-info { font-size:.75rem; color:var(--pfm-text-muted); margin-bottom:.375rem; }
|
||
.pfm-pagination { display:flex; align-items:center; justify-content:space-between;
|
||
margin-top:.75rem; font-size:.8125rem; color:var(--pfm-text-muted); }
|
||
.pfm-page-jump { display:flex; align-items:center; gap:.375rem; font-size:.8125rem; }
|
||
.pfm-page-jump input { width:3.5rem; padding:.25rem .375rem; border:1px solid var(--pfm-border-strong);
|
||
border-radius:.25rem; text-align:center;
|
||
background:var(--color-surface,#fff); color:var(--color-text-primary,#111827); }
|
||
.pfm-json-ta { width:100%; font-family:monospace; font-size:.75rem; border:1px solid var(--pfm-border-strong);
|
||
border-radius:.375rem; padding:.5rem;
|
||
background:var(--color-surface,#fff); color:var(--color-text-primary,#111827); }
|
||
.pfm-json-err { color:var(--color-error,#dc2626); font-size:.75rem; margin-top:.25rem; }
|
||
|
||
/* Form in create modal */
|
||
.pfm-field { margin-bottom:.875rem; }
|
||
.pfm-field label { display:block; font-size:.875rem; font-weight:500;
|
||
color:var(--color-text-secondary,#374151); margin-bottom:.25rem; }
|
||
.pfm-field input { width:100%; padding:.4rem .625rem; border:1px solid var(--pfm-border-strong);
|
||
border-radius:.375rem; font-size:.875rem;
|
||
background:var(--color-surface,#fff); color:var(--color-text-primary,#111827); }
|
||
.pfm-field input:focus { outline:none; border-color:var(--color-primary,#3b82f6); box-shadow:0 0 0 2px var(--color-primary,#3b82f6); }
|
||
.pfm-field-hint { font-size:.75rem; color:var(--pfm-text-muted); margin-top:.2rem; }
|
||
.pfm-field-error { font-size:.75rem; color:var(--color-error,#dc2626); margin-top:.2rem; }
|
||
|
||
/* Delete danger box */
|
||
.pfm-danger-box { background:var(--color-error-bg,#fef2f2); border:1px solid var(--pfm-danger-border);
|
||
border-radius:.5rem; padding:.875rem; font-size:.875rem;
|
||
color:var(--pfm-danger-text); }
|
||
|
||
@media (prefers-reduced-motion: reduce) {
|
||
.pfm-upload, .pfm-card, .pfm-btn, .pfm-toggle-slider, .pfm-toggle-slider:before { transition:none; }
|
||
}
|
||
`;
|
||
document.head.appendChild(style);
|
||
}
|
||
|
||
// ─── Safe HTML helper ─────────────────────────────────────────────────────
|
||
|
||
/**
|
||
* Parse html in a sandboxed DOMParser document (scripts never execute) and
|
||
* replace target's children with the result. All dynamic values in html
|
||
* must be escaped by the caller before passing here.
|
||
*/
|
||
function safeSetHTML(target, html) {
|
||
target.textContent = '';
|
||
// createContextualFragment parses html relative to the document context
|
||
// without executing scripts — a widely recognised safe insertion method.
|
||
const frag = document.createRange().createContextualFragment(html);
|
||
target.appendChild(frag);
|
||
}
|
||
|
||
// ─── Per-instance state ───────────────────────────────────────────────────
|
||
|
||
const _state = new Map(); // fieldId → { pluginId, actions, createFields, files, page, entriesPerPage, modal }
|
||
|
||
function getState(fieldId) {
|
||
if (!_state.has(fieldId)) _state.set(fieldId, {
|
||
pluginId: '', actions: {}, createFields: [], uploadHint: '',
|
||
directoryLabel: '', files: [], page: 1, entriesPerPage: 20,
|
||
currentModal: null
|
||
});
|
||
return _state.get(fieldId);
|
||
}
|
||
|
||
// ─── API helper ───────────────────────────────────────────────────────────
|
||
|
||
async function callAction(pluginId, actionId, params = {}) {
|
||
const resp = await fetch('/api/v3/plugins/action', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ plugin_id: pluginId, action_id: actionId, params })
|
||
});
|
||
return resp.json();
|
||
}
|
||
|
||
function notify(msg, type) {
|
||
if (window.showNotification) window.showNotification(msg, type);
|
||
else console.log(`[PFM][${type}] ${msg}`);
|
||
}
|
||
|
||
// Quotes too: the result lands in quoted attribute values (id=, value=,
|
||
// data-col=), and the textContent/innerHTML round-trip only escapes
|
||
// &, < and >.
|
||
function escHtml(s) {
|
||
const d = document.createElement('div');
|
||
d.textContent = String(s ?? '');
|
||
return d.innerHTML
|
||
.replace(/"/g, '"')
|
||
.replace(/'/g, ''');
|
||
}
|
||
|
||
function formatSize(bytes) {
|
||
if (bytes >= 1048576) return (bytes / 1048576).toFixed(1) + ' MB';
|
||
return (bytes / 1024).toFixed(2) + ' KB';
|
||
}
|
||
|
||
function formatDate(iso) {
|
||
try { return new Date(iso).toLocaleString(undefined, { dateStyle: 'short', timeStyle: 'short' }); }
|
||
catch { return iso; }
|
||
}
|
||
|
||
// ─── Core: load files ─────────────────────────────────────────────────────
|
||
|
||
async function loadFiles(fieldId) {
|
||
const st = getState(fieldId);
|
||
const root = document.getElementById(`${fieldId}_pfm`);
|
||
if (!root) return;
|
||
const grid = root.querySelector('.pfm-grid');
|
||
if (grid) safeSetHTML(grid, '<div class="pfm-empty"><i class="fas fa-spinner fa-spin"></i>Loading…</div>');
|
||
|
||
const data = await callAction(st.pluginId, st.actions.list).catch(() => null);
|
||
if (!data || data.status !== 'success') {
|
||
if (grid) safeSetHTML(grid, '<div class="pfm-empty"><i class="fas fa-exclamation-circle"></i>Failed to load files.</div>');
|
||
return;
|
||
}
|
||
st.files = data.files || [];
|
||
renderCards(fieldId);
|
||
}
|
||
|
||
// ─── Card grid ────────────────────────────────────────────────────────────
|
||
|
||
function renderCards(fieldId) {
|
||
const st = getState(fieldId);
|
||
const root = document.getElementById(`${fieldId}_pfm`);
|
||
if (!root) return;
|
||
const grid = root.querySelector('.pfm-grid');
|
||
if (!grid) return;
|
||
|
||
if (!st.files.length) {
|
||
safeSetHTML(grid, '<div class="pfm-empty"><i class="fas fa-folder-open"></i>No files yet. Create or upload one.</div>');
|
||
return;
|
||
}
|
||
|
||
// Remove any existing delegated listener before re-render
|
||
if (st._gridClickHandler) grid.removeEventListener('click', st._gridClickHandler);
|
||
if (st._gridChangeHandler) grid.removeEventListener('change', st._gridChangeHandler);
|
||
|
||
// Event delegation: handles edit/delete/toggle via data attributes so
|
||
// filenames and category names are never interpolated into JS string literals.
|
||
st._gridClickHandler = function(e) {
|
||
const btn = e.target.closest('[data-pfm-action]');
|
||
if (!btn) return;
|
||
const action = btn.dataset.pfmAction;
|
||
const fId = btn.dataset.pfmField;
|
||
if (action === 'edit') window._pfmOpenEdit(fId, btn.dataset.pfmFile);
|
||
if (action === 'delete') window._pfmOpenDelete(fId, btn.dataset.pfmFile);
|
||
};
|
||
st._gridChangeHandler = function(e) {
|
||
const inp = e.target.closest('[data-pfm-action="toggle"]');
|
||
if (!inp) return;
|
||
window._pfmToggle(inp.dataset.pfmField, inp.dataset.pfmCategory, inp.checked);
|
||
};
|
||
grid.addEventListener('click', st._gridClickHandler);
|
||
grid.addEventListener('change', st._gridChangeHandler);
|
||
|
||
// Build cards with DOM methods so no user-derived data flows through innerHTML.
|
||
grid.textContent = '';
|
||
const frag = document.createDocumentFragment();
|
||
st.files.forEach(function(f) {
|
||
const card = document.createElement('div');
|
||
card.className = 'pfm-card' + (f.enabled === false ? ' disabled' : '');
|
||
card.dataset.filename = f.filename;
|
||
card.dataset.category = f.category_name;
|
||
|
||
// Top row: label + optional toggle
|
||
const top = document.createElement('div');
|
||
top.className = 'pfm-card-top';
|
||
const lbl = document.createElement('span');
|
||
lbl.className = 'pfm-toggle-label';
|
||
lbl.textContent = f.enabled !== false ? 'Enabled' : 'Disabled';
|
||
top.appendChild(lbl);
|
||
if (st.actions.toggle) {
|
||
const tglLabel = document.createElement('label');
|
||
tglLabel.className = 'pfm-toggle-cb';
|
||
tglLabel.title = f.enabled !== false ? 'Click to disable' : 'Click to enable';
|
||
const tglInput = document.createElement('input');
|
||
tglInput.type = 'checkbox';
|
||
tglInput.checked = f.enabled !== false;
|
||
tglInput.dataset.pfmAction = 'toggle';
|
||
tglInput.dataset.pfmField = fieldId;
|
||
tglInput.dataset.pfmCategory = f.category_name;
|
||
const tglSlider = document.createElement('span');
|
||
tglSlider.className = 'pfm-toggle-slider';
|
||
tglLabel.appendChild(tglInput);
|
||
tglLabel.appendChild(tglSlider);
|
||
top.appendChild(tglLabel);
|
||
}
|
||
card.appendChild(top);
|
||
|
||
// Icon (static markup)
|
||
const icon = document.createElement('div');
|
||
icon.className = 'pfm-card-icon';
|
||
icon.innerHTML = '<i class="fas fa-file-code"></i>';
|
||
card.appendChild(icon);
|
||
|
||
// Name & meta — textContent avoids any HTML injection
|
||
const name = document.createElement('div');
|
||
name.className = 'pfm-card-name';
|
||
name.textContent = f.display_name || f.filename;
|
||
card.appendChild(name);
|
||
|
||
const meta = document.createElement('div');
|
||
meta.className = 'pfm-card-meta';
|
||
meta.appendChild(document.createTextNode(f.filename));
|
||
meta.appendChild(document.createElement('br'));
|
||
if (f.entry_count != null) {
|
||
meta.appendChild(document.createTextNode(f.entry_count + ' entries · ' + formatSize(f.size)));
|
||
}
|
||
meta.appendChild(document.createElement('br'));
|
||
meta.appendChild(document.createTextNode(formatDate(f.modified)));
|
||
card.appendChild(meta);
|
||
|
||
// Action buttons
|
||
const actions = document.createElement('div');
|
||
actions.className = 'pfm-card-actions';
|
||
if (st.actions.get && st.actions.save) {
|
||
const editBtn = document.createElement('button');
|
||
editBtn.className = 'pfm-btn pfm-btn-primary';
|
||
editBtn.dataset.pfmAction = 'edit';
|
||
editBtn.dataset.pfmField = fieldId;
|
||
editBtn.dataset.pfmFile = f.filename;
|
||
editBtn.innerHTML = '<i class="fas fa-edit"></i> Edit'; // static
|
||
actions.appendChild(editBtn);
|
||
}
|
||
if (st.actions.delete) {
|
||
const delBtn = document.createElement('button');
|
||
delBtn.className = 'pfm-btn pfm-btn-danger pfm-btn-sm';
|
||
delBtn.dataset.pfmAction = 'delete';
|
||
delBtn.dataset.pfmField = fieldId;
|
||
delBtn.dataset.pfmFile = f.filename;
|
||
delBtn.setAttribute('aria-label', 'Delete ' + f.filename);
|
||
delBtn.innerHTML = '<i class="fas fa-trash" aria-hidden="true"></i>'; // static
|
||
actions.appendChild(delBtn);
|
||
}
|
||
card.appendChild(actions);
|
||
frag.appendChild(card);
|
||
});
|
||
grid.appendChild(frag);
|
||
}
|
||
|
||
// ─── Edit modal ───────────────────────────────────────────────────────────
|
||
|
||
window._pfmOpenEdit = async function (fieldId, filename) {
|
||
const st = getState(fieldId);
|
||
const overlay = createOverlay(fieldId);
|
||
// Build modal using DOM methods so filename never enters a JS string literal.
|
||
const modal = document.createElement('div');
|
||
modal.className = 'pfm-modal';
|
||
safeSetHTML(modal, `
|
||
<div class="pfm-modal-header">
|
||
<span class="pfm-modal-title" id="${escHtml(fieldId)}_modal_title"><i class="fas fa-edit mr-2" aria-hidden="true"></i>${escHtml(filename)}</span>
|
||
<button type="button" class="pfm-btn pfm-btn-secondary pfm-btn-sm" id="${escHtml(fieldId)}_modal_close" aria-label="Close">
|
||
<i class="fas fa-times" aria-hidden="true"></i>
|
||
</button>
|
||
</div>
|
||
<div class="pfm-modal-body" id="${escHtml(fieldId)}_edit_body">
|
||
<div class="pfm-empty"><i class="fas fa-spinner fa-spin" aria-hidden="true"></i>Loading…</div>
|
||
</div>
|
||
<div class="pfm-modal-footer">
|
||
<button type="button" class="pfm-btn pfm-btn-secondary" id="${escHtml(fieldId)}_modal_cancel">Cancel</button>
|
||
<button type="button" class="pfm-btn pfm-btn-primary" id="${escHtml(fieldId)}_save_btn">
|
||
<i class="fas fa-save mr-1" aria-hidden="true"></i>Save
|
||
</button>
|
||
</div>`);
|
||
overlay.appendChild(modal);
|
||
// Bind events after DOM insertion — filename captured in closure, not in HTML.
|
||
modal.querySelector(`#${CSS.escape(fieldId)}_modal_close`).addEventListener('click', () => window._pfmCloseModal(fieldId));
|
||
modal.querySelector(`#${CSS.escape(fieldId)}_modal_cancel`).addEventListener('click', () => window._pfmCloseModal(fieldId));
|
||
modal.querySelector(`#${CSS.escape(fieldId)}_save_btn`).addEventListener('click', () => window._pfmSave(fieldId, filename));
|
||
trapModal(fieldId, modal, `${fieldId}_modal_title`);
|
||
|
||
const data = await callAction(st.pluginId, st.actions.get, { filename }).catch(() => null);
|
||
const body = document.getElementById(`${fieldId}_edit_body`);
|
||
if (!data || data.status !== 'success' || !body) {
|
||
if (body) safeSetHTML(body, `<div class="pfm-empty pfm-error-text">Couldn't load ${escHtml(filename)}. Close this window and try again.</div>`);
|
||
return;
|
||
}
|
||
|
||
const content = data.content || data.data || {};
|
||
st._editFilename = filename;
|
||
|
||
if (isTabular(content)) {
|
||
// Table path: track cell edits live in _editData
|
||
st._editData = content;
|
||
renderEntryTable(fieldId, body, content);
|
||
} else {
|
||
// Textarea path: _editData stays null; save() reads from the <textarea>
|
||
st._editData = null;
|
||
safeSetHTML(body, `
|
||
<textarea id="${escHtml(fieldId)}_json_ta" rows="20" class="pfm-json-ta"
|
||
aria-label="File contents (JSON)" aria-describedby="${escHtml(fieldId)}_json_err"
|
||
>${escHtml(JSON.stringify(content, null, 2))}</textarea>
|
||
<div id="${escHtml(fieldId)}_json_err" class="pfm-json-err" role="alert"></div>`);
|
||
}
|
||
};
|
||
|
||
function isTabular(data) {
|
||
if (typeof data !== 'object' || Array.isArray(data)) return false;
|
||
const keys = Object.keys(data);
|
||
if (!keys.length) return false;
|
||
const first = data[keys[0]];
|
||
if (typeof first !== 'object' || Array.isArray(first)) return false;
|
||
const entryKeys = Object.keys(first);
|
||
return entryKeys.length > 0 && entryKeys.length <= 8;
|
||
}
|
||
|
||
function renderEntryTable(fieldId, container, content) {
|
||
const st = getState(fieldId);
|
||
const entries = Object.entries(content).sort((a, b) => parseInt(a[0]) - parseInt(b[0]));
|
||
if (!entries.length) { container.textContent = 'No entries.'; return; }
|
||
|
||
const cols = Object.keys(entries[0][1]);
|
||
|
||
// Delegated listener: day/col reach _pfmCellEdit only through data-*
|
||
// attributes, never through a JS string spliced into an inline
|
||
// handler -- the browser HTML-decodes attribute values before
|
||
// running them as script, which undoes escHtml's quote escaping and
|
||
// reopens the exact injection it exists to close. `container` is a
|
||
// fresh element per modal open (see _pfmOpenEdit), so this attaches
|
||
// exactly once per table, even though buildPage() re-renders below.
|
||
container.addEventListener('input', (e) => {
|
||
const cell = e.target.closest('input[data-day], textarea[data-day]');
|
||
if (!cell) return;
|
||
window._pfmCellEdit(fieldId, cell.dataset.day, cell.dataset.col, cell.value);
|
||
});
|
||
|
||
const MS_PER_DAY = 86400 * 1000; // eslint-disable-line no-magic-numbers -- 86400s/day is not magic
|
||
const todayDoy = Math.ceil((new Date() - new Date(new Date().getFullYear(), 0, 0)) / MS_PER_DAY);
|
||
const total = entries.length;
|
||
const perPage = st.entriesPerPage;
|
||
|
||
function buildPage(page) {
|
||
const start = (page - 1) * perPage; // eslint-disable-line no-magic-numbers
|
||
const pageEntries = entries.slice(start, start + perPage);
|
||
const totalPages = Math.ceil(total / perPage);
|
||
|
||
safeSetHTML(container, `
|
||
<div class="pfm-table-info">
|
||
${total} entries total
|
||
<button class="pfm-btn pfm-btn-secondary pfm-btn-sm" style="margin-left:.5rem"
|
||
onclick="(function(){const targetPage=Math.ceil(${todayDoy}/${perPage});window._pfmTablePage('${fieldId}',targetPage);setTimeout(function(){const row=document.querySelector('tr[data-day=\\'${todayDoy}\\']');if(row)row.scrollIntoView({block:'center'});},60);})()">
|
||
<i class="fas fa-calendar-day"></i> Jump to today (day ${todayDoy})
|
||
</button>
|
||
</div>
|
||
<div id="${fieldId}_tbl_wrap" class="pfm-table-wrap" style="max-height:52vh;overflow-y:auto;">
|
||
<table class="pfm-table">
|
||
<thead>
|
||
<tr>
|
||
<th class="pfm-day-col">Day</th>
|
||
${cols.map(c => `<th>${escHtml(c.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase()))}</th>`).join('')}
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
${pageEntries.map(([day, val]) => `
|
||
<tr data-day="${escHtml(day)}" class="${parseInt(day) === todayDoy ? 'today-row' : ''}">
|
||
<td class="pfm-day-col" style="user-select:none;">${escHtml(day)}</td>
|
||
${cols.map(col => {
|
||
const v = val[col] ?? '';
|
||
const isLong = String(v).length > 60 || col === 'description' || col === 'definition' || col === 'content';
|
||
return isLong
|
||
? `<td><textarea data-day="${escHtml(day)}" data-col="${escHtml(col)}" rows="2"
|
||
>${escHtml(String(v))}</textarea></td>`
|
||
: `<td><input type="text" data-day="${escHtml(day)}" data-col="${escHtml(col)}"
|
||
value="${escHtml(String(v))}"></td>`;
|
||
}).join('')}
|
||
</tr>`).join('')}
|
||
</tbody>
|
||
</table>
|
||
</div>
|
||
<div class="pfm-pagination">
|
||
<span>Page ${page} of ${totalPages}</span>
|
||
<div class="pfm-page-jump">
|
||
<button class="pfm-btn pfm-btn-secondary pfm-btn-sm"
|
||
${page <= 1 ? 'disabled' : ''}
|
||
onclick="window._pfmTablePage('${fieldId}',${page - 1})">‹ Prev</button>
|
||
<span>Go to</span>
|
||
<input type="number" min="1" max="${totalPages}" value="${page}"
|
||
onchange="window._pfmTablePage('${fieldId}',+this.value)">
|
||
<button class="pfm-btn pfm-btn-secondary pfm-btn-sm"
|
||
${page >= totalPages ? 'disabled' : ''}
|
||
onclick="window._pfmTablePage('${fieldId}',${page + 1})">Next ›</button>
|
||
</div>
|
||
</div>`);
|
||
st._tablePage = page;
|
||
st._tableEntries = entries;
|
||
st._tableCols = cols;
|
||
}
|
||
|
||
// Store buildPage in per-instance state so multiple instances don't
|
||
// clobber each other's pagination via a shared global.
|
||
st._buildPage = buildPage;
|
||
buildPage(st._tablePage || 1);
|
||
}
|
||
|
||
// Global dispatcher — resolves the per-instance buildPage from state so
|
||
// multiple plugin-file-manager instances don't clobber each other.
|
||
window._pfmTablePage = function (fId, p) {
|
||
const s = getState(fId);
|
||
if (s._buildPage) {
|
||
const total = s._tableEntries ? s._tableEntries.length : 0;
|
||
const totalP = Math.ceil(total / s.entriesPerPage) || 1;
|
||
s._buildPage(Math.max(1, Math.min(p, totalP)));
|
||
}
|
||
};
|
||
|
||
window._pfmCellEdit = function (fieldId, day, col, value) {
|
||
const st = getState(fieldId);
|
||
if (st._editData && st._editData[day]) st._editData[day][col] = value;
|
||
};
|
||
|
||
window._pfmSave = async function (fieldId, filename) {
|
||
const st = getState(fieldId);
|
||
const saveBtn = document.getElementById(`${fieldId}_save_btn`);
|
||
let content;
|
||
|
||
// Try getting from inline table data first, then textarea fallback
|
||
if (st._editData) {
|
||
content = st._editData;
|
||
} else {
|
||
const ta = document.getElementById(`${fieldId}_json_ta`);
|
||
if (!ta) return;
|
||
try { content = JSON.parse(ta.value); }
|
||
catch (e) {
|
||
const errEl = document.getElementById(`${fieldId}_json_err`);
|
||
if (errEl) errEl.textContent = 'Invalid JSON: ' + e.message;
|
||
return;
|
||
}
|
||
}
|
||
|
||
if (saveBtn) { saveBtn.disabled = true; (function(b){b.textContent='';const i=document.createElement('i');i.className='fas fa-spinner fa-spin mr-1';b.appendChild(i);b.appendChild(document.createTextNode('Saving…'));})(saveBtn); }
|
||
|
||
const result = await callAction(st.pluginId, st.actions.save, {
|
||
filename, content: JSON.stringify(content)
|
||
}).catch(() => ({ status: 'error', message: 'Network error' }));
|
||
|
||
if (saveBtn) { saveBtn.disabled = false; (function(b){b.textContent='';const i=document.createElement('i');i.className='fas fa-save mr-1';b.appendChild(i);b.appendChild(document.createTextNode('Save'));})(saveBtn); }
|
||
|
||
if (result.status === 'success') {
|
||
notify('File saved successfully', 'success');
|
||
window._pfmCloseModal(fieldId);
|
||
await loadFiles(fieldId);
|
||
} else {
|
||
notify('Save failed: ' + (result.message || 'Unknown error'), 'error');
|
||
}
|
||
};
|
||
|
||
// ─── Delete modal ─────────────────────────────────────────────────────────
|
||
|
||
window._pfmOpenDelete = function (fieldId, filename) {
|
||
const overlay = createOverlay(fieldId);
|
||
const modal = document.createElement('div');
|
||
modal.className = 'pfm-modal';
|
||
modal.style.maxWidth = '28rem';
|
||
safeSetHTML(modal, `
|
||
<div class="pfm-modal-header">
|
||
<span class="pfm-modal-title" id="${escHtml(fieldId)}_del_title"><i class="fas fa-trash mr-2" aria-hidden="true"></i>Delete File</span>
|
||
<button type="button" class="pfm-btn pfm-btn-secondary pfm-btn-sm" id="${escHtml(fieldId)}_del_close" aria-label="Close">
|
||
<i class="fas fa-times" aria-hidden="true"></i>
|
||
</button>
|
||
</div>
|
||
<div class="pfm-modal-body">
|
||
<div class="pfm-danger-box">
|
||
<strong>${escHtml(filename)}</strong> will be permanently deleted and removed
|
||
from the plugin configuration. This cannot be undone.
|
||
</div>
|
||
</div>
|
||
<div class="pfm-modal-footer">
|
||
<button type="button" class="pfm-btn pfm-btn-secondary" id="${escHtml(fieldId)}_del_cancel">Cancel</button>
|
||
<button type="button" class="pfm-btn pfm-btn-danger" id="${escHtml(fieldId)}_del_confirm">
|
||
<i class="fas fa-trash mr-1" aria-hidden="true"></i>Delete
|
||
</button>
|
||
</div>`);
|
||
overlay.appendChild(modal);
|
||
const cancelBtn = modal.querySelector(`#${CSS.escape(fieldId)}_del_cancel`);
|
||
modal.querySelector(`#${CSS.escape(fieldId)}_del_close`).addEventListener('click', () => window._pfmCloseModal(fieldId));
|
||
cancelBtn.addEventListener('click', () => window._pfmCloseModal(fieldId));
|
||
modal.querySelector(`#${CSS.escape(fieldId)}_del_confirm`).addEventListener('click', () => window._pfmConfirmDelete(fieldId, filename));
|
||
// Destructive dialog: start on Cancel.
|
||
trapModal(fieldId, modal, `${fieldId}_del_title`, cancelBtn);
|
||
};
|
||
|
||
window._pfmConfirmDelete = async function (fieldId, filename) {
|
||
const st = getState(fieldId);
|
||
const result = await callAction(st.pluginId, st.actions.delete, { filename })
|
||
.catch(() => ({ status: 'error', message: 'Network error' }));
|
||
if (result.status === 'success') {
|
||
notify('File deleted', 'success');
|
||
window._pfmCloseModal(fieldId);
|
||
await loadFiles(fieldId);
|
||
} else {
|
||
notify("Couldn't delete the file: " + (result.message || 'unknown error') + '. Try again.', 'error');
|
||
}
|
||
};
|
||
|
||
// ─── Create modal ─────────────────────────────────────────────────────────
|
||
|
||
window._pfmOpenCreate = function (fieldId) {
|
||
const st = getState(fieldId);
|
||
const fields = st.createFields;
|
||
const overlay = createOverlay(fieldId);
|
||
const modal = document.createElement('div');
|
||
modal.className = 'pfm-modal';
|
||
modal.style.maxWidth = '32rem';
|
||
safeSetHTML(modal, `
|
||
<div class="pfm-modal-header">
|
||
<span class="pfm-modal-title" id="${escHtml(fieldId)}_cre_title"><i class="fas fa-plus-circle mr-2" aria-hidden="true"></i>Create New File</span>
|
||
<button type="button" class="pfm-btn pfm-btn-secondary pfm-btn-sm" id="${escHtml(fieldId)}_cre_close" aria-label="Close">
|
||
<i class="fas fa-times" aria-hidden="true"></i>
|
||
</button>
|
||
</div>
|
||
<div class="pfm-modal-body">
|
||
<div id="${escHtml(fieldId)}_create_err" class="pfm-field-error" role="alert" style="margin-bottom:.5rem;"></div>
|
||
${fields.map(f => `
|
||
<div class="pfm-field">
|
||
<label for="${escHtml(fieldId)}_cf_${escHtml(f.key)}">${escHtml(f.label || f.key)}</label>
|
||
<input type="text" id="${escHtml(fieldId)}_cf_${escHtml(f.key)}"
|
||
placeholder="${escHtml(f.placeholder || '')}"
|
||
${f.pattern ? `pattern="${escHtml(f.pattern)}"` : ''}>
|
||
${f.hint ? `<div class="pfm-field-hint">${escHtml(f.hint)}</div>` : ''}
|
||
</div>`).join('')}
|
||
</div>
|
||
<div class="pfm-modal-footer">
|
||
<button type="button" class="pfm-btn pfm-btn-secondary" id="${escHtml(fieldId)}_cre_cancel">Cancel</button>
|
||
<button type="button" class="pfm-btn pfm-btn-create" id="${escHtml(fieldId)}_create_btn">
|
||
<i class="fas fa-plus mr-1" aria-hidden="true"></i>Create
|
||
</button>
|
||
</div>`);
|
||
overlay.appendChild(modal);
|
||
modal.querySelector(`#${CSS.escape(fieldId)}_cre_close`).addEventListener('click', () => window._pfmCloseModal(fieldId));
|
||
modal.querySelector(`#${CSS.escape(fieldId)}_cre_cancel`).addEventListener('click', () => window._pfmCloseModal(fieldId));
|
||
modal.querySelector(`#${CSS.escape(fieldId)}_create_btn`).addEventListener('click', () => window._pfmConfirmCreate(fieldId));
|
||
trapModal(fieldId, modal, `${fieldId}_cre_title`, modal.querySelector('.pfm-field input'));
|
||
};
|
||
|
||
window._pfmConfirmCreate = async function (fieldId) {
|
||
const st = getState(fieldId);
|
||
const errEl = document.getElementById(`${fieldId}_create_err`);
|
||
const btn = document.getElementById(`${fieldId}_create_btn`);
|
||
const params = {};
|
||
|
||
for (const f of st.createFields) {
|
||
const inp = document.getElementById(`${fieldId}_cf_${f.key}`);
|
||
if (!inp) continue;
|
||
const val = inp.value.trim();
|
||
// Client-side pattern validation omitted — server-side create-file script validates.
|
||
params[f.key] = val;
|
||
}
|
||
|
||
if (btn) { btn.disabled = true; (function(b){b.textContent='';const i=document.createElement('i');i.className='fas fa-spinner fa-spin mr-1';b.appendChild(i);b.appendChild(document.createTextNode('Creating…'));})(btn); }
|
||
if (errEl) errEl.textContent = '';
|
||
|
||
const result = await callAction(st.pluginId, st.actions.create, params)
|
||
.catch(() => ({ status: 'error', message: 'Network error' }));
|
||
|
||
if (btn) { btn.disabled = false; (function(b){b.textContent='';const i=document.createElement('i');i.className='fas fa-plus mr-1';b.appendChild(i);b.appendChild(document.createTextNode('Create'));})(btn); }
|
||
|
||
if (result.status === 'success') {
|
||
notify('File created', 'success');
|
||
window._pfmCloseModal(fieldId);
|
||
await loadFiles(fieldId);
|
||
} else {
|
||
if (errEl) errEl.textContent = result.message || 'Create failed';
|
||
}
|
||
};
|
||
|
||
// ─── Toggle ───────────────────────────────────────────────────────────────
|
||
|
||
window._pfmToggle = async function (fieldId, categoryName, enabled) {
|
||
const st = getState(fieldId);
|
||
const result = await callAction(st.pluginId, st.actions.toggle, { category_name: categoryName, enabled })
|
||
.catch(() => ({ status: 'error', message: 'Network error' }));
|
||
if (result.status === 'success') {
|
||
notify(enabled ? `${categoryName} enabled` : `${categoryName} disabled`, 'success');
|
||
await loadFiles(fieldId);
|
||
} else {
|
||
// The action endpoint relays the script's own message on failure;
|
||
// without it every error reads as a bare "Toggle failed".
|
||
notify(result.message ? `Toggle failed: ${result.message}` : 'Toggle failed', 'error');
|
||
await loadFiles(fieldId); // revert UI
|
||
}
|
||
};
|
||
|
||
// ─── Upload ───────────────────────────────────────────────────────────────
|
||
|
||
window._pfmUpload = async function (fieldId, file) {
|
||
const st = getState(fieldId);
|
||
const notifyFn = window.showNotification || console.log;
|
||
if (!file.name.toLowerCase().endsWith('.json')) {
|
||
notifyFn('Only .json files can be uploaded', 'error'); return;
|
||
}
|
||
let content;
|
||
try { content = await file.text(); JSON.parse(content); }
|
||
catch { notifyFn('File contains invalid JSON', 'error'); return; }
|
||
|
||
const result = await callAction(st.pluginId, st.actions.upload, {
|
||
filename: file.name, content
|
||
}).catch(() => ({ status: 'error', message: 'Network error' }));
|
||
|
||
if (result.status === 'success') {
|
||
notify('File uploaded: ' + (result.filename || file.name), 'success');
|
||
await loadFiles(fieldId);
|
||
} else {
|
||
notify('Upload failed: ' + (result.message || ''), 'error');
|
||
}
|
||
};
|
||
|
||
// ─── Modal helpers ────────────────────────────────────────────────────────
|
||
|
||
function createOverlay(fieldId) {
|
||
window._pfmCloseModal(fieldId); // close any open modal first
|
||
const overlay = document.createElement('div');
|
||
overlay.className = 'pfm-overlay';
|
||
overlay.id = `${fieldId}_pfm_overlay`;
|
||
// Close on backdrop click
|
||
overlay.addEventListener('click', e => { if (e.target === overlay) window._pfmCloseModal(fieldId); });
|
||
document.body.appendChild(overlay);
|
||
getState(fieldId).currentModal = overlay;
|
||
return overlay;
|
||
}
|
||
|
||
// Dialog semantics + focus trap for an open modal (utils/dialog.js).
|
||
// Every close path goes through _pfmCloseModal, which releases it.
|
||
function trapModal(fieldId, modal, titleId, initialFocus) {
|
||
if (!window.LEDDialog) return;
|
||
const st = getState(fieldId);
|
||
st._releaseDialog = window.LEDDialog.trap(modal, {
|
||
labelledBy: titleId,
|
||
initialFocus: initialFocus || null,
|
||
onEscape: () => window._pfmCloseModal(fieldId)
|
||
});
|
||
}
|
||
|
||
window._pfmCloseModal = function (fieldId) {
|
||
const st = getState(fieldId);
|
||
if (st.currentModal) { st.currentModal.remove(); st.currentModal = null; }
|
||
st._editData = null;
|
||
st._editFilename = null;
|
||
if (st._releaseDialog) {
|
||
const release = st._releaseDialog;
|
||
st._releaseDialog = null;
|
||
release();
|
||
}
|
||
};
|
||
|
||
// ─── Widget registration ──────────────────────────────────────────────────
|
||
|
||
window.LEDMatrixWidgets.register('plugin-file-manager', {
|
||
name: 'Plugin File Manager Widget',
|
||
version: '1.0.0',
|
||
|
||
render: function (container, config, value, options) {
|
||
const fieldId = (options.fieldId || container.id || 'pfm').replace(/[^a-zA-Z0-9_-]/g, '_');
|
||
const wc = config['x-widget-config'] || {};
|
||
const actions = wc.actions || {};
|
||
const pluginId = options.pluginId || '';
|
||
|
||
const st = getState(fieldId);
|
||
Object.assign(st, {
|
||
pluginId,
|
||
actions,
|
||
createFields: wc.create_fields || [],
|
||
uploadHint: wc.upload_hint || 'Upload JSON files',
|
||
directoryLabel: wc.directory_label || ''
|
||
});
|
||
|
||
safeSetHTML(container, `
|
||
<div class="pfm-root" id="${fieldId}_pfm">
|
||
<div class="pfm-header">
|
||
<div>
|
||
<div class="pfm-title">File Explorer</div>
|
||
${st.directoryLabel ? `<div class="pfm-dir">Manage files in <code>${escHtml(st.directoryLabel)}</code></div>` : ''}
|
||
</div>
|
||
<div style="display:flex;gap:.375rem;">
|
||
${actions.create ? `
|
||
<button class="pfm-btn pfm-btn-create"
|
||
onclick="window._pfmOpenCreate('${fieldId}')">
|
||
<i class="fas fa-plus mr-1"></i>New File
|
||
</button>` : ''}
|
||
</div>
|
||
</div>
|
||
|
||
${actions.upload ? `
|
||
<div class="pfm-upload" id="${fieldId}_upload_zone"
|
||
onclick="document.getElementById('${fieldId}_file_input').click()"
|
||
ondragover="event.preventDefault();this.classList.add('dragover')"
|
||
ondragleave="this.classList.remove('dragover')"
|
||
ondrop="this.classList.remove('dragover');event.preventDefault();
|
||
if(event.dataTransfer.files[0])window._pfmUpload('${fieldId}',event.dataTransfer.files[0])">
|
||
<input type="file" id="${fieldId}_file_input" accept=".json"
|
||
style="display:none"
|
||
onchange="if(this.files[0])window._pfmUpload('${fieldId}',this.files[0]);this.value=''">
|
||
<i class="fas fa-cloud-upload-alt pfm-upload-icon" aria-hidden="true"></i>
|
||
<p>Drag and drop or click to upload</p>
|
||
<small>${escHtml(st.uploadHint)}</small>
|
||
</div>` : ''}
|
||
|
||
<div class="pfm-grid">
|
||
<div class="pfm-empty"><i class="fas fa-spinner fa-spin"></i>Loading…</div>
|
||
</div>
|
||
</div>`);
|
||
|
||
loadFiles(fieldId);
|
||
},
|
||
|
||
getValue: function () { return null; }, // file ops are immediate; nothing to submit
|
||
setValue: function (fieldId) { loadFiles(fieldId); }
|
||
});
|
||
})();
|