mirror of
https://github.com/ChuckBuilds/LEDMatrix.git
synced 2026-10-04 06:15:09 +00:00
* fix(web): keep Cache and Logs helpers out of each other's way Both partials declared top-level showError and escapeHtml. Their scripts run at global scope after every HTMX swap, so whichever tab was opened last owned window.showError, and a Cache failure after visiting Logs rendered into the Logs panel (and the other way round). Each script is now an IIFE; Cache still exports deleteCacheFile for its row buttons. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(web): make the HTMX-failure fallbacks for tab panels actually run - The "HTMX never loaded" fallback read appElement.__x.$data, which is Alpine 2. The page ships Alpine 3, so the check was always false and the Overview never loaded without HTMX. It now reads Alpine.$data(). - The Overview and WiFi panels used hx-on::htmx:response-error, which htmx expands to "htmx:htmx:response-error", an event that never fires. - loadTabContent sent requests with <body> as the source, so htmx fired its events on <body> and no panel's hx-on handler ran at all. The panel is now the source. htmx also resolves its promise on a 4xx/5xx, and the panel was stamped data-loaded anyway, leaving a skeleton that never retried; it is now stamped only when no responseError fired. loadPluginsDirect, loadOverviewDirect and loadWifiDirect are merged into one window.loadPartialDirect(id, url), which also runs the partial's inline scripts before Alpine sees the markup (as htmx-config.js does on htmx:afterSwap). The ~10 s "htmx never arrived" path in loadTabContent uses it for every tab instead of four hard-coded ones. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(web): store and registry failures no longer wipe the Plugin Manager showError replaced the whole #plugins-content with an error message, so one failed store search, custom-registry install or saved-repository call took the installed list, the store and every control with it, with no way back short of reloading the tab. Those failures are now error notifications. The full-panel message is kept only for a first load of the installed list that failed (nothing to show yet); a failed refresh of an already-rendered list is a notification too. showSuccess's fallback branch, which wrote the message into innerHTML unescaped, is gone: showNotification always exists. The "Please try refreshing your browser" hint tested for the text "Failed to Fetch", which no browser produces (Chrome says "Failed to fetch", Firefox "NetworkError..."), so it never appeared. It now keys on the failure itself: a TypeError from fetch(), or PluginAPI's NETWORK_ERROR wrapper around one. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(web): escape plugin action and install output on every path executePluginAction escaped data.message and data.output when an action failed but put data.message straight into innerHTML when it succeeded, and set the OAuth step-2 button's innerHTML from the manifest's step2_button_text. Plugin actions run plugin code, so that is plugin- or server-controlled markup in the page. Both paths now escape, and the button label is set with textContent. The same pattern sat in the install-from-GitHub-URL status lines (plugin_id, the server's message, and error.message, which can echo a repository URL) and the custom-registry load error; those are escaped too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(web): file-upload widget owns the image list and schedule editor plugins_manager.js loads after the widget bundle, so its older copies of deleteUploadedFile, updateImageList, hideUploadProgress, formatDate, openImageSchedule, toggleImageScheduleEnabled, updateImageSchedule{Mode, Time,Day} and updateCheckboxGroupData replaced the widget's. They are deleted; the widget files are the only definitions. Before switching over, the two sets were diffed and fixed so nothing regresses: - The old copy labelled the schedule/delete buttons for screen readers and lazy-loaded thumbnails; the widget now does both. - The schedule button did nothing on a card rendered by plugin_config.html whenever the image id is a UUID (every upload): the template turns "-" into "_" in the editor's id, and neither JS copy did. Both now use the template's rule. - The widget's "keep the open editor open" copied the editor's innerHTML into the new list. That dropped its event listeners and showed the old values, so after the first change the editor looked live but ignored input. A schedule edit now saves to the hidden input and updates the card's summary in place without re-rendering the list; a list re-render (upload, delete) rebuilds an open editor from the data. Editor controls are routed by one delegated change listener, so there are no per-element listeners to lose. - The old deleteUploadedFile had a JSON branch that removed a #file_<id> element and skipped the re-render. No template or script renders such an element, and JSON uploads are listed through updateImageList like images, so re-rendering (the widget's behaviour) is the consistent one; the branch was not carried over. - The template always renders the summary line (".image-schedule-summary", "Always shown" when unscheduled) so an edit has a line to update. The inline-handler test evaluated plugins_manager.js's updateImageList; test_file_upload_widget.js now covers the widget's list and editor. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(web): delete the unused handleCredentialsUpload Its last caller went when plugin_config.html switched credential uploads to the file-upload widget's handleSingleFileSelect. Nothing in the web UI, the tests or the plugin monorepo references it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(web): delete dead and shadowed front-end code Nothing calls any of these (checked across web_interface/, test/ and the ledmatrix-plugins monorepo, including hx-*/x-*/onclick attributes): - app-shell.js: the Alpine methods refreshPlugins (it called a nonexistent this.searchPluginStore), loadPluginConfig, savePluginConfig, getSchemaPropertyType, escapeCssSelector, formatCommitInfo and formatDateInfo, and the top-level copies of savePluginConfig, getSchemaPropertyType, escapeCssSelector, formatCommitInfo, formatDateInfo and togglePluginFromTab. Plugin config forms save through hx-post in plugin_config.html. - window.reconnectSSE (app-shell.js); window.updateArrayTableAddButtonState (array-table.js). - toggleNestedSection, defined twice (app-shell.js and plugins_manager.js) and called from nowhere. - plugins_manager.js: the window.initializePlugins wrapper around an IIFE-local origInit that was always undefined, and __pluginDomReady, which was written but never read. - display.html's fixInvalidNumberInputs fallback: app-shell.js defines it before any partial loads. - base.html's window.loadCodeMirror and the two CodeMirror stylesheet preloads, and the .CodeMirror rules in plugins.html. The raw JSON editor is a plain textarea. Also deleted: app-shell.js definitions that a later script always replaced, so they never ran: executePluginAction (plugins_manager.js assigns its own), uninstallPlugin and its pollUninstallOperation (plugins_manager.js), and updateAllPlugins (install_manager.js). vendor/codemirror stays: test/test_web_smoke.py still requests codemirror.min.js as a sample static asset. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(web): call showNotification without checking it exists app-shell.js defines window.showNotification (a stand-in that queues until the notification widget loads) and base.html runs it, deferred, before every other script that notifies: app.js, the utilities, the widget bundle, plugins_manager.js, and all partials, which HTMX loads after the page. The 81 `typeof showNotification === 'function'` / `!== 'undefined'` checks, the `window.showNotification || console.log` and `|| alert` fallbacks, and their else branches (alert(), console output, and schedule.html's own hand-built toast) could never take the fallback path. They are removed, as is fonts.html's second copy of the queueing stand-in. The stand-in in app-shell.js keeps its guard (it must not replace the widget's implementation if load order ever changes), and BaseWidget's public notify()/getNotificationFunction() keep their shape for widgets that plugins ship. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(web): one HTML escaper, window.LEDEscape About 30 files each carried their own escapeHtml / escapeAttr / escHtml / _esc / escapeJs. They disagreed: several (notification.js, display.html's escapeHtml, operation_history.html, the app() stub) did not escape quotes, google-calendar-picker.js and tools.html's escHtml left ' alone, and some turned 0 into ''. Most were fine only because the quote-safe widget copies were preferred at runtime. window.LEDEscape now lives at the top of app-early.js, a blocking script in <head>, so it exists before any other script runs: html(v) & < > " ' as entities, null/undefined as '' attr(v) the same, for call sites that want to say "attribute" jsStringAttr(v) a JS string literal safe inside an inline handler Every former copy is now a one-line name for it (kept so call sites do not change), widgets included, with no fallback. plugins_manager.js loses its four escapeJs wrappers (callers use jsStringAttr), the duplicate escapeAttr and escapeHtml inside renderInstalledCards and renderCustomRegistryPlugins, and the window.escapeHtml / window.escapeAttribute exports, which nothing read. addArrayObjectItem's fallback markup (with a sixth hand-written escape chain) is gone too: window.renderArrayObjectItem is defined earlier in the same file, so the fallback could not run. The unused escapeHtml methods on the Alpine app (app-early.js stub and app-shell.js) are deleted. test_html_escaping.js now runs LEDEscape and every remaining name for it, and fails if a hand-rolled escaper reappears anywhere in web_interface/. Suites that evaluate slices of plugins_manager.js or widget files load LEDEscape from app-early.js through test/js/led_escape.js. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(web): stop htmx re-running partial scripts after every tab load htmx-config.js runs each swapped-in <script> itself on htmx:afterSwap and meant to turn htmx's own script handling off with htmx.config.allowScriptTags = false. It did that once, while setting up, but base.html loads htmx with a dynamic <script>, so htmx was not defined yet and the setting never applied. On every tab load htmx then tried to run each script again in its settle phase, found it already replaced (no parent node) and threw "Cannot read properties of null (reading 'insertBefore')" into the console, which also skipped the rest of that swap's settle tasks. The setting is now applied in the afterSwap handler, which always runs after htmx exists and before htmx settles the same swap. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(web): show "--" for a system stat the server could not read The stats stream and /system/status now send null for a metric they cannot read (cpu_temp off a Pi, for one) instead of 0. updateSystemStats built the header and Overview text as value + unit, so a null showed as "null°C". CPU, memory and temperature, in the header and on the Overview, now render "--" plus the unit for null or a missing field -- the same placeholder the page starts with, and what tools.html already shows. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(web): one Alpine accessor and one plugin-list signal window.getApp() (app-early.js) returns the root <body x-data="app()"> component through Alpine's public Alpine.$data, or null before Alpine has initialised it. It replaces the private el._x_dataStack[0] reads in app.js, app-early.js, app-shell.js, settings-search.js, overview.html and plugins_manager.js, the three local getAppComponent/appData/getAppData copies, and the Alpine 2 el.__x.$data fallbacks, which Alpine 3 never provides. Publishing the installed-plugin list: one load set window.installedPlugins and dispatched pluginsUpdated twice (loadInstalledPlugins, then renderInstalledPlugins), then wrote into the Alpine component through _x_dataStack[0] and called its updatePluginTabs() directly, and app-early.js's global listener set window.installedPlugins a third time and called updatePluginTabs() again. Now renderInstalledPlugins is the one publisher: it sets window.installedPlugins and dispatches pluginsUpdated once, and the full app()'s listener (app-shell.js) is the receiver. The app-early.js listener only builds the tab row while the app is not the full implementation yet. The "grid not loaded yet" case is a normal state (Plugin Manager tab not opened), so it logs through pluginLog instead of console.warn. updatePluginTabs had a "Debounce" comment and clearTimeout over a timer nothing ever set, and two identical branches; it now just calls _doUpdatePluginTabs (app-early.js detects the full implementation by that name in its source, which the new comment says). app()'s unused baseComponent lookup is removed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(web): reload the plugin list after installs and failed toggles Several callers refreshed the installed list with if (typeof loadInstalledPlugins === 'function') loadInstalledPlugins(); else if (typeof window.loadInstalledPlugins === 'function') ... but loadInstalledPlugins is local to the plugin-manager IIFE and window.loadInstalledPlugins is never defined, so from outside that IIFE both tests were false and nothing reloaded: - A failed plugin toggle left the switch drawn in the new state while the data said the old one. It now re-renders from the reverted data. The optimistic in-place edit also has to forget the grid's last-rendered markup, or setGridHtmlIfChanged sees identical HTML and skips the revert. A successful toggle still keeps the switch (and focus) as drawn. - Installing from a GitHub URL (the early handleGitHubPluginInstall), installing or uploading a Starlark app, and toggling a Starlark app on its config tab never refreshed the list, so the new app had no tab or Installed badge until the page was reloaded. They now force a reload through window.pluginManager.loadInstalledPlugins(true), and the Starlark grid redraws when that finishes instead of after a fixed 500 ms. - The Starlark uninstall inside the IIFE reloaded from the 3 s cache, which could still hold the app; it now forces a reload. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(web): route debug output through debugLog base.html defines window.debugLog, gated on localStorage.pluginDebug. plugins_manager.js read the same key twice more into its own flags (_PLUGIN_DEBUG_EARLY, and PLUGIN_DEBUG behind a pluginLog() wrapper), and api_client.js's RequestThrottler had a separate `debug` property with a setDebug() that nothing called. All of it now goes through debugLog. The "functions defined" dumps with their ✓ lines, and two per-plugin "enabled=" loops that ran on every render, are dropped; "[PLUGINS STUB]" labels on code that has not been a stub for a long time read "[PLUGINS]". Ungated console.log calls that announced normal events on every page load or action (settings search and tooltips registering, every toast repeated to the console, the schedule pickers initialising, widget registry unregister/clear) go through debugLog too. What remains on console.log is the widget registry's on-demand LEDMatrixWidgets.debug() dump and BaseWidget.notify's no-notifier fallback. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(web): drop waits and guards that could never fire - handlePluginAction polled up to 10 x 50 ms for window.togglePlugin, configurePlugin, updatePlugin and uninstallPlugin before calling them. All four are defined when the scripts load, before any card can be clicked, so the poll always succeeded at once; it now calls them. The long thinking-aloud comment over the toggle state is replaced by two lines on why the stored state, not the checkbox, decides. - initializePlugins checked typeof on setupGitHubInstallHandlers and applyStoreFiltersAndSort, function declarations in the same IIFE, and wrapped window.checkGitHubAuthStatus(), which returns a promise with its own .catch, in try/catch. - searchPluginStore wrapped each "#store-count" update (a getElementById and an innerHTML assignment) in try/catch four times; one setStoreCount() helper does it. The store's post-render re-attach of the GitHub token handler dropped its try/catch and existence checks for the same reason. - The load-time fallback outside the IIFE tested typeof initializePluginPageWhenReady, which is IIFE-local and so always undefined there; it calls window.initPluginsPage directly. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(web): delete two unused plugin-manager helpers stopOnDemand (IIFE-local; the page's stop button calls window.stopOnDemand from app-shell.js) and debounce had no callers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(web): document the plugin-config handlers templates call validatePluginConfigForm, handleConfigSave, handleToggleResponse, handlePluginUpdate and refreshPluginConfig each get a JSDoc naming the attribute in partials/plugin_config.html that calls it and what the return value means (only validatePluginConfigForm's matters: false cancels the submit). - The `if (!window.__pluginConfigHandlersInitialized)` wrapper is gone: app-shell.js runs once per page, so it was never false. The block is dedented one level; `git diff -w` shows the real change. - The three handlers read xhr.responseJSON first. XMLHttpRequest has no such property (it is jQuery's), so that branch never ran; one xhrJson(xhr) helper parses responseText for all of them, with the same fallbacks as before. - runPluginOnDemand and stopOnDemand checked that plugins_manager.js's openOnDemandModal/requestOnDemandStop exist; plugins_manager.js is on every page, so they call them. - fixInvalidNumberInputs had a stray "Notification helper function" comment on top of its own; a leftover "section toggle ... duplicate definition removed" note is gone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(web): one toast per save, and a failed durations save says so app.js's global htmx:afterRequest listener showed the server's message for every htmx request, and every form and button that posts through htmx (plugin config save/toggle/update, Display, Durations, General, Schedule, Dim schedule, the Overview actions) also reports its own result from hx-on after-request. Each save showed two toasts. The global listener now stays quiet for a request whose element, or its form, has its own after-request handler. That exposed the Rotation & Durations form's handler, which read xhr.responseJSON: XMLHttpRequest has no such property, so it always said "Durations saved" in green, even when the save failed (the global toast had been the only place the error showed). display.html already had a correct version (2xx only counts as saved; the server's message wins; its status may refine success but never overturn failure). That is now window.showSaveResult(xhr, savedText, failedText) in app.js, used by the Display, Durations and General forms; General's inline copy of the same logic is gone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(web): file headers and comments that say what the code does now - plugins_manager.js, app-shell.js, app.js and app-early.js open with a header: what the file owns, how base.html loads it and in what order relative to the others, and the globals it defines. app-early.js's app() stub also says why it exists and that, with app-shell.js now loaded before Alpine, it does not run in practice. - base.html's note on plugins_manager.js said it must load last to win over same-named functions in app.js/app-shell.js; there are none left, so it now gives the real reason (it uses everything loaded before it). - Change-narration and "already defined at the top, no need to redefine" notes are gone or rewritten as present-tense reasons; comments that were wrong are fixed ("Toggle password visibility" over the function that opens the token panel, "Insert before the closing </nav>" over an appendChild, "(from v2)", the export note that still listed escapeHtml). About forty comments that restated the line below them are removed, and a second window.currentPluginConfig = null outside the IIFE is dropped (the IIFE sets it). - The file-upload, checkbox-group and custom-feeds widgets' render() stubs say plainly that the widget is rendered server-side, instead of "for now" / "placeholder for future client-side rendering". test_plugin_action_delegation.js sliced the source up to one of the removed notes; it now ends the slice at the next section header. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(web): keep the escapeHtml/escapeAttribute globals for plugin pages 6da77363 removed window.escapeHtml and window.escapeAttribute because nothing in core or the plugin monorepo read them. Plugin web UIs served through serve_plugin_web_ui and third-party plugin pages may still call them, so they come back as aliases of window.LEDEscape.html and .attr, defined in app-early.js before any other script runs. test_html_escaping.js checks the aliases exist. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(changelog): web-frontend Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(web): encode the image thumbnail path; match script tags case-insensitively CodeQL flagged the upload widget building an <img> src from a stored path, and the escaper test extracting inline scripts with a case-sensitive regex. Each path segment is now URL-encoded (still a same-origin path, and correct for names with spaces or * fix(web): clear Codacy findings in the escaper, app shell and upload widget - LEDEscape looks entities up in a Map instead of indexing an object. - showNotification is declared as a global for app-shell.js. - openImageSchedule checks the index is a non-negative integer and reads the image with Array.prototype.at. - The schedule editor calls escapeHtml directly and documents why its innerHTML template is safe: every value is escaped or constrained. The remaining rule hits are suppressed on that line with the reason. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(web): build the image schedule editor with DOM calls Codacy does not honour inline suppressions, and the editor's innerHTML template kept tripping its XSS rules even though every value was escaped. The editor is now built with a small element helper (createElement and setAttribute), so no value is ever parsed as HTML, and the file's own escapeHtml goes away. Also for Codacy: - LEDEscape.attr is its own function rather than a second name for html. - The tab loader records a failed load on the panel (data-load-failed) from a named handler, instead of a closure over a local flag. The fake DOM in test_file_upload_widget.js gains append/replaceChildren, its hostile-id check now asserts the id arrives as attribute data with no innerHTML anywhere in the editor, and test_html_escaping.js drops the file-upload.js escaper it no longer has. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(web): schedule editor helpers as plain functions Codacy's lint flags arrow functions held in local constants and a forEach callback that returns a value. The editor's pieces are now named function declarations (displayStyle, scheduleModeOption, scheduleRangeTime, scheduleDayTime, scheduleDayRow) taking what they need as arguments, and the element helper loops with for...of. htmx is declared as a global in app-shell.js. Output is unchanged; test_file_upload_widget.js passes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
859 lines
46 KiB
JavaScript
859 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) {
|
||
window.showNotification(msg, type);
|
||
}
|
||
|
||
function escHtml(s) { return window.LEDEscape.html(s); }
|
||
|
||
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);
|
||
if (!file.name.toLowerCase().endsWith('.json')) {
|
||
window.showNotification('Only .json files can be uploaded', 'error'); return;
|
||
}
|
||
let content;
|
||
try { content = await file.text(); JSON.parse(content); }
|
||
catch { window.showNotification('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); }
|
||
});
|
||
})();
|