mirror of
https://github.com/ChuckBuilds/LEDMatrix.git
synced 2026-08-01 16:58:06 +00:00
* chore(web): remove dead legacy client-side plugin-config generator (~2,300 lines) Plugin config forms have been rendered server-side (plugin_config.html via GET /partials/plugin-config/<id>) since the HTMX migration; the old client-side generator survived as unreachable code. Verified dead by call graph, not by naming: showPluginConfigModal and showGithubTokenInstructions have zero callers anywhere in templates or JS, and everything removed here is reachable only from those two roots. Removed: - plugins_manager.js: showPluginConfigModal, generatePluginConfigForm, generateFormFromSchema, generateFieldHtml, generateSimpleConfigForm, handlePluginConfigSubmit, the modal's JSON-editor view (initJsonEditor, switchPluginConfigView, syncFormToJson/JsonToForm, saveConfigFromJsonEditor, resetPluginConfigToDefaults, displayValidationErrors, closePluginConfigModal, savePluginConfiguration, currentPluginConfigState), their exclusive helpers (getSchemaPropertyType, escapeCssSelector, dotToNested, collectBooleanFields, normalizeFormDataForConfig, flattenConfig, loadCustomHtmlWidget), the orphaned-modal cleanup block, the modal's listener wiring, and the never-invoked showGithubTokenInstructions/closeInstructionsModal pair. - plugins.html: the #plugin-config-modal markup those functions drove. - base.html: the deprecated pluginConfigData() component and the window.PluginConfigHelpers shim (only ever called by pluginConfigData). Deliberately kept, verified still live: - renderArrayObjectItem, getSchemaProperty, escapeHtml/escapeAttribute (window-exposed for the top-level array-of-objects handlers the server-rendered form uses), toggleNestedSection, addKeyValuePair/ addArrayObjectItem families, executePluginAction, and window.currentPluginConfig = null init (file-upload.js and executePluginAction read it, optional-chained). - app()'s internal generateConfigForm/generateSimpleConfigForm methods in base.html: unreachable now but embedded in the live Alpine component; excising methods from a live object is deferred to keep this change zero-risk. Validation: every deletion seam inspected line-by-line; Jinja parse of both templates passes; repo-wide sweep confirms zero remaining references to any deleted function or element id (deleted ranges contained no Jinja tags). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ * feat(web): mobile navigation drawer + responsive CSS gap fixes Phones previously got the desktop layout squeezed: ~12 system tabs plus one tab per installed plugin wrapped into many rows of small pill buttons, and the header's settings-search and system-stats widgets were dropped entirely (hidden below their breakpoints, never relocated). - Off-canvas nav drawer below md: the existing nav markup (system tab row + #plugin-tabs-row, including dynamically injected plugin tabs) is wrapped in a #site-nav container that CSS repositions into a slide-in drawer on small screens. Same DOM nodes, same @click handlers, nothing duplicated. Tabs become full-width rows with 44px+ touch targets. A hamburger button (md:hidden) in the header and a backdrop toggle the new mobileNavOpen Alpine state (added to both app() definitions, mirroring activeTab). Clicking any tab, a search result, or the backdrop closes the drawer. At md+ hard CSS guards make all drawer styles inert - desktop renders exactly as before. - Header widgets relocated, not hidden: placeHeaderWidgets() in app.js moves the #settings-search-wrap and #system-stats nodes (same elements, listeners intact - both are looked up by id from SSE/search code, so they must never be duplicated) into the drawer below md and back into the header above it, via a matchMedia listener. - Fixed 13 breakpoint utility classes that templates referenced but app.css never defined (sm:block, sm:grid-cols-2, sm:text-sm, md:block, md:w-auto, lg:block, lg:flex, lg:w-64, xl:grid-cols-2/3, 2xl:grid-cols-2/3/4). This was a live bug: 'hidden sm:block' on the search box and 'hidden lg:flex' on the stats meant BOTH were invisible at every screen width. Audit method (repeatable): diff classes used in templates vs defined in app.css. - Mobile modal sizing: one global rule caps .modal-content at 95vw/90vh with internal scroll below 640px - covers every modal without per-template changes. - Horizontal-scroll affordance: pure-CSS edge-fade shadows on .overflow-x-auto containers (scrolling-shadows technique), plus larger in-table touch targets below md. Validation: breakpoint used-vs-defined audit now returns zero gaps; Jinja parse of base.html passes; all changes to desktop behavior are additive (new utilities) or scoped inside max-width media queries. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ * feat(web): x-advanced schema flag groups plugin config fields under a collapsed Advanced Settings section Plugin config pages show every schema property at equal visual priority, which overwhelms first-time users. Plugin authors can now add "x-advanced": true to any flat (non-object) property in config_schema.json to move it into one collapsed "Advanced Settings (N)" section rendered after the basic fields - progressive disclosure with zero loss of control. Implementation: the main render loop in plugin_config.html splits ordered properties into basic/advanced tiers; the advanced group reuses the exact .nested-section/.nested-content/toggleSection() shell that nested object sections already use, so the settings search's expand-on-match behavior works on advanced fields with no JS changes. Object-type properties ignore the flag (they already render as their own collapsible sections). No backend change needed: jsonschema ignores unknown x-* keywords exactly as it does for x-widget/x-propertyOrder. Documented in docs/widget-guide.md alongside the other x-* extensions. Validation (rendered with real Jinja, not just parsed): - synthetic schema with 2 advanced fields: basic fields render before the section, advanced inside the collapsed shell, count badge correct, x-advanced on an object property correctly ignored - schema without any x-advanced: output is identical to the pre-change template (whitespace-normalized diff against git HEAD's version) Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ * feat(web): Display Settings basic/advanced split + live total-resolution readout The Hardware Configuration card showed ~17 fields at equal priority; a new user only needs 7 of them to get a correctly-sized, correctly-colored image (rows, cols, chain_length, parallel, brightness, hardware_mapping, led_rgb_sequence). The other 10 (multiplexing, panel_type, row_address_type, gpio_slowdown, rp1_rio, scan_mode, pwm_bits, pwm_dither_bits, pwm_lsb_nanoseconds, limit_refresh_rate_hz) now live in a collapsed "Advanced Hardware Settings" section using the same nested-section shell as plugin config forms, so toggleSection() and settings-search auto-expand work unchanged. led_rgb_sequence moved up beside brightness/hardware_mapping (2-col grid became 3-col). No field was removed or renamed; the form still posts the same names to /api/v3/config/main. Also adds a live "Your display: W x H pixels" readout under the four sizing fields (width = cols x chain_length, height = rows x parallel - the exact math the chain-length tooltip describes in prose), recomputed client-side on every input event, no round-trip. Deviation from plan, deliberate: disable_hardware_pulsing / inverse_colors / show_refresh_rate stay in their separate "Display Options" card rather than moving across cards - relocating fields between form sections risks regressions for no decluttering gain in the card users complained about. Validation (real Jinja render): all 17 hardware fields present exactly once, basic fields render before the advanced section and the 10 advanced fields inside it, div count balanced (71/71), readout + recompute script present. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ * feat(web): plugin install auto-enables + persistent restart nudge Getting a plugin onto the display used to take three disconnected manual steps: install from the store, flip its enable toggle, then restart the display service - with no in-UI hint that steps 2 and 3 were needed (only docs/GETTING_STARTED.md mentions it). - installPlugin() now enables the plugin immediately on successful install (owner-confirmed behavior change: always auto-enable, no opt-out; users who don't want it running toggle it off as before), then shows a persistent toast ("... restart the display to show it") with an inline "Restart Now" button wired to the existing restartDisplay() - the same function the three existing Restart Display buttons call. - notification.js: show() accepts optional { actionLabel, onAction } to render one inline action button per toast. Callbacks are stored per notification id and cleaned up on dismiss; a new triggerAction() public method runs the callback and dismisses. The global showNotification() shorthand now forwards a full options object as its second argument (legacy type-string calls unchanged). Scope note: applies to the plugin store's install path (window.installPlugin). The custom-registry install path keeps its existing behavior. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ * feat(web): dismissible Getting Started checklist on Overview New users land on a dense multi-tab dashboard with no suggested order of operations (the only guided flow is the WiFi captive portal). This adds a non-gating checklist card at the top of Overview with five steps, each a deep link that switches to the right tab (and closes the mobile nav drawer): 1. Set panel size -> Display tab (done: rows/cols/chain_length > 0) 2. Set timezone/location -> General tab (done: differs from template defaults America/New_York / Tampa) 3. Install a plugin -> Plugins tab (done: /api/v3/plugins/installed non-empty) 4. Enable a plugin -> Plugins tab (done: any installed plugin enabled) 5. Configure it -> Plugins tab (done: first enabled plugin has >=1 saved value differing from its schema defaults) Steps 1-2 are computed server-side in Jinja from main_config (already in the partial's context); 3-5 client-side from existing endpoints. No new backend state: dismissal persists in localStorage (mirroring the reconciliation banner's sessionStorage pattern one section up); deep links use the same _x_dataStack app-data access as settings-search.js. Disclosed heuristic limit: values left at legitimate defaults (a user actually in Tampa) read as "not done". Validation: real Jinja render across 3 config variants confirms the server-side done-flags flip correctly; div balance intact; /plugins/config response shape (config dict directly in .data) verified against api_v3.py. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ * feat(display): drag-and-drop plugin rotation order for the primary display mode The primary rotation's order was invisible and unconfigurable: modes are registered in parallel-load COMPLETION order, so rotation order actually varied between restarts. Only the niche Vegas Scroll mode had a working order UI. This adds real, persisted ordering end to end: Backend: - config.template.json: new display.plugin_rotation_order (default [], fully backward compatible). - display_controller.py: _apply_plugin_rotation_order() rebuilds available_modes grouped by plugin per the configured list (each plugin's modes keep their declared order; unlisted plugins follow in existing relative order; empty config = exact no-op). Applied at startup after parallel load and after live enable/disable reconcile (before the existing _resync_mode_index_after_change, which preserves the current mode). Mirrors vegas_mode get_ordered_plugins() semantics. - api_v3.py save_main_config: accepts plugin_rotation_order as a JSON array (same parse/guard pattern as vegas_plugin_order). Frontend: - New shared widget static/v3/js/widgets/plugin-order-list.js: the Vegas section's drag-and-drop list factored out verbatim (native HTML5 drag events, saved-order-first rendering, hidden-input JSON sync), parameterized by container/order-input/optional exclude-checkbox/badge. - display.html: Vegas section now calls the shared module; its ~130-line inline copy of the same logic is deleted. - durations.html: new "Rotation Order" card above the durations grid using the same module, posting plugin_rotation_order with the existing form. Deviation from plan, deliberate: durations stay as their own mode-keyed grid rather than inline in the drag rows - verified display_durations keys are MODE names (display_controller.py resolves duration per mode_key), not plugin ids, and one plugin can own several modes, so the planned 1:1 inline pairing was wrong. Validation: py_compile on both Python files; _apply_plugin_rotation_order unit-tested standalone (configured order applied, empty-config no-op, unknown ids skipped - 3/3); both templates render with balanced divs, the hidden input carries the saved order, and the old inline implementation is confirmed gone; config.template.json parses. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ * feat(web): serve the interface at / — /v3 kept as a legacy alias The user-visible URL no longer carries the interface version: the pages blueprint is now registered un-prefixed (primary) AND at /v3 (second registration, name='pages_v3_legacy'), so: - http://<device>/ serves the interface directly (the old @app.route('/') redirect is removed — the blueprint's own index takes its place) - every existing /v3/... bookmark and all the hardcoded /v3/partials/... fetches in templates/JS keep working verbatim through the alias mount — zero template/JS churn, zero broken links - url_for('pages_v3.*') resolves against the primary registration, so all server-side redirects (captive portal detection endpoints) now emit un-prefixed URLs - the AP-mode captive-portal allowlist learned the un-prefixed page paths (/setup, /partials/, /settings/, /plugin-ui/) so setup-mode requests don't redirect-loop - /api/v3 and the templates/v3, static/v3 directories are deliberately untouched (internal, invisible to users; owner-confirmed scope) Validation: dual registration mechanics tested against real Flask (test client): /, /v3, /v3/ redirect, partials and /setup reachable on both mounts, url_for yields un-prefixed paths; py_compile passes. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ * perf(web): stream the preview PNG raw instead of PIL decode + re-encode display_preview_generator() opened each changed snapshot with PIL and re-encoded it to PNG just to base64 it — but /tmp/led_matrix_preview.png already IS a PNG, written atomically by the display service (tmp file + os.replace in display_manager.py), so a partially-written file can never be observed. Read the bytes and base64 them directly: identical payload (front-end consumes data:image/png;base64 — verified in base.html), one full image decode+encode per frame less on the same Pi that's driving the matrix. The existing mtime skip and viewer-marker throttling are unchanged (they already covered the "skip unchanged frames" concern). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ * perf(web): gzip response compression via flask-compress The interface ships a ~5,000-line HTML shell and >20k lines of JS uncompressed; on phone/WiFi that dominates load time. Flask-Compress gzips/brotlis compressible responses transparently. - Optional dependency, same graceful pattern as flask-limiter: missing package = uncompressed responses, no crash. - SSE safety verified empirically against the real package (1.24): an actual streamed text/event-stream response comes back with no Content-Encoding while a large HTML response gzips — the display preview / stats / logs streams are unaffected. - Added flask-compress>=1.14 to web_interface/requirements.txt. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ * perf(web): gate verbose console logging behind the existing pluginDebug switch plugins_manager.js, base.html's inline scripts, and app.js emitted 198 console.log calls in production - including per-interaction [DEBUG] dumps - costing main-thread time and drowning real errors in noise. - New window.debugLog() gate defined in base.html's first inline script (before any other script runs): forwards to console.log only when localStorage.pluginDebug === 'true' - the SAME switch plugins_manager.js already used for its _PLUGIN_DEBUG_EARLY logs, so existing debug workflow docs stay valid. Exposed as window.LEDMATRIX_DEBUG for other scripts. - Mechanically rewrote console.log( -> debugLog( in plugins_manager.js (127), base.html (64), app.js (7). Verified no occurrences lived inside string literals before rewriting; console.error/console.warn untouched. - app.js's no-Alpine showNotification fallback restored to console.info - it's a user-facing last resort, not debug output. Both load paths are safe: the gate is the first inline <script> in <head>, and every rewritten file loads deferred after it. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ * perf(web): vendor CDN assets locally — LAN-speed loads, fully offline-capable Font Awesome, CodeMirror, and htmx were fetched from cdnjs/unpkg on every fresh page load, adding third-party round-trips on a device that often lives on a local network (and htmx was local-only in AP mode, meaning two different loading behaviors to reason about). - Vendored pinned copies under static/v3/vendor/: Font Awesome 6.0.0 (css/all.min.css + the 8 webfonts it references relatively) and CodeMirror 5.65.2 (core, javascript mode, closebrackets/matchbrackets addons, base + monokai css) - ~1.1 MB total, exact versions the CDN tags pinned. - htmx + sse + json-enc extensions now load from the existing local copies (verified 1.9.10, matching the CDN pin) on EVERY network, not just AP mode; the pinned CDN copies remain as a one-shot rescue fallback, mirroring the pattern Alpine already used. The convoluted isAPMode source-flipping logic collapses away. - Dropped the CDN preconnect/dns-prefetch hints (no longer on the critical path). - Fixed a latent bug while relinking CodeMirror: the loader requested mode/json/json.min.js, which does not exist on cdnjs (HTTP 404 verified) - it 404'd on every JSON-editor open. JSON highlighting comes from the javascript mode; the phantom entry is removed. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ * perf(web): extract 3,850 lines of inline JS from base.html to cacheable static files base.html shipped ~4,200 lines of inline JavaScript inside the HTML document, re-downloaded and re-parsed on every page load (gzip helps the transfer, but inline scripts can never be browser-cached). The four largest blocks - none containing any Jinja syntax, verified by scanning every inline block for {{ }} / {% %} - now live as static files served with the app's existing mtime-versioned immutable caching: - js/htmx-config.js (246 lines): HTMX swap/script-execution config, toggleSection helpers - js/app-early.js (346 lines): early helpers + the app() stub that must precede Alpine init - js/app-shell.js (2,997 lines): SSE wiring + the full Alpine app() implementation and tab logic - js/custom-feeds-helpers.js (262 lines): custom-feeds table helpers Each replacement <script src> is CLASSIC (no defer/async) at the exact position of the inline block it replaces - identical execution timing and DOM visibility to inline scripts, so relative ordering with the deferred scripts and with each other is unchanged. base.html drops from ~4,940 to 1,079 lines. Validation: extraction proven lossless by programmatically reassembling the four files back into the template and comparing against git HEAD - byte-for-byte identical. Jinja parse passes; script open/close tags balanced (53/53, after excluding a literal "<script>" inside an HTML comment). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ * fix(web): size the live preview from the PNG's real dimensions, not config The initial SSE render sized the preview image (and both overlay canvases) from the server-reported config dimensions (cols x chain_length, rows x parallel), while the scale slider's re-render path sized from img.naturalWidth/naturalHeight. Whenever the snapshot PNG's actual size disagrees with the config (stale config, display service not restarted after a hardware change), the initial render stretched the image at a fractional ratio - blurry despite image-rendering: pixelated - and touching the scale slider "fixed" it. Reported live on the devpi test rig. Both paths now size from the loaded image's natural dimensions inside img.onload (which also removes a transient wrong-size flash between src assignment and load). The meta label now reports the true snapshot size. The preview card also gets overflow-x-auto so on narrow screens a wide preview scrolls at its exact pixel-perfect size instead of being squeezed into the viewport (fractional downscaling of pixel art also reads as blur). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ * feat(web): fold Display Options into the advanced dropdown; Vegas above Double-Sided Owner-requested layout refinement of the Display Settings tab: - The "Display Options" card (disable_hardware_pulsing, inverse_colors, show_refresh_rate, use_short_date_format, Dynamic Duration) moves inside the collapsed advanced section, now titled "Advanced Hardware & Display Options (15)". Hidden form fields still submit with the form, and settings search still auto-expands the section on match, so nothing is lost - the tab just leads with the essentials. - The "Vegas Scroll Mode" section moves above "Double-Sided Display". New section order: Hardware (+ advanced dropdown) > Vegas Scroll > Double-Sided > Multi-Display Sync. Validation (real Jinja render): all 23 field names present exactly once, divs balanced (70/70), the five Display Options fields render inside the advanced section's bounds, and section markers confirm the new order. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ * feat(web): Getting Started items are manually checkable; card auto-hides when complete Two gaps reported from live testing on the devpi rig: 1. The timezone/location step never showed done for a user whose real timezone IS the shipped default (America/New_York) - the heuristic can only detect difference-from-default, not "user saved this". Clicking an item's checkbox now toggles it done manually (persisted per browser in localStorage), so any heuristic false-negative is one tap to clear. Clicking the item text still deep-links to its tab. 2. The card now hides itself automatically once every step is done (auto-detected or manually checked) - previously it stayed until the X was clicked. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ * chore(web): CI cleanup — declare debugLog global, fix entity-unescape order, drop v3 from UI branding - Add debugLog to the /* global */ headers of the six JS files that call it (defined in base.html's first inline script) — resolves the wall of "'debugLog' is not defined" ESLint errors failing the Codacy check. - Fix the two js/double-escaping CodeQL alerts in app-shell.js: the entity-unescape chains decoded & before </>, so a value containing a pre-escaped "&lt;" wrongly double-decoded to "<". & now decodes last (standard order). Pre-existing bug, made visible when the inline scripts moved into scannable .js files. - Page title / header drop the "- v3" suffix, matching the de-versioned user-facing URL. The remaining 7 CodeQL alerts are pre-existing patterns newly visible to scanning (CodeQL doesn't see inline template JS): 4 github.com/htmx.org URL-substring checks (the htmx ones match error-message text, not URLs — false positives in context) and 1 innerHTML XSS-through-DOM in the GitHub install flow. Triage/fix deferred to a focused follow-up rather than expanding this PR. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ * fix(web): add the missing nav tab for the Rotation & Durations page The durations partial (/partials/durations) has existed as a route with no nav tab and no content panel referencing it - an orphaned page. That made the new rotation-order UI unreachable through the interface (caught by the owner testing on the rig; my endpoint-level tests fetched the partial by URL and never noticed the missing entry point). - New "Rotation" tab (fa-rotate icon, verified present in the vendored FA 6.0.0 css) between Display and Backup & Restore, wired exactly like the other tabs (#durations-content + hx-get + loadtab; loadTabContent() is fully generic, so no JS changes needed). - Page heading updated from "Display Durations" to "Rotation & Durations" to match its content since the rotation-order card landed. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ * fix(web): Rotation & Durations page lists every enabled plugin's screens The durations grid looped over display.display_durations, which nothing has ever populated (verified {} on a real production install) - so the page rendered no duration fields at all. Worse, its inputs posted bare mode names, which save_main_config's endswith('_duration') filter silently dropped: the page was broken in both directions, unnoticed because it was also unreachable (previous commit). - pages_v3._load_durations_partial now builds one entry per display mode of every ENABLED plugin via plugin_manager.get_plugin_display_modes() (falling back to the plugin id), overlaid with saved values, defaulting to the display controller's 30s. Grouped per plugin, sorted by name. Saved keys not owned by any enabled plugin stay visible under "Other saved entries" instead of vanishing. - durations.html renders the grouped inputs, named duration__<mode_key> (mode keys are arbitrary, so they can't use the *_duration suffix convention), with an explanatory empty state when no plugins are enabled. - api_v3.save_main_config accepts the new duration__<mode> fields and writes them into display.display_durations under the bare mode key - exactly what the display controller reads (display_durations.get(mode_key, 30)). Validation: py_compile both blueprints; Jinja render with 3 groups asserts grouped inputs, saved-value overlay, stale-entry group, empty state, and div balance. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ * feat(web): restart-pending banner, unsaved-changes guard, installable web app Three usability improvements from live testing feedback: - Restart-pending banner: every successful POST to /api/v3/config/main (display hardware, rotation/durations, general settings) now raises a persistent banner - "Configuration saved, restart the display to apply" - with a Restart Now button that posts restart_display_service directly. Backed by sessionStorage so it survives tab switches and reloads until restarted or dismissed. Plugin config saves are deliberately excluded: they apply live via the display process's config watcher. - Unsaved-changes guard: plugin config panels are Alpine x-if templates, so navigating away destroys the panel and revisiting re-fetches it - edits were silently discarded. Forms now mark themselves dirty on input (cleared on successful submit), a capture-phase click handler confirms before a lossy tab switch, and beforeunload guards full page unloads. System tabs (x-show, persistent DOM) are exempt - no false prompts. - Installable web app: manifest.json (standalone display, dark theme) + generated LED-grid icons (192/512 maskable + 180 apple-touch), linked from base.html. "Add to Home Screen" now yields an app-like fullscreen experience; no service worker, so zero behavioral risk. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ * test(web): smoke tests + static-analysis audits for the web UI Guardrails so this branch's fix classes can't regress silently: - test_web_smoke.py (24 tests): boots the pages blueprint with the same dual registration app.py uses and asserts every page/partial returns 200 with its load-bearing markers (nav wiring, getting-started card, advanced section, rotation order card, per-mode duration inputs), the /v3 legacy alias serves everything, all critical static assets (incl. vendored fontawesome/codemirror, PWA manifest/icons) are served, durations group per plugin with the leftover bucket, and the advanced-hardware section really contains the tuning fields. Would have caught this session's unreachable-durations-page and orphaned-tab bugs instantly. - test_web_static_audit.py (3 tests): (1) every responsive utility class referenced in templates is actually defined in app.css - the silently-no-op class bug that left the header search box invisible at every width; (2) every url_for('static', ...) reference points to a real file; (3) any JS file calling the debugLog global declares it in a /* global */ header. All 40 web tests pass (24 + 3 new, 13 existing) under pytest + Flask. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ * feat(web): floating live preview + per-plugin "Preview on display", drawer a11y Preview-while-configuring: - Floating mini preview (fixed, bottom-right) available on every tab except Overview, fed from the same SSE display stream by updateDisplayPreview - no new connections. Collapses to a round toggle button; open/closed state persists in localStorage; hides on Overview where the full preview lives. - "Preview on display" button on every plugin config page header: runs that plugin on the real display for 60 seconds via the existing /display/on-demand/start API and opens the floating preview, closing the configure -> see-the-result loop. Drawer/nav accessibility: - aria-current="page" tracks the active tab (system + dynamic plugin tabs, matched via their Alpine @click expression), updated from the activeTab watcher so search deep-links and checklist navigation are covered too. - Escape closes the mobile drawer and returns focus to the hamburger; opening the drawer moves focus to its first tab. Validation: all 40 web tests pass; Jinja parse + div balance on both touched templates. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ * fix(web): resolve Codacy findings — DOM building over innerHTML, Map callbacks, misc lint Verified each of the 27 reported findings against current code; all fixed except one rule class skipped with reason below. - app-early.js: plugin tab buttons are now built with createElement/ createTextNode instead of innerHTML template strings (icon class and name come from plugin manifests - semi-trusted input; the old code escaped the name but interpolated the icon class). Both construction sites. Also the forEach arrow no longer returns tab.remove()'s value. - plugin-order-list.js: rows, empty state, and error state all built with DOM APIs - the file no longer contains innerHTML at all (the now-unneeded escapeHtml/escapeAttr helpers are removed); MODE_LABELS is a Map so the vegas-mode lookup can't hit prototype properties. - notification.js: actionCallbacks is a Map (get/set/delete) instead of a plain object - resolves the object-injection-sink and dynamic-delete findings; triggerAction also type-checks the callback. - htmx-config.js: unused catch binding dropped; var -> const in the afterSettle handler; the swapped-<script> re-execution reads/writes textContent instead of innerHTML; the diagnostic form payload uses a null-prototype object so a field named __proto__ can't pollute. - custom-feeds-helpers.js DELETED (with its script tag): all three of its functions (addCustomFeedRow, removeCustomFeedRow, handleCustomFeedLogoUpload) are shadowed by the deferred widgets/custom-feeds.js window assignments, which always win at call time - the copies were dead even when they lived inline in base.html. This also resolves the unused-function and unused-variable findings there. Skipped: 4x "Non-serializable expression must be wrapped with $(...)" in app-early.js - that rule targets code crossing a browser-automation serialization boundary (e.g. page.evaluate); these are ordinary arrow functions in plain browser code with no such boundary. Validation: all 40 web tests pass (incl. the static-asset reference audit, which confirms no template still points at the deleted file); Jinja parse OK. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ * feat(web): update flow installs changed Python dependencies automatically The in-app updater (Update Now banner -> git_pull action) stashed, pulled, and purged plugins - but never touched Python dependencies. Any release adding a package (e.g. this branch's flask-compress, which lives in web_interface/requirements.txt) silently required an SSH session and a manual pip install that most users will never do. - git_pull now records HEAD before pulling; after a successful pull it diffs old..new and, if requirements.txt or web_interface/requirements.txt changed, installs exactly those via _pip_install_requirements - the same vetted root-visible sudo path the Tools-tab buttons use (with its existing graceful fallback when the sudo wrapper isn't configured). Results are appended to the update toast; a failure points the user at the Tools-tab button instead of failing the whole update. - install_base_requirements (Tools tab) now also installs web_interface/requirements.txt - previously it only covered the root file, so web-only dependencies were unreachable from the UI entirely. No install happens when the pull was already-up-to-date or when no requirements file changed, so routine updates stay fast. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ * fix(web): address CodeRabbit review — validation, a11y, perf, and privacy fixes Verified each finding against current code. Fixed: - api_v3: plugin_rotation_order is now strictly validated (JSON list of strings, 400 with a descriptive message otherwise) and popped from the payload before any further handling. - display_controller: _apply_plugin_rotation_order defensively ignores a non-list value (keeps the existing rotation, logs a warning) and drops non-string entries; new logs carry the [DisplayController] prefix. Unit-tested both defensive paths. - app.py: snapshot-read handler narrowed to OSError with debug logging; flask-compress ImportError now emits one structured warning with the install remedy. - htmx-config: the response-error logger prints form FIELD NAMES only - values (API keys, passwords) never reach the console. - plugin-order-list: saved order/exclusions normalized with Array.isArray (a saved "null" previously crashed .forEach); each row gained keyboard/touch-accessible move-up/move-down buttons (HTML5 drag events don't fire on most mobile browsers) that reorder and syncInputs() immediately alongside native drag. - app-shell: window.installedPlugins setter always takes the new list (same-ID metadata/enabled updates were silently dropped); tab rebuild stays gated on ID changes. LED dot renderer reads the frame with ONE getImageData call instead of one per pixel (~9,200/frame at 192x48). - plugins_manager: togglePlugin returns its request promise resolving the API outcome; the install flow now shows the "installed and enabled" toast (with Restart Now) only after enablement succeeds, and a warning without a restart offer when it fails. - a11y: hamburger aria-label flips Open/Close with drawer state; both Advanced-section toggle buttons declare aria-controls/aria-expanded and the shared toggleSection() keeps aria-expanded in sync; move buttons have per-plugin aria-labels. - Rotation/Vegas order-list bootstraps cap their retries (~5s) and show a reload hint instead of spinning forever; Alpine app-state lookups prefer [x-data="app()"] with a generic fallback. Skipped, with reasons: - executePluginAction arg order: caller (plugin_config.html) already passes (actionId, index, pluginId) matching the signature exactly. - generateFieldHtml XSS, entity-unescape blocks, dotToNested pollution, and "app.loadInstalledPlugins" in app-shell: all inside the legacy client-side config cluster whose entry points are shadowed by plugins_manager.js / replaced by server-rendered forms (zero live callers, verified) - queued for wholesale deletion in the follow-up rather than patching dead code. - custom-feeds-helpers.js findings (3): file was deleted in a prior commit. - console.error/warn override removal and afterSwap script re-execution removal: deliberate pre-existing workarounds every partial's inline init currently depends on; reworking them safely needs isolated testing (follow-up), and the error suppression is already double-gated (insertBefore AND htmx match). - "move durations bootstrap into a bundle": inline partial-scoped init is the established pattern for HTMX partials in this codebase. Validation: all 40 web tests pass; py_compile on all touched Python; all touched templates parse; rotation-order defensive paths unit-tested. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ * chore(web): fix remaining real Codacy findings (2 of 6) - htmx-config.js: two more unused catch bindings dropped (optional catch binding), matching the earlier fix. - app-early.js: second forEach arrow (the stub updatePluginTabs copy) braced so the callback no longer returns tab.remove()'s value. The other 4 findings ("Non-serializable expression must be wrapped with $(...)") are deliberately NOT "fixed": that rule belongs to a browser-automation (WebdriverIO-style) lint context and is misfiring on ordinary arrow-function constants. Converting them to function declarations would look compliant but BREAK the code - all four arrows intentionally capture the enclosing Alpine component's `this` for the stub-to-full enhancement logic. The right remedy is disabling that pattern for this repo in Codacy's Code Patterns settings (or dismissing the four findings), not a code change. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ * fix(web): floating preview shows a frame immediately on open + is resizable The floating preview opened empty and stayed empty until the display next CHANGED - the SSE stream only pushes frames on change, and the panel only consumed frames while already open, so the connection's initial frame (sent while the panel was closed) was dropped. Reported from mobile testing as "the button doesn't work". - updateDisplayPreview now caches the latest frame globally regardless of panel state; opening the panel populates the image from that cache instantly, then live frames take over. - Resizable: a size button cycles 192/256/384/512px presets (persisted per browser; works on touch), and desktop additionally gets a native drag handle (CSS resize: both). The image is fluid within the panel; on phones the panel is capped to the viewport width. The size icon (fa-up-right-and-down-left-from-center) is verified present in the vendored FA 6.0.0. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ * fix(web): stop duration fields leaking into config root; isolate per-file dependency installs; fix test fixture leak Verified each finding against current code. - api_v3 save_main_config: both duration blocks (*_duration suffix fields and the newer duration__<mode> fields) only READ from `data`, never removed the keys. The generic "remaining keys" merge later in the same function has no skip-list entry for either pattern, so every duration field was ALSO written a second time as a bogus top-level config key (e.g. "clock_duration": 30 and "duration__mlb_live": 42 sitting at config root, alongside the correct nested display.display_durations.<key>). Confirmed by tracing the full function. Fixed by popping each handled key from `data` (same pattern already used for plugin_rotation_order) and validating strictly: a non-integer duration now returns 400 with a message naming the offending field/mode instead of silently logging and moving on (for the *_duration fields, which previously had zero validation at all). - api_v3 dependency-install loops (git_pull's post-update sync and install_base_requirements): _pip_install_requirements can raise subprocess.TimeoutExpired or OSError (confirmed: install_requirements_file in permission_utils.py never catches either internally, despite its docstring's "never raises on non-zero exit" only covering return codes). Both loops previously let one file's exception either abort the whole try block (skipping the second requirements file entirely) or propagate uncaught. Each file's install is now in its own try/except, so a timeout or OSError on one file is recorded as a labeled failure and the loop continues to the next file. - test_web_smoke.py: the `client` fixture mutated the module-level pages_v3 Blueprint singleton's config_manager/plugin_manager directly with no teardown - since pages_v3 is shared across the whole pytest process (test_web_settings_ui.py touches the same attributes), this fixture's mocks could leak into whichever test ran next. Now saves the originals, yields the client, and restores them in a finally block. Validation: py_compile passes; all 40 web tests pass with the now-generator fixture. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ * fix(web): repair garbled Advanced Hardware section description An earlier sed-based text update concatenated the old and new copies of this description instead of replacing one with the other, leaving a duplicated sentence with the — entity broken into ".mdash;" (visible as literal "mdash;" text on the page). Restored to one clean sentence. Other findings from this review were already fixed in a prior commit (installedPlugins setter) or are confirmed dead code with zero live callers (executePluginAction/dotToNested/entity-unescape/generateFieldHtml, all reachable only from the two unused savePluginConfig copies in app-shell.js - grepped every template, no references) - same legacy cluster flagged in earlier review passes, still queued for a dedicated deletion follow-up rather than patched in place here. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ * fix(web): remove redundant htmx:afterSwap script re-execution (was double-executing every partial's inline script) Re-verified this CodeRabbit finding, previously deferred as "needs isolated testing" - traced it to a confirmed, active bug rather than a style concern: htmx 1.9.10's own config defaults to allowScriptTags: true (confirmed in the vendored htmx.min.js, which itself contains the same clone-and-reinsert <script> mechanism internally). This means htmx ALREADY re-executes every <script> tag in swapped content by default, exactly like a browser navigating to a new page. The custom htmx:afterSwap listener in htmx-config.js did the identical clone-and-reinsert a SECOND time on top of htmx's own handling - so every inline <script> block in every HTMX-loaded partial (overview, display, durations, plugin config, etc. - most partials have one) executed twice per load. Confirmed safe to delete outright, not just narrow: grepped every hand-written JS file for a manual `dispatchEvent(... 'htmx:afterSwap' ...)` that might have relied on this handler for a non-htmx code path (e.g. the direct-fetch fallbacks like loadOverviewDirect) - none exists, so nothing depended on this listener specifically; htmx's native handling covers every real htmx-driven swap on its own. Left in place, unchanged: the console.error/console.warn global override a few lines up in the same file, which suppresses known-noisy HTMX-timing-race messages. That one is a legitimate anti-pattern too (broad substring matching can mask unrelated errors) but redesigning it needs care to preserve real diagnostics while still hiding the specific harmless races it targets - a scoped follow-up, not a same-day deletion like this confirmed-duplicate handler. Validation: all 27 fast web tests pass; JS brace/paren balance sanity checked (no local Node/browser available in this sandbox to execute the file directly - verify manually in-browser before merge). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ * chore(display): add missing [DisplayController] prefix to the reconcile-complete log Re-verifying the full CodeRabbit findings list against current code surfaced one still-open item: the nitpick asked for the prefix on BOTH rotation-related log lines, but only "Applied plugin rotation order" got it in the earlier pass - "Plugin reconcile complete" was missed. No message/argument/level change, matching the finding's own scope. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KEZK1P1Q1fu5pcuVrkrCFZ * fix(web): repair dead /v3/logs link on the display hardware-error banner The "Logs tab" link in the display-settings simulation-mode banner was a real <a href> to /v3/logs, but no such route has ever existed (log content is loaded client-side via activeTab, not a dedicated page route) - the link 404'd regardless of the /v3 prefix change. Switch it to the same activeTab-switching pattern the real nav uses. * fix(web): raise display Rows field max from 64 to 128 Cols already allowed up to 128; Rows was capped at 64, which rejects valid larger panel configurations (e.g. 128-row tile chains). No server-side schema enforces a rows max, so this was purely an overly-strict HTML input attribute. * fix(web): remove redundant htmx.org substring check flagged by CodeQL CodeQL flags .includes('htmx.org') as "incomplete URL substring sanitization" - a false positive here, since this string is only ever matched against console.error/warn message text to decide whether to suppress a known-harmless HTMX timing-race log line, not used for any URL-trust/redirect decision. The check was also redundant: 'htmx' is already a substring of 'htmx.org', so the plain .includes('htmx') check right next to it already covers every case the removed check did. * fix(web): restore htmx script re-execution timing that Alpine x-data depends on Removing the custom htmx:afterSwap script-reexecution handler (in a prior commit, as a "duplicate execution" cleanup) broke every partial whose Alpine x-data component function is defined by an inline <script> in that same partial (e.g. wifi.html's wifiSetup()) - confirmed live via browser console: "Alpine Expression Error: wifiSetup is not defined" on every field in the WiFi tab. Root cause: htmx's own native script execution runs during its "settle" phase (~20ms after swap, per htmx's own defaultSettleDelay), but Alpine's MutationObserver evaluates x-data on newly-inserted elements synchronously, right as the swap lands - before settle. So the inline <script> defining wifiSetup() was still un-run when Alpine tried to call it, and Alpine does not retry a failed x-data evaluation later once the function does become defined. Fix: re-execute swapped <script> tags ourselves on htmx:afterSwap (which fires synchronously, before settle, beating Alpine's observer), and disable htmx's own native script re-execution (htmx.config.allowScriptTags = false) so the same script doesn't also run a second time during settle - restoring correct timing without reintroducing the original double-execution bug. Also in this commit: - fix XSS: unescaped repoUrl in a title attribute in renderSavedRepositories - replace .includes('github.com') substring checks with real URL hostname validation (CodeQL: incomplete URL substring sanitization) * fix(web): wait for async plugin install to finish before auto-enabling it Confirmed live: installing hockey-scoreboard logged "installation queued" (success) immediately followed by "enabling it failed" with a 404 "Plugin not found" from /api/v3/plugins/toggle. /api/v3/plugins/install runs the actual clone + plugin-manager discovery asynchronously via an operation queue when one is configured - the response installPlugin() was checking only means the operation was queued, not that the plugin is installed yet. Calling togglePlugin() right after that response 404s because plugin_manager hasn't discovered the new plugin. Fix: reuse the same operation-polling mechanism uninstallPlugin() already has (generalized pollOperationStatus() to take onComplete/onFailed/onTimeout callbacks instead of hardcoding uninstall behavior) so installPlugin() waits for the operation to actually complete before enabling it. Falls back to enabling immediately when no operation_id is returned (direct/synchronous install path, no queue configured). * fix(web): resolve remaining valid findings from latest review pass - custom-feeds.js: fix asset-upload contract mismatch (field name "file" -> "files", response read from top-level "uploaded_files" not "data.files") - same bug already fixed in this file on a separate branch/PR (#420), which this branch never received since they're independent PRs off main - custom-feeds.js: add aria-label to the two icon-only "remove feed" buttons - custom-feeds.js: move file-input reset into .finally() so a failed upload doesn't leave the input stuck holding the file, blocking retry of the same file - app-shell.js: fix executePluginAction(pluginId, actionId) parameter order/count mismatch vs. its callers' (actionId, index, pluginId) - currently masked by plugins_manager.js's correct version overwriting this one at load time (classic vs. deferred script order), but worth fixing outright since it's an isolated, self-contained reassignment (not inside the Alpine app() object literal) and removes a latent footgun - overview.html: align Alpine-state resolution with settings-search.js's two-tier getAppData() (also check appEl.__x.$data, not just _x_dataStack) Verified already addressed by earlier passes (no change needed): plugin_rotation_order validation, DisplayController log prefixes, togglePlugin returning its promise for install-flow chaining, installedPlugins setter always updating state, mobile-nav aria-label, toggleSection aria-expanded sync, PluginOrderList bounded init retries (both display.html and durations.html), plugin-order-list.js Array.isArray validation, batched getImageData in the LED-dot preview renderer, app.py exception narrowing/ logging, form-submission log redaction. Confirmed dead code, skipped (unreachable - zero template/JS callers, verified via full-repo grep): dotToNested prototype-pollution hardening, generateFieldHtml HTML-injection hardening, and the HTML-entity-unescape block in JSON parsing - all three live only inside app-shell.js's two legacy savePluginConfig implementations (one Alpine-method, one standalone), neither of which any template or script calls. The real, live plugin-config path is server-rendered via GET /partials/plugin-config/<id>. Explicitly NOT reverted: the htmx:afterSwap script-execution listener. An earlier finding batch asked to remove it as "duplicate" htmx behavior; that was tried and reverted this session after live testing on hardware proved it broke every partial whose Alpine x-data depends on an inline <script> in the same partial (confirmed: WiFi tab hard-failed with "wifiSetup is not defined"). Removing it again would reintroduce that regression. --------- Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
1204 lines
85 KiB
HTML
1204 lines
85 KiB
HTML
{# Plugin Configuration Partial - Server-side rendered form #}
|
|
{# This template is loaded via HTMX when a plugin tab is clicked #}
|
|
|
|
{% import 'v3/partials/_macros.html' as ui %}
|
|
|
|
{# ===== MACROS FOR FORM FIELD GENERATION ===== #}
|
|
|
|
{# Render a single form field based on schema type #}
|
|
{% macro render_field(key, prop, value, prefix='', plugin_id='') %}
|
|
{% set full_key = (prefix ~ '.' ~ key) if prefix else key %}
|
|
{% set field_id = (plugin_id ~ '-' ~ full_key)|replace('.', '-')|replace('_', '-') %}
|
|
{% set label = prop.title if prop.title else key|replace('_', ' ')|title %}
|
|
{% set description = prop.description if prop.description else '' %}
|
|
{% set _pt = prop.get('type') %}
|
|
{% set field_type = _pt if (_pt is string) else ((_pt | first) if (_pt and _pt is iterable and _pt is not string) else 'string') %}
|
|
|
|
{# Handle nested objects - check for widget first #}
|
|
{% if field_type == 'object' %}
|
|
{% set obj_widget = prop.get('x-widget') or prop.get('x_widget') %}
|
|
{% if obj_widget == 'schedule-picker' %}
|
|
{# Schedule picker widget - renders enable/mode/times UI #}
|
|
{% set obj_value = value if value is not none else {} %}
|
|
<div class="form-group mb-4" id="setting-{{ field_id }}" data-setting-key="{{ full_key }}">
|
|
<label class="block text-sm font-medium text-gray-700 mb-1">{{ label }}{{ ui.help_tip(description, label) }}</label>
|
|
<div id="{{ field_id }}_container" class="schedule-picker-container mt-1"></div>
|
|
<input type="hidden" id="{{ field_id }}_data" name="{{ full_key }}" value='{{ (obj_value|tojson|safe)|replace("'", "'") }}'>
|
|
</div>
|
|
<script>
|
|
(function() {
|
|
function initWidget() {
|
|
if (!window.LEDMatrixWidgets) { setTimeout(initWidget, 50); return; }
|
|
var widget = window.LEDMatrixWidgets.get('schedule-picker');
|
|
if (!widget) { setTimeout(initWidget, 50); return; }
|
|
var container = document.getElementById('{{ field_id }}_container');
|
|
if (!container) return;
|
|
var value = {{ obj_value|tojson|safe }};
|
|
var config = { 'x-options': {{ (prop.get('x-options') or prop.get('x_options') or {})|tojson|safe }} };
|
|
widget.render(container, config, value, { fieldId: '{{ field_id }}', pluginId: '{{ plugin_id }}' });
|
|
}
|
|
if (document.readyState === 'loading') {
|
|
document.addEventListener('DOMContentLoaded', initWidget);
|
|
} else {
|
|
setTimeout(initWidget, 50);
|
|
}
|
|
})();
|
|
</script>
|
|
{% elif obj_widget == 'time-range' %}
|
|
{# Time range widget - renders start/end time inputs #}
|
|
{% set obj_value = value if value is not none else {} %}
|
|
<div class="form-group mb-4" id="setting-{{ field_id }}" data-setting-key="{{ full_key }}">
|
|
<label class="block text-sm font-medium text-gray-700 mb-1">{{ label }}{{ ui.help_tip(description, label) }}</label>
|
|
<div id="{{ field_id }}_container" class="time-range-container mt-1"></div>
|
|
<input type="hidden" id="{{ field_id }}_data" name="{{ full_key }}" value='{{ (obj_value|tojson|safe)|replace("'", "'") }}'>
|
|
</div>
|
|
<script>
|
|
(function() {
|
|
function initWidget() {
|
|
if (!window.LEDMatrixWidgets) { setTimeout(initWidget, 50); return; }
|
|
var widget = window.LEDMatrixWidgets.get('time-range');
|
|
if (!widget) { setTimeout(initWidget, 50); return; }
|
|
var container = document.getElementById('{{ field_id }}_container');
|
|
if (!container) return;
|
|
var value = {{ obj_value|tojson|safe }};
|
|
var config = { 'x-options': {{ (prop.get('x-options') or prop.get('x_options') or {})|tojson|safe }} };
|
|
widget.render(container, config, value, { fieldId: '{{ field_id }}', pluginId: '{{ plugin_id }}' });
|
|
}
|
|
if (document.readyState === 'loading') {
|
|
document.addEventListener('DOMContentLoaded', initWidget);
|
|
} else {
|
|
setTimeout(initWidget, 50);
|
|
}
|
|
})();
|
|
</script>
|
|
{% elif prop.properties %}
|
|
{{ render_nested_section(key, prop, value, prefix, plugin_id) }}
|
|
{% endif %}
|
|
{% else %}
|
|
<div class="form-group mb-4" id="setting-{{ field_id }}" data-setting-key="{{ full_key }}">
|
|
<label for="{{ field_id }}" class="block text-sm font-medium text-gray-700 mb-1">
|
|
{{ label }}{{ ui.help_tip(description, label) }}
|
|
</label>
|
|
|
|
{# Boolean - check for widget first #}
|
|
{% if field_type == 'boolean' %}
|
|
{% set bool_widget = prop.get('x-widget') or prop.get('x_widget') %}
|
|
{% if bool_widget == 'toggle-switch' %}
|
|
{# Render toggle-switch widget #}
|
|
<div id="{{ field_id }}_container" class="toggle-switch-container"></div>
|
|
<script>
|
|
(function() {
|
|
function initWidget() {
|
|
if (!window.LEDMatrixWidgets) { setTimeout(initWidget, 50); return; }
|
|
var widget = window.LEDMatrixWidgets.get('toggle-switch');
|
|
if (!widget) { setTimeout(initWidget, 50); return; }
|
|
var container = document.getElementById('{{ field_id }}_container');
|
|
if (!container) return;
|
|
var value = {{ value|tojson|safe if value is not none else 'false' }};
|
|
var config = {
|
|
'type': 'boolean',
|
|
'x-options': {{ (prop.get('x-options') or prop.get('x_options') or {})|tojson|safe }}
|
|
};
|
|
widget.render(container, config, value, { fieldId: '{{ field_id }}', name: '{{ full_key }}', pluginId: '{{ plugin_id }}' });
|
|
}
|
|
if (document.readyState === 'loading') {
|
|
document.addEventListener('DOMContentLoaded', initWidget);
|
|
} else {
|
|
setTimeout(initWidget, 50);
|
|
}
|
|
})();
|
|
</script>
|
|
{% else %}
|
|
{# Default checkbox - value="true" ensures checked sends "true" not "on" #}
|
|
<label class="flex items-center cursor-pointer">
|
|
<input type="checkbox"
|
|
id="{{ field_id }}"
|
|
name="{{ full_key }}"
|
|
value="true"
|
|
{% if value %}checked{% endif %}
|
|
class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded">
|
|
<span class="ml-2 text-sm text-gray-600">Enabled</span>
|
|
</label>
|
|
{% endif %}
|
|
|
|
{# Enum dropdown #}
|
|
{% elif prop.enum %}
|
|
<select id="{{ field_id }}"
|
|
name="{{ full_key }}"
|
|
class="form-select w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 bg-white text-black">
|
|
{% for option in prop.enum %}
|
|
<option value="{{ option }}" {% if value == option %}selected{% endif %}>
|
|
{{ option|replace('_', ' ')|title }}
|
|
</option>
|
|
{% endfor %}
|
|
</select>
|
|
|
|
{# Number input - check for widget first #}
|
|
{% elif field_type in ['number', 'integer'] %}
|
|
{% set num_widget = prop.get('x-widget') or prop.get('x_widget') %}
|
|
{% if num_widget in ['slider', 'number-input'] %}
|
|
{# Render slider or number-input widget #}
|
|
<div id="{{ field_id }}_container" class="{{ num_widget }}-container"></div>
|
|
<script>
|
|
(function() {
|
|
function initWidget() {
|
|
if (!window.LEDMatrixWidgets) { setTimeout(initWidget, 50); return; }
|
|
var widget = window.LEDMatrixWidgets.get('{{ num_widget }}');
|
|
if (!widget) { setTimeout(initWidget, 50); return; }
|
|
var container = document.getElementById('{{ field_id }}_container');
|
|
if (!container) return;
|
|
var value = {{ value|tojson if value is not none else (prop.default|tojson if prop.default is defined else 'null') }};
|
|
var config = {
|
|
'type': '{{ field_type }}',
|
|
'minimum': {{ prop.minimum|tojson if prop.minimum is defined else 'null' }},
|
|
'maximum': {{ prop.maximum|tojson if prop.maximum is defined else 'null' }},
|
|
'x-options': {{ (prop.get('x-options') or prop.get('x_options') or {})|tojson|safe }}
|
|
};
|
|
widget.render(container, config, value, { fieldId: '{{ field_id }}', name: '{{ full_key }}', pluginId: '{{ plugin_id }}' });
|
|
}
|
|
if (document.readyState === 'loading') {
|
|
document.addEventListener('DOMContentLoaded', initWidget);
|
|
} else {
|
|
setTimeout(initWidget, 50);
|
|
}
|
|
})();
|
|
</script>
|
|
{% else %}
|
|
{# Default number input #}
|
|
<input type="number"
|
|
id="{{ field_id }}"
|
|
name="{{ full_key }}"
|
|
value="{{ value if value is not none else (prop.default if prop.default is defined else '') }}"
|
|
{% if prop.minimum is defined %}min="{{ prop.minimum }}"{% endif %}
|
|
{% if prop.maximum is defined %}max="{{ prop.maximum }}"{% endif %}
|
|
{% if field_type == 'integer' %}step="1"{% else %}step="any"{% endif %}
|
|
class="form-input w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 bg-white text-black placeholder:text-gray-500">
|
|
{% endif %}
|
|
|
|
{# Array - check for file upload widget first (to avoid breaking static-image plugin), then checkbox-group, then array of objects #}
|
|
{% elif field_type == 'array' %}
|
|
{% set x_widget = prop.get('x-widget') or prop.get('x_widget') %}
|
|
{% if x_widget == 'file-upload' %}
|
|
{# File upload widget for arrays #}
|
|
{% set upload_config = prop.get('x-upload-config') or {} %}
|
|
{% set max_files = upload_config.get('max_files', 10) %}
|
|
{% set allowed_types = upload_config.get('allowed_types', ['image/png', 'image/jpeg', 'image/bmp', 'image/gif']) %}
|
|
{% set max_size_mb = upload_config.get('max_size_mb', 5) %}
|
|
{% set plugin_id_from_config = upload_config.get('plugin_id', plugin_id) %}
|
|
{% set array_value = value if value is not none and value is iterable and value is not string else (prop.default if prop.default is defined and prop.default is iterable and prop.default is not string else []) %}
|
|
|
|
<div id="{{ field_id }}_upload_widget" class="mt-1">
|
|
<!-- File Upload Drop Zone -->
|
|
<div id="{{ field_id }}_drop_zone"
|
|
class="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-blue-400 transition-colors cursor-pointer"
|
|
ondrop="window.handleFileDrop(event, this.dataset.fieldId)"
|
|
ondragover="event.preventDefault()"
|
|
data-field-id="{{ field_id }}"
|
|
data-plugin-id="{{ plugin_id_from_config }}"
|
|
data-upload-endpoint="{{ upload_config.get('endpoint', '/api/v3/plugins/assets/upload') }}"
|
|
data-file-type="{{ upload_config.get('file_type', 'image') }}"
|
|
data-max-files="{{ max_files }}"
|
|
data-max-size-mb="{{ max_size_mb }}"
|
|
data-allowed-types="{{ allowed_types|join(',') }}"
|
|
onclick="document.getElementById('{{ field_id }}_file_input').click()">
|
|
<input type="file"
|
|
id="{{ field_id }}_file_input"
|
|
multiple
|
|
accept="{{ allowed_types|join(',') }}"
|
|
style="display: none;"
|
|
data-field-id="{{ field_id }}"
|
|
data-plugin-id="{{ plugin_id_from_config }}"
|
|
data-upload-endpoint="{{ upload_config.get('endpoint', '/api/v3/plugins/assets/upload') }}"
|
|
data-file-type="{{ upload_config.get('file_type', 'image') }}"
|
|
data-multiple="true"
|
|
data-max-files="{{ max_files }}"
|
|
data-max-size-mb="{{ max_size_mb }}"
|
|
data-allowed-types="{{ allowed_types|join(',') }}"
|
|
onchange="window.handleFileSelect(event, this.dataset.fieldId)">
|
|
<i class="fas fa-cloud-upload-alt text-3xl text-gray-400 mb-2"></i>
|
|
<p class="text-sm text-gray-600">Drag and drop images here or click to browse</p>
|
|
<p class="text-xs text-gray-500 mt-1">Max {{ max_files }} files, {{ max_size_mb }}MB each (PNG, JPG, GIF, BMP)</p>
|
|
</div>
|
|
<p class="text-xs text-amber-600 mt-2 flex items-center">
|
|
<i class="fas fa-info-circle mr-1"></i>
|
|
Remember to save configuration after upload
|
|
</p>
|
|
|
|
<!-- Uploaded Images List -->
|
|
<div id="{{ field_id }}_image_list" class="mt-4 space-y-2">
|
|
{% for img in array_value %}
|
|
{% set img_id = img.get('id', loop.index0) %}
|
|
{% set img_schedule = img.get('schedule', {}) %}
|
|
{% set has_schedule = img_schedule.get('enabled', false) and img_schedule.get('mode') and img_schedule.get('mode') != 'always' %}
|
|
<div id="img_{{ img_id|string|replace('.', '_')|replace('-', '_') }}" class="bg-gray-50 p-3 rounded-lg border border-gray-200">
|
|
<div class="flex items-center justify-between mb-2">
|
|
<div class="flex items-center space-x-3 flex-1">
|
|
<img src="/{{ img.get('path', '') }}"
|
|
alt="{{ img.get('filename', '') }}"
|
|
class="w-16 h-16 object-cover rounded"
|
|
onerror="this.style.display='none'; this.nextElementSibling.style.display='block';">
|
|
<div style="display:none;" class="w-16 h-16 bg-gray-200 rounded flex items-center justify-center">
|
|
<i class="fas fa-image text-gray-400"></i>
|
|
</div>
|
|
<div class="flex-1 min-w-0">
|
|
<p class="text-sm font-medium text-gray-900 truncate">{{ img.get('original_filename') or img.get('filename', 'Image') }}</p>
|
|
<p class="text-xs text-gray-500">
|
|
{% if img.get('size') %}{{ (img.get('size') / 1024)|round }} KB{% endif %}
|
|
{% if img.get('uploaded_at') %} • {{ img.get('uploaded_at') }}{% endif %}
|
|
</p>
|
|
{% if has_schedule %}
|
|
<p class="text-xs text-blue-600 mt-1">
|
|
<i class="fas fa-clock mr-1"></i>Scheduled
|
|
</p>
|
|
{% endif %}
|
|
</div>
|
|
</div>
|
|
<div class="flex items-center space-x-2 ml-4">
|
|
<button type="button"
|
|
data-field-id="{{ field_id }}"
|
|
data-image-id="{{ img_id }}"
|
|
data-image-idx="{{ loop.index0 }}"
|
|
onclick="window.openImageSchedule(this.dataset.fieldId, this.dataset.imageId || null, parseInt(this.dataset.imageIdx))"
|
|
class="text-blue-600 hover:text-blue-800 p-2"
|
|
title="Schedule this image">
|
|
<i class="fas fa-calendar-alt"></i>
|
|
</button>
|
|
<button type="button"
|
|
data-field-id="{{ field_id }}"
|
|
data-image-id="{{ img_id }}"
|
|
data-plugin-id="{{ plugin_id_from_config }}"
|
|
onclick="window.deleteUploadedImage(this.dataset.fieldId, this.dataset.imageId, this.dataset.pluginId)"
|
|
class="text-red-600 hover:text-red-800 p-2"
|
|
title="Delete image">
|
|
<i class="fas fa-trash"></i>
|
|
</button>
|
|
</div>
|
|
</div>
|
|
<div id="schedule_{{ img_id|string|replace('.', '_')|replace('-', '_') }}" class="hidden mt-3 pt-3 border-t border-gray-300"></div>
|
|
</div>
|
|
{% endfor %}
|
|
</div>
|
|
|
|
<!-- Hidden input to store image data -->
|
|
<input type="hidden" id="{{ field_id }}_images_data" name="{{ full_key }}" value='{{ (array_value|tojson|safe)|replace("'", "'") }}'>
|
|
</div>
|
|
{% elif x_widget == 'checkbox-group' %}
|
|
{# Checkbox group widget for multi-select arrays with enum items #}
|
|
{% set array_value = value if value is not none and value is iterable and value is not string else (prop.default if prop.default is defined and prop.default is iterable and prop.default is not string else []) %}
|
|
{% set items_schema = prop.get('items') or {} %}
|
|
{% set enum_items = items_schema.get('enum') or [] %}
|
|
{% set x_options = prop.get('x-options') or {} %}
|
|
{% set labels = x_options.get('labels') or {} %}
|
|
|
|
<div class="mt-1 space-y-2">
|
|
{% for option in enum_items %}
|
|
{% set is_checked = option in array_value %}
|
|
{% set option_label = labels.get(option, option|replace('_', ' ')|title) %}
|
|
{% set checkbox_id = (field_id ~ '_' ~ option)|replace('.', '_')|replace(' ', '_') %}
|
|
<label class="flex items-center cursor-pointer">
|
|
<input type="checkbox"
|
|
id="{{ checkbox_id }}"
|
|
name="{{ full_key }}[]"
|
|
data-checkbox-group="{{ field_id }}"
|
|
data-option-value="{{ option }}"
|
|
value="{{ option }}"
|
|
{% if is_checked %}checked{% endif %}
|
|
onchange="updateCheckboxGroupData('{{ field_id }}')"
|
|
class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded">
|
|
<span class="ml-2 text-sm text-gray-700">{{ option_label }}</span>
|
|
</label>
|
|
{% endfor %}
|
|
</div>
|
|
{# Hidden input to store selected values as JSON array (like array-of-objects pattern) #}
|
|
<input type="hidden" id="{{ field_id }}_data" name="{{ full_key }}_data" value='{{ (array_value|tojson|safe)|replace("'", "'") }}'>
|
|
{# Sentinel hidden input with bracket notation to allow clearing array to [] when all unchecked #}
|
|
{# This ensures the field is always submitted, even when all checkboxes are unchecked #}
|
|
<input type="hidden" name="{{ full_key }}[]" value="">
|
|
{% elif x_widget == 'google-calendar-picker' %}
|
|
{# Google Calendar picker — dynamically loads calendars from the API #}
|
|
{# Normalise: if value is a string (legacy comma-separated), split it; otherwise fall back to default or [] #}
|
|
{% if value is not none and value is string and value %}
|
|
{% set array_value = value.split(',') | map('trim') | list %}
|
|
{% elif value is not none and value is iterable and value is not string %}
|
|
{% set array_value = value %}
|
|
{% elif prop.default is defined and prop.default is string and prop.default %}
|
|
{% set array_value = prop.default.split(',') | map('trim') | list %}
|
|
{% elif prop.default is defined and prop.default is iterable and prop.default is not string %}
|
|
{% set array_value = prop.default %}
|
|
{% else %}
|
|
{% set array_value = [] %}
|
|
{% endif %}
|
|
<div id="{{ field_id }}_container" class="google-calendar-picker-container mt-1"></div>
|
|
<script>
|
|
(function() {
|
|
var MAX_RETRIES = 40;
|
|
var retries = 0;
|
|
function initWidget() {
|
|
if (retries >= MAX_RETRIES) { return; }
|
|
retries++;
|
|
if (!window.LEDMatrixWidgets) { setTimeout(initWidget, 50); return; }
|
|
var widget = window.LEDMatrixWidgets.get('google-calendar-picker');
|
|
if (!widget) { setTimeout(initWidget, 50); return; }
|
|
var container = document.getElementById('{{ field_id }}_container');
|
|
if (!container) return;
|
|
var value = {{ array_value|tojson|safe }};
|
|
widget.render(container, {}, value, { fieldId: '{{ field_id }}', pluginId: '{{ plugin_id }}', name: '{{ full_key }}' });
|
|
}
|
|
if (document.readyState === 'loading') {
|
|
document.addEventListener('DOMContentLoaded', initWidget);
|
|
} else {
|
|
setTimeout(initWidget, 50);
|
|
}
|
|
})();
|
|
</script>
|
|
{% elif x_widget == 'day-selector' %}
|
|
{# Day selector widget for selecting days of the week #}
|
|
{% set array_value = value if value is not none and value is iterable and value is not string else (prop.default if prop.default is defined and prop.default is iterable and prop.default is not string else []) %}
|
|
<div id="{{ field_id }}_container" class="day-selector-container mt-1"></div>
|
|
<script>
|
|
(function() {
|
|
function initWidget() {
|
|
if (!window.LEDMatrixWidgets) { setTimeout(initWidget, 50); return; }
|
|
var widget = window.LEDMatrixWidgets.get('day-selector');
|
|
if (!widget) { setTimeout(initWidget, 50); return; }
|
|
var container = document.getElementById('{{ field_id }}_container');
|
|
if (!container) return;
|
|
var value = {{ array_value|tojson|safe }};
|
|
var config = { 'x-options': {{ (prop.get('x-options') or prop.get('x_options') or {})|tojson|safe }} };
|
|
widget.render(container, config, value, { fieldId: '{{ field_id }}', pluginId: '{{ plugin_id }}', name: '{{ full_key }}' });
|
|
}
|
|
if (document.readyState === 'loading') {
|
|
document.addEventListener('DOMContentLoaded', initWidget);
|
|
} else {
|
|
setTimeout(initWidget, 50);
|
|
}
|
|
})();
|
|
</script>
|
|
{% else %}
|
|
{# Check for custom-feeds widget first #}
|
|
{% set items_schema = prop.get('items') or {} %}
|
|
{% if x_widget == 'custom-feeds' %}
|
|
{# Custom feeds table interface - widget-specific implementation #}
|
|
{# Validate that required fields exist in schema #}
|
|
{% set item_properties = items_schema.get('properties', {}) %}
|
|
{% if not (item_properties.get('name') and item_properties.get('url')) %}
|
|
{# Fallback to generic if schema doesn't match expected structure #}
|
|
<p class="text-xs text-amber-600 mt-1">
|
|
<i class="fas fa-exclamation-triangle mr-1"></i>
|
|
Custom feeds widget requires 'name' and 'url' properties in items schema.
|
|
</p>
|
|
{% else %}
|
|
{% set max_items = prop.get('maxItems', 50) %}
|
|
{% set array_value = value if value is not none and value is iterable and value is not string else (prop.default if prop.default is defined and prop.default is iterable and prop.default is not string else []) %}
|
|
|
|
<div class="custom-feeds-table-container mt-1">
|
|
<table class="min-w-full divide-y divide-gray-200 border border-gray-300 rounded-lg">
|
|
<thead class="bg-gray-50">
|
|
<tr>
|
|
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Name</th>
|
|
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">URL</th>
|
|
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Logo</th>
|
|
<th class="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Enabled</th>
|
|
<th class="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody id="{{ field_id }}_tbody" class="bg-white divide-y divide-gray-200">
|
|
{% for item in array_value %}
|
|
{% set item_index = loop.index0 %}
|
|
<tr class="custom-feed-row" data-index="{{ item_index }}">
|
|
<td class="px-4 py-3 whitespace-nowrap">
|
|
<input type="text"
|
|
name="{{ full_key }}.{{ item_index }}.name"
|
|
value="{{ item.get('name', '') }}"
|
|
class="block w-full px-2 py-1 border border-gray-300 rounded text-sm"
|
|
placeholder="Feed Name"
|
|
required>
|
|
</td>
|
|
<td class="px-4 py-3 whitespace-nowrap">
|
|
<input type="url"
|
|
name="{{ full_key }}.{{ item_index }}.url"
|
|
value="{{ item.get('url', '') }}"
|
|
class="block w-full px-2 py-1 border border-gray-300 rounded text-sm"
|
|
placeholder="https://example.com/feed"
|
|
required>
|
|
</td>
|
|
<td class="px-4 py-3 whitespace-nowrap">
|
|
{% set logo_value = item.get('logo') or {} %}
|
|
{% set logo_path = logo_value.get('path', '') %}
|
|
<div class="flex items-center space-x-2">
|
|
<input type="file"
|
|
id="{{ field_id }}_logo_{{ item_index }}"
|
|
accept="image/png,image/jpeg,image/bmp,image/gif"
|
|
style="display: none;"
|
|
onchange="handleCustomFeedLogoUpload(event, '{{ field_id }}', {{ item_index }}, '{{ plugin_id }}', '{{ full_key }}')">
|
|
<button type="button"
|
|
onclick="document.getElementById('{{ field_id }}_logo_{{ item_index }}').click()"
|
|
class="px-2 py-1 text-xs bg-gray-200 hover:bg-gray-300 rounded">
|
|
<i class="fas fa-upload mr-1"></i> Upload
|
|
</button>
|
|
{% if logo_path %}
|
|
<img src="/{{ logo_path }}" alt="Logo" class="w-8 h-8 object-cover rounded border" id="{{ field_id }}_logo_preview_{{ item_index }}">
|
|
<input type="hidden" name="{{ full_key }}.{{ item_index }}.logo.path" value="{{ logo_path }}">
|
|
<input type="hidden" name="{{ full_key }}.{{ item_index }}.logo.id" value="{{ logo_value.get('id', '') }}">
|
|
{% else %}
|
|
<span class="text-xs text-gray-400">No logo</span>
|
|
{% endif %}
|
|
</div>
|
|
</td>
|
|
<td class="px-4 py-3 whitespace-nowrap text-center">
|
|
<input type="hidden" name="{{ full_key }}.{{ item_index }}.enabled" value="{{ 'true' if item.get('enabled', true) else 'false' }}">
|
|
<input type="checkbox"
|
|
name="{{ full_key }}.{{ item_index }}.enabled"
|
|
{% if item.get('enabled', true) %}checked{% endif %}
|
|
value="true"
|
|
onchange="this.previousElementSibling.value = this.checked ? 'true' : 'false'"
|
|
class="h-4 w-4 text-blue-600">
|
|
</td>
|
|
<td class="px-4 py-3 whitespace-nowrap text-center">
|
|
<button type="button"
|
|
onclick="removeCustomFeedRow(this)"
|
|
class="text-red-600 hover:text-red-800 px-2 py-1">
|
|
<i class="fas fa-trash"></i>
|
|
</button>
|
|
</td>
|
|
</tr>
|
|
{% endfor %}
|
|
</tbody>
|
|
</table>
|
|
<button type="button"
|
|
onclick="addCustomFeedRow('{{ field_id }}', '{{ full_key }}', {{ max_items }}, '{{ plugin_id }}')"
|
|
class="mt-3 px-4 py-2 text-sm bg-blue-600 hover:bg-blue-700 text-white rounded-md"
|
|
{% if array_value|length >= max_items %}disabled style="opacity: 0.5;"{% endif %}>
|
|
<i class="fas fa-plus mr-1"></i> Add Feed
|
|
</button>
|
|
</div>
|
|
{% endif %}
|
|
{% elif x_widget == 'array-table' %}
|
|
{# Generic array-of-objects table widget - reads columns from schema #}
|
|
{% set item_properties = items_schema.get('properties', {}) %}
|
|
{% set max_items = prop.get('maxItems', 50) %}
|
|
{% set array_value = value if value is not none and value is iterable and value is not string else (prop.default if prop.default is defined and prop.default is iterable and prop.default is not string else []) %}
|
|
|
|
{# Use x-columns if specified, otherwise auto-detect first 4 simple properties #}
|
|
{% set x_columns = prop.get('x-columns') %}
|
|
{% if x_columns %}
|
|
{% set display_columns = x_columns %}
|
|
{% else %}
|
|
{% set display_columns = [] %}
|
|
{% for col_name in item_properties.keys() %}
|
|
{% set col_def = item_properties[col_name] %}
|
|
{% if col_def.get('type') not in ['object', 'array'] and display_columns|length < 4 %}
|
|
{% set _ = display_columns.append(col_name) %}
|
|
{% endif %}
|
|
{% endfor %}
|
|
{% endif %}
|
|
|
|
<div class="array-table-container mt-1" data-field-id="{{ field_id }}" data-full-key="{{ full_key }}" data-max-items="{{ max_items }}" data-plugin-id="{{ plugin_id }}">
|
|
<div style="overflow-x:auto">
|
|
<table class="divide-y divide-gray-200 border border-gray-300 rounded-lg" style="min-width:max-content;width:100%">
|
|
<thead class="bg-gray-50">
|
|
<tr>
|
|
{% for col_name in display_columns %}
|
|
{% set col_def = item_properties.get(col_name, {}) %}
|
|
{% set col_title = col_def.get('title', col_name|replace('_', ' ')|title) %}
|
|
{% set col_xwidget = col_def.get('x-widget') or col_def.get('x_widget', '') %}
|
|
{% set col_enum = col_def.get('enum', []) %}
|
|
{% set _raw_ctype = col_def.get('type', 'string') %}
|
|
{% if _raw_ctype is iterable and _raw_ctype is not string %}
|
|
{% set col_ctype = (_raw_ctype | reject('equalto','null') | list | first) or 'string' %}
|
|
{% else %}
|
|
{% set col_ctype = _raw_ctype or 'string' %}
|
|
{% endif %}
|
|
{% if col_xwidget == 'date-picker' %}{% set col_min_w = '140px' %}
|
|
{% elif col_xwidget == 'time-picker' %}{% set col_min_w = '115px' %}
|
|
{% elif col_xwidget == 'file-upload-single' %}{% set col_min_w = '200px' %}
|
|
{% elif col_enum %}{% set col_min_w = '90px' %}
|
|
{% elif col_ctype == 'boolean' %}{% set col_min_w = '60px' %}
|
|
{% elif col_ctype in ['integer', 'number'] %}{% set col_min_w = '80px' %}
|
|
{% else %}{% set col_min_w = '110px' %}{% endif %}
|
|
<th class="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider" style="min-width:{{ col_min_w }}">{{ col_title }}</th>
|
|
{% endfor %}
|
|
<th class="px-3 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider" style="min-width:90px">Actions</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody id="{{ field_id }}_tbody" class="bg-white divide-y divide-gray-200">
|
|
{% for item in array_value %}
|
|
{% set item_index = loop.index0 %}
|
|
<tr class="array-table-row" data-index="{{ item_index }}">
|
|
{% for col_name in display_columns %}
|
|
{% set col_def = item_properties.get(col_name, {}) %}
|
|
{# Normalize nullable types e.g. ["null","integer"] → "integer" #}
|
|
{% set _raw_type = col_def.get('type', 'string') %}
|
|
{% if _raw_type is iterable and _raw_type is not string %}
|
|
{% set col_type = (_raw_type | reject('equalto','null') | list | first) or 'string' %}
|
|
{% else %}
|
|
{% set col_type = _raw_type or 'string' %}
|
|
{% endif %}
|
|
{% set col_xwidget = col_def.get('x-widget') or col_def.get('x_widget', '') %}
|
|
{% set col_enum = col_def.get('enum', []) %}
|
|
{% set col_value = item.get(col_name, col_def.get('default', '')) %}
|
|
{% if col_xwidget == 'date-picker' %}{% set td_min_w = '140px' %}
|
|
{% elif col_xwidget == 'time-picker' %}{% set td_min_w = '115px' %}
|
|
{% elif col_xwidget == 'file-upload-single' %}{% set td_min_w = '200px' %}
|
|
{% elif col_enum %}{% set td_min_w = '90px' %}
|
|
{% elif col_type == 'boolean' %}{% set td_min_w = '60px' %}
|
|
{% elif col_type in ['integer', 'number'] %}{% set td_min_w = '80px' %}
|
|
{% else %}{% set td_min_w = '110px' %}{% endif %}
|
|
<td class="px-3 py-3 whitespace-nowrap" style="min-width:{{ td_min_w }};vertical-align:middle">
|
|
{% if col_type == 'boolean' %}
|
|
{# Hidden sentinel ensures unchecked boxes still submit "false" (browsers
|
|
omit unchecked checkboxes entirely). It shares the checkbox's `name`,
|
|
so it must always mirror the checkbox's actual state — both here at
|
|
render time and on every toggle — or whichever of the two same-named
|
|
inputs the save request happens to prefer can silently revert this
|
|
field to false regardless of what's checked. #}
|
|
<input type="hidden" name="{{ full_key }}.{{ item_index }}.{{ col_name }}" value="{{ 'true' if col_value else 'false' }}">
|
|
<input type="checkbox"
|
|
name="{{ full_key }}.{{ item_index }}.{{ col_name }}"
|
|
{% if col_value %}checked{% endif %}
|
|
value="true"
|
|
onchange="this.previousElementSibling.value = this.checked ? 'true' : 'false'"
|
|
class="h-4 w-4 text-blue-600">
|
|
{% elif col_type == 'integer' or col_type == 'number' %}
|
|
<input type="number"
|
|
name="{{ full_key }}.{{ item_index }}.{{ col_name }}"
|
|
value="{{ col_value if col_value is not none else '' }}"
|
|
{% if col_def.get('minimum') is not none %}min="{{ col_def.get('minimum') }}"{% endif %}
|
|
{% if col_def.get('maximum') is not none %}max="{{ col_def.get('maximum') }}"{% endif %}
|
|
{% if col_type == 'integer' %}step="1"{% else %}step="any"{% endif %}
|
|
class="block w-20 px-2 py-1 border border-gray-300 rounded text-sm text-center"
|
|
{% if col_def.get('description') %}title="{{ col_def.get('description') }}"{% endif %}>
|
|
{% elif col_enum %}
|
|
<select name="{{ full_key }}.{{ item_index }}.{{ col_name }}"
|
|
class="block w-full px-2 py-1 border border-gray-300 rounded text-sm bg-white">
|
|
{% for opt in col_enum %}{% if opt is not none %}
|
|
<option value="{{ opt }}" {% if col_value == opt or (col_value is none and col_def.get('default') == opt) %}selected{% endif %}>{{ opt }}</option>
|
|
{% endif %}{% endfor %}
|
|
</select>
|
|
{% elif col_xwidget == 'date-picker' %}
|
|
<input type="date"
|
|
name="{{ full_key }}.{{ item_index }}.{{ col_name }}"
|
|
value="{{ col_value if col_value is not none else '' }}"
|
|
class="block w-full px-2 py-1 border border-gray-300 rounded text-sm">
|
|
{% elif col_xwidget == 'time-picker' %}
|
|
<input type="time"
|
|
name="{{ full_key }}.{{ item_index }}.{{ col_name }}"
|
|
value="{{ col_value if col_value is not none else '00:00' }}"
|
|
class="block w-full px-2 py-1 border border-gray-300 rounded text-sm">
|
|
{% elif col_xwidget == 'file-upload-single' %}
|
|
{% set cell_input_id = field_id ~ '_' ~ item_index ~ '_' ~ col_name %}
|
|
<div class="flex items-center gap-1">
|
|
{% if col_value %}<img src="/{{ col_value }}" class="w-6 h-6 object-cover rounded flex-shrink-0" onerror="this.style.display='none'">{% endif %}
|
|
<input type="text"
|
|
id="{{ cell_input_id }}"
|
|
name="{{ full_key }}.{{ item_index }}.{{ col_name }}"
|
|
value="{{ col_value if col_value is not none else '' }}"
|
|
class="block w-20 px-1 py-1 border border-gray-300 rounded text-xs"
|
|
placeholder="path…">
|
|
<label class="cursor-pointer flex-shrink-0 inline-flex items-center px-1 py-1 bg-blue-50 border border-blue-200 rounded text-xs text-blue-600 hover:bg-blue-100" title="Upload image">
|
|
<i class="fas fa-upload"></i>
|
|
<input type="file"
|
|
accept="image/png,image/jpeg,image/bmp,image/gif"
|
|
style="display:none"
|
|
data-plugin-id="{{ plugin_id }}"
|
|
data-target-input="{{ cell_input_id }}"
|
|
onchange="(function(e){ const t=document.getElementById('{{ cell_input_id }}'); const p=t.previousElementSibling && t.previousElementSibling.tagName==='IMG' ? t.previousElementSibling : null; window.handleArrayTableImageUpload(e,t,p,'{{ plugin_id }}'); })(event)">
|
|
</label>
|
|
</div>
|
|
{% else %}
|
|
<input type="text"
|
|
name="{{ full_key }}.{{ item_index }}.{{ col_name }}"
|
|
value="{{ col_value if col_value is not none else '' }}"
|
|
class="block w-full px-2 py-1 border border-gray-300 rounded text-sm"
|
|
{% if col_def.get('description') %}placeholder="{{ col_def.get('description') }}"{% endif %}
|
|
{% if col_def.get('pattern') %}pattern="{{ col_def.get('pattern') }}"{% endif %}
|
|
{% if col_def.get('minLength') %}minlength="{{ col_def.get('minLength') }}"{% endif %}
|
|
{% if col_def.get('maxLength') %}maxlength="{{ col_def.get('maxLength') }}"{% endif %}>
|
|
{% endif %}
|
|
</td>
|
|
{% endfor %}
|
|
|
|
{# Actions cell: delete + optional edit button for advanced props #}
|
|
{% set has_advanced = namespace(value=false) %}
|
|
{% for k in item_properties.keys() %}{% if k not in display_columns and k != 'id' %}{% set has_advanced.value = true %}{% endif %}{% endfor %}
|
|
<td class="px-3 py-3 whitespace-nowrap text-center" style="min-width:90px;vertical-align:middle">
|
|
<button type="button"
|
|
onclick="removeArrayTableRow(this)"
|
|
class="text-red-600 hover:text-red-800 px-2 py-1">
|
|
<i class="fas fa-trash"></i>
|
|
</button>
|
|
{% if has_advanced.value %}
|
|
<button type="button"
|
|
onclick="openArrayTableRowEditor(this)"
|
|
class="text-blue-500 hover:text-blue-700 px-2 py-1 ml-1"
|
|
title="Edit layout, style and other advanced properties">
|
|
<i class="fas fa-sliders-h"></i>
|
|
</button>
|
|
{% endif %}
|
|
</td>
|
|
|
|
{# Hidden cell: flat hidden inputs for non-displayed props (layout, style, etc.) #}
|
|
{% if has_advanced.value %}
|
|
{% set adv_schema = namespace(d={}) %}
|
|
{% for k, v in item_properties.items() %}{% if k not in display_columns and k != 'id' %}{% set _ = adv_schema.d.update({k: v}) %}{% endif %}{% endfor %}
|
|
<td style="display:none" class="array-table-advanced-data"
|
|
data-prop-schema='{{ adv_schema.d|tojson }}'>
|
|
{% for prop_name, prop_schema in adv_schema.d.items() %}
|
|
{% set prop_type = prop_schema.get('type', 'string') %}
|
|
{% if prop_type == 'object' and prop_schema.get('properties') %}
|
|
{% for sub_name, sub_schema in prop_schema.get('properties', {}).items() %}
|
|
{% set sub_val = item.get(prop_name, {}).get(sub_name) %}
|
|
{% set sub_default = sub_schema.get('default') %}
|
|
{% set final_val = sub_val if sub_val is not none else sub_default %}
|
|
<input type="hidden"
|
|
name="{{ full_key }}.{{ item_index }}.{{ prop_name }}.{{ sub_name }}"
|
|
data-nested-prop="{{ prop_name }}.{{ sub_name }}"
|
|
data-prop-type="{{ sub_schema.get('type', 'string') }}"
|
|
data-prop-schema='{{ sub_schema|tojson }}'
|
|
value="{{ final_val if final_val is not none else '' }}">
|
|
{% endfor %}
|
|
{% else %}
|
|
{% set prop_val = item.get(prop_name) %}
|
|
{% set prop_default = prop_schema.get('default') %}
|
|
{% set final_val = prop_val if prop_val is not none else prop_default %}
|
|
<input type="hidden"
|
|
name="{{ full_key }}.{{ item_index }}.{{ prop_name }}"
|
|
data-nested-prop="{{ prop_name }}"
|
|
data-prop-type="{{ prop_schema.get('type', 'string') }}"
|
|
data-prop-schema='{{ prop_schema|tojson }}'
|
|
value="{{ final_val if final_val is not none else '' }}">
|
|
{% endif %}
|
|
{% endfor %}
|
|
</td>
|
|
{% endif %}
|
|
</tr>
|
|
{% endfor %}
|
|
</tbody>
|
|
</table>
|
|
<button type="button"
|
|
onclick="addArrayTableRow(this)"
|
|
data-field-id="{{ field_id }}"
|
|
data-full-key="{{ full_key }}"
|
|
data-max-items="{{ max_items }}"
|
|
data-plugin-id="{{ plugin_id }}"
|
|
data-item-properties='{% set ns = namespace(d={}) %}{% for k in display_columns %}{% if k in item_properties %}{% set _ = ns.d.update({k: item_properties[k]}) %}{% endif %}{% endfor %}{{ ns.d|tojson }}'
|
|
data-full-item-properties='{{ item_properties|tojson }}'
|
|
data-display-columns='{{ display_columns|tojson }}'
|
|
class="mt-3 px-4 py-2 text-sm bg-blue-600 hover:bg-blue-700 text-white rounded-md"
|
|
{% if array_value|length >= max_items %}disabled style="opacity: 0.5;"{% endif %}>
|
|
<i class="fas fa-plus mr-1"></i> Add Item
|
|
</button>
|
|
</div>{# end overflow-x:auto wrapper #}
|
|
</div>
|
|
{% elif x_widget == 'color-picker' %}
|
|
{# RGB color array: R / G / B number inputs + visual swatch + sync'd hex picker #}
|
|
{% set color_arr = value if value is not none and value is iterable and value is not string else (prop.default if prop.default is defined and prop.default is iterable and prop.default is not string else [255, 255, 255]) %}
|
|
{% set r_val = color_arr[0] if color_arr|length > 0 else 255 %}
|
|
{% set g_val = color_arr[1] if color_arr|length > 1 else 255 %}
|
|
{% set b_val = color_arr[2] if color_arr|length > 2 else 255 %}
|
|
{% set hex_val = '#%02x%02x%02x' % (r_val|int, g_val|int, b_val|int) %}
|
|
<div class="flex items-center gap-3 flex-wrap mt-1" id="{{ field_id }}_color_row">
|
|
<input type="color"
|
|
id="{{ field_id }}_hex"
|
|
value="{{ hex_val }}"
|
|
class="h-9 w-12 cursor-pointer rounded border border-gray-300"
|
|
title="Color picker"
|
|
oninput="(function(h){var r=parseInt(h.slice(1,3),16),g=parseInt(h.slice(3,5),16),b=parseInt(h.slice(5,7),16);document.getElementById('{{ field_id }}_r').value=r;document.getElementById('{{ field_id }}_g').value=g;document.getElementById('{{ field_id }}_b').value=b;})(this.value)">
|
|
<div class="flex items-center gap-1">
|
|
<label class="text-xs text-gray-500 font-medium">R</label>
|
|
<input type="number" min="0" max="255" step="1"
|
|
id="{{ field_id }}_r"
|
|
name="{{ full_key }}.0"
|
|
value="{{ r_val }}"
|
|
class="w-16 px-2 py-1 border border-gray-300 rounded text-sm text-center"
|
|
oninput="(function(){var r=+document.getElementById('{{ field_id }}_r').value||0,g=+document.getElementById('{{ field_id }}_g').value||0,b=+document.getElementById('{{ field_id }}_b').value||0;document.getElementById('{{ field_id }}_hex').value='#'+[r,g,b].map(function(n){return n.toString(16).padStart(2,'0')}).join('')})()">
|
|
</div>
|
|
<div class="flex items-center gap-1">
|
|
<label class="text-xs text-gray-500 font-medium">G</label>
|
|
<input type="number" min="0" max="255" step="1"
|
|
id="{{ field_id }}_g"
|
|
name="{{ full_key }}.1"
|
|
value="{{ g_val }}"
|
|
class="w-16 px-2 py-1 border border-gray-300 rounded text-sm text-center"
|
|
oninput="(function(){var r=+document.getElementById('{{ field_id }}_r').value||0,g=+document.getElementById('{{ field_id }}_g').value||0,b=+document.getElementById('{{ field_id }}_b').value||0;document.getElementById('{{ field_id }}_hex').value='#'+[r,g,b].map(function(n){return n.toString(16).padStart(2,'0')}).join('')})()">
|
|
</div>
|
|
<div class="flex items-center gap-1">
|
|
<label class="text-xs text-gray-500 font-medium">B</label>
|
|
<input type="number" min="0" max="255" step="1"
|
|
id="{{ field_id }}_b"
|
|
name="{{ full_key }}.2"
|
|
value="{{ b_val }}"
|
|
class="w-16 px-2 py-1 border border-gray-300 rounded text-sm text-center"
|
|
oninput="(function(){var r=+document.getElementById('{{ field_id }}_r').value||0,g=+document.getElementById('{{ field_id }}_g').value||0,b=+document.getElementById('{{ field_id }}_b').value||0;document.getElementById('{{ field_id }}_hex').value='#'+[r,g,b].map(function(n){return n.toString(16).padStart(2,'0')}).join('')})()">
|
|
</div>
|
|
<div class="w-8 h-8 rounded border border-gray-300 flex-shrink-0"
|
|
style="background-color: rgb({{ r_val }}, {{ g_val }}, {{ b_val }})"
|
|
title="Color preview"></div>
|
|
</div>
|
|
{% else %}
|
|
{# Generic array-of-objects would go here if needed in the future #}
|
|
{# For now, fall back to regular array input (comma-separated) #}
|
|
{# Regular array input (comma-separated) #}
|
|
{% set array_value = value if value is not none else (prop.default if prop.default is defined else []) %}
|
|
<input type="text"
|
|
id="{{ field_id }}"
|
|
name="{{ full_key }}"
|
|
value="{{ array_value|join(', ') if array_value is iterable and array_value is not string else '' }}"
|
|
placeholder="Enter values separated by commas"
|
|
class="form-input w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 bg-white text-black placeholder:text-gray-500">
|
|
<p class="text-xs text-gray-400 mt-1">Separate multiple values with commas</p>
|
|
{% endif %}
|
|
{% endif %}
|
|
|
|
{# String/default field - check for widgets #}
|
|
{% else %}
|
|
{% set str_widget = prop.get('x-widget') or prop.get('x_widget') %}
|
|
{% set str_value = value if value is not none else (prop.default if prop.default is defined else '') %}
|
|
{% if str_widget == 'file-upload' %}
|
|
{# Single-file upload widget for string fields (e.g., credentials.json) #}
|
|
{% set upload_config = prop.get('x-upload-config') or {} %}
|
|
{% set upload_endpoint = upload_config.get('upload_endpoint', '') %}
|
|
{% set target_filename = upload_config.get('target_filename', 'file.json') %}
|
|
{% set max_size_mb = upload_config.get('max_size_mb', 1) %}
|
|
{% set allowed_extensions = upload_config.get('allowed_extensions', ['.json']) %}
|
|
<div id="{{ field_id }}_upload_widget" class="mt-1">
|
|
<div id="{{ field_id }}_drop_zone"
|
|
class="border-2 border-dashed border-gray-300 rounded-lg p-4 text-center hover:border-blue-400 transition-colors cursor-pointer"
|
|
role="button"
|
|
tabindex="0"
|
|
aria-label="Upload {{ target_filename }}"
|
|
ondrop="window.handleFileDrop(event, this.dataset.fieldId)"
|
|
ondragover="event.preventDefault()"
|
|
data-field-id="{{ field_id }}"
|
|
onclick="document.getElementById('{{ field_id }}_file_input').click()"
|
|
onkeydown="if(event.key==='Enter'||event.key===' '){event.preventDefault();document.getElementById('{{ field_id }}_file_input').click();}">
|
|
<input type="file"
|
|
id="{{ field_id }}_file_input"
|
|
accept="{{ allowed_extensions|join(',') }}"
|
|
style="display: none;"
|
|
data-field-id="{{ field_id }}"
|
|
data-upload-endpoint="{{ upload_endpoint }}"
|
|
data-target-filename="{{ target_filename }}"
|
|
data-max-size-mb="{{ max_size_mb }}"
|
|
data-allowed-extensions="{{ allowed_extensions|join(',') }}"
|
|
onchange="window.handleSingleFileSelect(event, this.dataset.fieldId)">
|
|
<i class="fas fa-cloud-upload-alt text-2xl text-gray-400 mb-1"></i>
|
|
<p class="text-sm text-gray-600">Click to upload {{ target_filename }}</p>
|
|
<p class="text-xs text-gray-500 mt-1">Max {{ max_size_mb }}MB ({{ allowed_extensions|join(', ') }})</p>
|
|
</div>
|
|
<div id="{{ field_id }}_upload_status" class="mt-2 text-xs text-gray-500" aria-live="polite"></div>
|
|
<input type="hidden"
|
|
id="{{ field_id }}"
|
|
name="{{ full_key }}"
|
|
value="{{ str_value }}">
|
|
</div>
|
|
{% elif str_widget == 'json-file-manager' %}
|
|
{# Embedded file manager — plugin's web_ui/file_manager.html served via /v3/plugin-ui/ route #}
|
|
<div class="mt-1 rounded-lg border border-gray-200 overflow-hidden">
|
|
<iframe id="{{ field_id }}_frame"
|
|
src="/v3/plugin-ui/{{ plugin_id }}/web-ui/file_manager.html"
|
|
style="width:100%;height:640px;border:none;"
|
|
title="File Manager for {{ plugin_id }}"></iframe>
|
|
</div>
|
|
<p class="text-xs text-amber-600 mt-2 flex items-center">
|
|
<i class="fas fa-info-circle mr-1"></i>
|
|
Changes in the file manager save immediately — no need to click Save Configuration.
|
|
</p>
|
|
{% elif str_widget in ['text-input', 'textarea', 'select-dropdown', 'toggle-switch', 'radio-group', 'date-picker', 'time-picker', 'slider', 'color-picker', 'email-input', 'url-input', 'password-input', 'font-selector', 'file-upload-single', 'plugin-file-manager'] %}
|
|
{# Render widget container #}
|
|
<div id="{{ field_id }}_container" class="{{ str_widget }}-container"></div>
|
|
<script>
|
|
(function() {
|
|
function initWidget() {
|
|
if (!window.LEDMatrixWidgets) { setTimeout(initWidget, 50); return; }
|
|
var widget = window.LEDMatrixWidgets.get('{{ str_widget }}');
|
|
if (!widget) { setTimeout(initWidget, 50); return; }
|
|
var container = document.getElementById('{{ field_id }}_container');
|
|
if (!container) return;
|
|
var value = {{ str_value|tojson|safe }};
|
|
var config = {
|
|
'type': '{{ field_type }}',
|
|
'enum': {{ (prop.enum or [])|tojson|safe }},
|
|
'minimum': {{ prop.minimum|tojson if prop.minimum is defined else 'null' }},
|
|
'maximum': {{ prop.maximum|tojson if prop.maximum is defined else 'null' }},
|
|
'x-options': {{ (prop.get('x-options') or prop.get('x_options') or {})|tojson|safe }},
|
|
'x-upload-config': {{ (prop.get('x-upload-config') or prop.get('x_upload_config') or {})|tojson|safe }},
|
|
'x-widget-config': {{ (prop.get('x-widget-config') or prop.get('x_widget_config') or {})|tojson|safe }}
|
|
};
|
|
widget.render(container, config, value, { fieldId: '{{ field_id }}', name: '{{ full_key }}', pluginId: '{{ plugin_id }}' });
|
|
}
|
|
if (document.readyState === 'loading') {
|
|
document.addEventListener('DOMContentLoaded', initWidget);
|
|
} else {
|
|
setTimeout(initWidget, 50);
|
|
}
|
|
})();
|
|
</script>
|
|
{% else %}
|
|
{# Default text input #}
|
|
<input type="text"
|
|
id="{{ field_id }}"
|
|
name="{{ full_key }}"
|
|
value="{{ str_value }}"
|
|
class="form-input w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 bg-white text-black placeholder:text-gray-500">
|
|
{% endif %}
|
|
{% endif %}
|
|
</div>
|
|
{% endif %}
|
|
{% endmacro %}
|
|
|
|
{# Render a nested/collapsible section for object types #}
|
|
{% macro render_nested_section(key, prop, value, prefix='', plugin_id='') %}
|
|
{% set full_key = (prefix ~ '.' ~ key) if prefix else key %}
|
|
{% set section_id = (plugin_id ~ '-section-' ~ full_key)|replace('.', '-')|replace('_', '-') %}
|
|
{% set label = prop.title if prop.title else key|replace('_', ' ')|title %}
|
|
{% set description = prop.description if prop.description else '' %}
|
|
{% set nested_value = value if value else {} %}
|
|
|
|
<div class="nested-section border border-gray-300 rounded-lg mb-4">
|
|
<button type="button"
|
|
class="w-full bg-gray-100 hover:bg-gray-200 px-4 py-3 flex items-center justify-between text-left transition-colors rounded-t-lg"
|
|
onclick="toggleSection('{{ section_id }}')">
|
|
<div class="flex-1">
|
|
<h4 class="font-semibold text-gray-900">{{ label }}</h4>
|
|
{% if description %}
|
|
<p class="text-sm text-gray-600 mt-1">{{ description }}</p>
|
|
{% endif %}
|
|
</div>
|
|
<i id="{{ section_id }}-icon" class="fas fa-chevron-right text-gray-500 transition-transform"></i>
|
|
</button>
|
|
<div id="{{ section_id }}" class="nested-content bg-gray-50 px-4 py-4 space-y-3 hidden" style="display: none;">
|
|
{% set property_order = prop['x-propertyOrder'] if 'x-propertyOrder' in prop else prop.properties.keys()|list %}
|
|
{% for nested_key in property_order %}
|
|
{% if nested_key in prop.properties %}
|
|
{% set nested_prop = prop.properties[nested_key] %}
|
|
{% set nested_val = nested_value[nested_key] if nested_key in nested_value else none %}
|
|
{{ render_field(nested_key, nested_prop, nested_val, full_key, plugin_id) }}
|
|
{% endif %}
|
|
{% endfor %}
|
|
</div>
|
|
</div>
|
|
{% endmacro %}
|
|
|
|
{# ===== MAIN TEMPLATE ===== #}
|
|
|
|
<div class="plugin-config-container"
|
|
data-plugin-id="{{ plugin.id }}"
|
|
x-data="{ saving: false, saveError: null, saveSuccess: false }">
|
|
|
|
<div class="border-b border-gray-200 pb-4 mb-6">
|
|
<div class="flex items-center justify-between">
|
|
<div>
|
|
<h2 class="text-lg font-semibold text-gray-900">{{ plugin.name or plugin.id }}</h2>
|
|
<p class="mt-1 text-sm text-gray-600">{{ plugin.description or 'Plugin configuration' }}</p>
|
|
</div>
|
|
<div class="flex items-center space-x-4">
|
|
<button type="button"
|
|
onclick="window.previewPluginNow('{{ plugin.id }}')"
|
|
class="btn bg-blue-600 hover:bg-blue-700 text-white px-3 py-1.5 text-sm rounded-md"
|
|
title="Run this plugin on the display for 60 seconds and open the live preview">
|
|
<i class="fas fa-play mr-1"></i>Preview on display
|
|
</button>
|
|
<label class="flex items-center cursor-pointer">
|
|
<input type="checkbox"
|
|
id="plugin-enabled-{{ plugin.id }}"
|
|
name="enabled"
|
|
value="true"
|
|
{% if plugin.enabled %}checked{% endif %}
|
|
hx-post="/api/v3/plugins/toggle?plugin_id={{ plugin.id }}"
|
|
hx-trigger="change"
|
|
hx-swap="none"
|
|
hx-vals='js:{enabled: document.getElementById("plugin-enabled-{{ plugin.id }}").checked ? "true" : "false"}'
|
|
hx-on::after-request="handleToggleResponse(event, '{{ plugin.id }}')"
|
|
class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded">
|
|
<span class="ml-2 text-sm {% if plugin.enabled %}text-green-600{% else %}text-gray-500{% endif %}">
|
|
{% if plugin.enabled %}Enabled{% else %}Disabled{% endif %}
|
|
</span>
|
|
</label>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<form id="plugin-config-form-{{ plugin.id }}"
|
|
hx-post="/api/v3/plugins/config?plugin_id={{ plugin.id }}"
|
|
hx-trigger="submit"
|
|
hx-swap="none"
|
|
hx-indicator="#save-indicator-{{ plugin.id }}"
|
|
hx-on::before-request="this.querySelector('[type=submit]').disabled = true"
|
|
hx-on::after-request="handleConfigSave(event, '{{ plugin.id }}')"
|
|
onsubmit="return validatePluginConfigForm(this, '{{ plugin.id }}');">
|
|
|
|
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
|
|
{# Plugin Information Panel #}
|
|
<div class="bg-gray-50 rounded-lg p-4">
|
|
<h3 class="text-md font-medium text-gray-900 mb-3">Plugin Information</h3>
|
|
<dl class="space-y-2">
|
|
<div>
|
|
<dt class="text-sm font-medium text-gray-500">Name</dt>
|
|
<dd class="text-sm text-gray-900">{{ plugin.name or plugin.id }}</dd>
|
|
</div>
|
|
<div>
|
|
<dt class="text-sm font-medium text-gray-500">Author</dt>
|
|
<dd class="text-sm text-gray-900">{{ plugin.author or 'Unknown' }}</dd>
|
|
</div>
|
|
{% if plugin.version %}
|
|
<div>
|
|
<dt class="text-sm font-medium text-gray-500">Version</dt>
|
|
<dd class="text-sm text-gray-900">{{ plugin.version }}</dd>
|
|
</div>
|
|
{% endif %}
|
|
{% if plugin.last_commit %}
|
|
<div>
|
|
<dt class="text-sm font-medium text-gray-500">Commit</dt>
|
|
<dd class="text-sm text-gray-900 font-mono">
|
|
{{ plugin.last_commit[:7] if plugin.last_commit|length > 7 else plugin.last_commit }}
|
|
{% if plugin.branch %}
|
|
<span class="text-gray-500">({{ plugin.branch }})</span>
|
|
{% endif %}
|
|
</dd>
|
|
</div>
|
|
{% endif %}
|
|
{% if plugin.category %}
|
|
<div>
|
|
<dt class="text-sm font-medium text-gray-500">Category</dt>
|
|
<dd class="text-sm text-gray-900">{{ plugin.category }}</dd>
|
|
</div>
|
|
{% endif %}
|
|
{% if plugin.tags %}
|
|
<div>
|
|
<dt class="text-sm font-medium text-gray-500">Tags</dt>
|
|
<dd class="flex flex-wrap gap-1 mt-1">
|
|
{% for tag in plugin.tags %}
|
|
<span class="bg-blue-100 text-blue-800 text-xs px-2 py-1 rounded">{{ tag }}</span>
|
|
{% endfor %}
|
|
</dd>
|
|
</div>
|
|
{% endif %}
|
|
</dl>
|
|
|
|
{# On-Demand Controls #}
|
|
<div class="mt-4 pt-4 border-t border-gray-200 space-y-3">
|
|
<div class="flex items-center gap-2">
|
|
<i class="fas fa-bolt text-blue-500"></i>
|
|
<span class="text-sm font-semibold text-gray-900">On-Demand Controls</span>
|
|
</div>
|
|
<div class="flex flex-wrap gap-2">
|
|
<button type="button"
|
|
onclick="runPluginOnDemand('{{ plugin.id }}')"
|
|
class="px-3 py-2 text-sm bg-green-600 hover:bg-green-700 text-white rounded-md flex items-center gap-2 transition-colors">
|
|
<i class="fas fa-play-circle"></i>
|
|
<span>Run On-Demand</span>
|
|
</button>
|
|
<button type="button"
|
|
onclick="stopOnDemand()"
|
|
class="px-3 py-2 text-sm bg-red-600 hover:bg-red-700 text-white rounded-md flex items-center gap-2 transition-colors">
|
|
<i class="fas fa-stop"></i>
|
|
<span>Stop On-Demand</span>
|
|
</button>
|
|
</div>
|
|
{% if not plugin.enabled %}
|
|
<p class="text-xs text-amber-600">Plugin is disabled, but on-demand will temporarily enable it.</p>
|
|
{% endif %}
|
|
</div>
|
|
</div>
|
|
|
|
{# Configuration Form Panel #}
|
|
<div class="bg-gray-50 rounded-lg p-4">
|
|
<h3 class="text-md font-medium text-gray-900 mb-3">Configuration</h3>
|
|
{{ ui.settings_filter("Filter this plugin's settings…") }}
|
|
<div class="space-y-4 max-h-96 overflow-y-auto pr-2">
|
|
{% if schema and schema.properties %}
|
|
{# Use property order if defined, otherwise use natural order #}
|
|
{# Skip 'enabled' field - it's handled by the header toggle #}
|
|
{% set property_order = schema['x-propertyOrder'] if 'x-propertyOrder' in schema else schema.properties.keys()|list %}
|
|
{# Flat (non-object) properties flagged "x-advanced": true are
|
|
grouped into one collapsed "Advanced Settings" section after
|
|
the basic fields. Object-type properties already render as
|
|
their own collapsible sections, so the flag is ignored for
|
|
them. Schemas without the flag render exactly as before. #}
|
|
{% set tiers = namespace(basic=[], advanced=[]) %}
|
|
{% for key in property_order %}
|
|
{% if key in schema.properties and key != 'enabled' %}
|
|
{% set prop = schema.properties[key] %}
|
|
{% set is_object = prop.type is defined and 'object' in prop.type %}
|
|
{% if prop.get('x-advanced') and not is_object %}
|
|
{% set tiers.advanced = tiers.advanced + [key] %}
|
|
{% else %}
|
|
{% set tiers.basic = tiers.basic + [key] %}
|
|
{% endif %}
|
|
{% endif %}
|
|
{% endfor %}
|
|
{% for key in tiers.basic %}
|
|
{% set prop = schema.properties[key] %}
|
|
{% set value = config[key] if key in config else none %}
|
|
{{ render_field(key, prop, value, '', plugin.id) }}
|
|
{% endfor %}
|
|
{% if tiers.advanced %}
|
|
{% set adv_section_id = (plugin.id ~ '-section-advanced-settings')|replace('.', '-')|replace('_', '-') %}
|
|
<div class="nested-section border border-gray-300 rounded-lg mb-4">
|
|
<button type="button"
|
|
class="w-full bg-gray-100 hover:bg-gray-200 px-4 py-3 flex items-center justify-between text-left transition-colors rounded-t-lg"
|
|
aria-controls="{{ adv_section_id }}"
|
|
aria-expanded="false"
|
|
onclick="toggleSection('{{ adv_section_id }}')">
|
|
<div class="flex-1">
|
|
<h4 class="font-semibold text-gray-900">
|
|
<i class="fas fa-sliders-h mr-1 text-gray-500"></i>Advanced Settings ({{ tiers.advanced|length }})
|
|
</h4>
|
|
<p class="text-sm text-gray-600 mt-1">Optional fine-tuning — the defaults work for most setups.</p>
|
|
</div>
|
|
<i id="{{ adv_section_id }}-icon" class="fas fa-chevron-right text-gray-500 transition-transform"></i>
|
|
</button>
|
|
<div id="{{ adv_section_id }}" class="nested-content bg-gray-50 px-4 py-4 space-y-3 hidden" style="display: none;">
|
|
{% for key in tiers.advanced %}
|
|
{% set prop = schema.properties[key] %}
|
|
{% set value = config[key] if key in config else none %}
|
|
{{ render_field(key, prop, value, '', plugin.id) }}
|
|
{% endfor %}
|
|
</div>
|
|
</div>
|
|
{% endif %}
|
|
{% else %}
|
|
{# No schema - render simple form from config #}
|
|
{% if config %}
|
|
{% for key, value in config.items() %}
|
|
{% if key not in ['enabled'] %}
|
|
<div class="form-group mb-4">
|
|
<label class="block text-sm font-medium text-gray-700 mb-1">
|
|
{{ key|replace('_', ' ')|title }}
|
|
</label>
|
|
{% if value is sameas true or value is sameas false %}
|
|
<label class="flex items-center cursor-pointer">
|
|
<input type="checkbox" name="{{ key }}" {% if value %}checked{% endif %}
|
|
class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded">
|
|
<span class="ml-2 text-sm text-gray-600">Enabled</span>
|
|
</label>
|
|
{% elif value is number %}
|
|
<input type="number" name="{{ key }}" value="{{ value }}"
|
|
class="form-input w-full rounded-md border-gray-300 bg-gray-900 text-white placeholder:text-gray-400">
|
|
{% else %}
|
|
<input type="text" name="{{ key }}" value="{{ value }}"
|
|
class="form-input w-full rounded-md border-gray-300 bg-gray-900 text-white placeholder:text-gray-400">
|
|
{% endif %}
|
|
</div>
|
|
{% endif %}
|
|
{% endfor %}
|
|
{% else %}
|
|
<p class="text-gray-500 text-sm">No configuration options available for this plugin.</p>
|
|
{% endif %}
|
|
{% endif %}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
{# Web UI Actions — hide if schema has a dedicated file-manager widget,
|
|
or if every action is marked ui_hidden in the manifest. #}
|
|
{% set has_file_manager_widget = namespace(value=false) %}
|
|
{% for _fk, _fp in schema.get('properties', {}).items() %}
|
|
{% if (_fp.get('x-widget') or _fp.get('x_widget')) in ('json-file-manager', 'plugin-file-manager') %}
|
|
{% set has_file_manager_widget.value = true %}
|
|
{% endif %}
|
|
{% endfor %}
|
|
{% set visible_actions = [] %}
|
|
{% for _a in web_ui_actions %}
|
|
{% if not _a.get('ui_hidden', false) %}
|
|
{% set _ = visible_actions.append(_a) %}
|
|
{% endif %}
|
|
{% endfor %}
|
|
{% if visible_actions and not has_file_manager_widget.value %}
|
|
<div class="mt-6 pt-4 border-t border-gray-200">
|
|
<h3 class="text-md font-medium text-gray-900 mb-3">Plugin Actions</h3>
|
|
{% if visible_actions[0].section_description %}
|
|
<p class="text-sm text-gray-600 mb-4">{{ visible_actions[0].section_description }}</p>
|
|
{% endif %}
|
|
<div class="space-y-3">
|
|
{% for action in visible_actions %}
|
|
{% set action_id = "action-" ~ action.id ~ "-" ~ loop.index0 %}
|
|
{% set status_id = "action-status-" ~ action.id ~ "-" ~ loop.index0 %}
|
|
{% set bg_color = action.color or 'blue' %}
|
|
{% if bg_color == 'green' %}
|
|
{% set bg_class = 'bg-green-50' %}
|
|
{% set border_class = 'border-green-200' %}
|
|
{% set text_class = 'text-green-900' %}
|
|
{% set text_light_class = 'text-green-700' %}
|
|
{% set btn_class = 'bg-green-600 hover:bg-green-700' %}
|
|
{% elif bg_color == 'red' %}
|
|
{% set bg_class = 'bg-red-50' %}
|
|
{% set border_class = 'border-red-200' %}
|
|
{% set text_class = 'text-red-900' %}
|
|
{% set text_light_class = 'text-red-700' %}
|
|
{% set btn_class = 'bg-red-600 hover:bg-red-700' %}
|
|
{% elif bg_color == 'yellow' %}
|
|
{% set bg_class = 'bg-yellow-50' %}
|
|
{% set border_class = 'border-yellow-200' %}
|
|
{% set text_class = 'text-yellow-900' %}
|
|
{% set text_light_class = 'text-yellow-700' %}
|
|
{% set btn_class = 'bg-yellow-600 hover:bg-yellow-700' %}
|
|
{% elif bg_color == 'purple' %}
|
|
{% set bg_class = 'bg-purple-50' %}
|
|
{% set border_class = 'border-purple-200' %}
|
|
{% set text_class = 'text-purple-900' %}
|
|
{% set text_light_class = 'text-purple-700' %}
|
|
{% set btn_class = 'bg-purple-600 hover:bg-purple-700' %}
|
|
{% else %}
|
|
{% set bg_class = 'bg-blue-50' %}
|
|
{% set border_class = 'border-blue-200' %}
|
|
{% set text_class = 'text-blue-900' %}
|
|
{% set text_light_class = 'text-blue-700' %}
|
|
{% set btn_class = 'bg-blue-600 hover:bg-blue-700' %}
|
|
{% endif %}
|
|
<div class="{{ bg_class }} border {{ border_class }} rounded-lg p-4">
|
|
<div class="flex items-center justify-between">
|
|
<div class="flex-1">
|
|
<h4 class="font-medium {{ text_class }} mb-1">
|
|
{% if action.icon %}<i class="{{ action.icon }} mr-2"></i>{% endif %}{{ action.title or action.id }}
|
|
</h4>
|
|
<p class="text-sm {{ text_light_class }}">{{ action.description or '' }}</p>
|
|
</div>
|
|
<button type="button"
|
|
id="{{ action_id }}"
|
|
onclick="executePluginAction('{{ action.id }}', {{ loop.index0 }}, '{{ plugin.id }}')"
|
|
data-plugin-id="{{ plugin.id }}"
|
|
data-action-id="{{ action.id }}"
|
|
class="btn {{ btn_class }} text-white px-4 py-2 rounded-md whitespace-nowrap">
|
|
{% if action.icon %}<i class="{{ action.icon }} mr-2"></i>{% endif %}{{ action.button_text or action.title or action.id }}
|
|
</button>
|
|
</div>
|
|
<div id="{{ status_id }}" class="mt-3 hidden"></div>
|
|
</div>
|
|
{% endfor %}
|
|
</div>
|
|
</div>
|
|
{% endif %}
|
|
|
|
{# Action Buttons #}
|
|
<div class="flex justify-end space-x-3 mt-6 pt-6 border-t border-gray-200">
|
|
<button type="button"
|
|
onclick="refreshPluginConfig('{{ plugin.id }}')"
|
|
class="btn bg-gray-600 hover:bg-gray-700 text-white px-4 py-2 rounded-md">
|
|
<i class="fas fa-sync-alt mr-2"></i>Refresh
|
|
</button>
|
|
<button type="button"
|
|
hx-post="/api/v3/plugins/update?plugin_id={{ plugin.id }}"
|
|
hx-swap="none"
|
|
hx-on::after-request="handlePluginUpdate(event, '{{ plugin.id }}')"
|
|
class="btn bg-yellow-600 hover:bg-yellow-700 text-white px-4 py-2 rounded-md">
|
|
<i class="fas fa-download mr-2"></i>Update
|
|
</button>
|
|
<button type="button"
|
|
onclick="if(confirm('Are you sure you want to uninstall {{ plugin.name or plugin.id }}?')) uninstallPlugin('{{ plugin.id }}')"
|
|
class="btn bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-md">
|
|
<i class="fas fa-trash mr-2"></i>Uninstall
|
|
</button>
|
|
<button type="submit" class="btn bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-md flex items-center">
|
|
<span id="save-indicator-{{ plugin.id }}" class="htmx-indicator mr-2">
|
|
<i class="fas fa-spinner fa-spin"></i>
|
|
</span>
|
|
<i class="fas fa-save mr-2 save-icon"></i>
|
|
<span>Save Configuration</span>
|
|
</button>
|
|
</div>
|
|
</form>
|
|
</div>
|
|
|